context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
using System;
using System.IO;
using System.Threading;
namespace Lucene.Net.Store
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// An interprocess mutex lock.
/// <para/>Typical use might look like:
///
/// <code>
/// var result = Lock.With.NewAnonymous<string>(
/// @lock: directory.MakeLock("my.lock"),
/// lockWaitTimeout: Lock.LOCK_OBTAIN_WAIT_FOREVER,
/// doBody: () =>
/// {
/// //... code to execute while locked ...
/// return "the result";
/// }).Run();
/// </code>
/// </summary>
/// <seealso cref="Directory.MakeLock(string)"/>
public abstract class Lock : IDisposable
{
/// <summary>
/// How long <see cref="Obtain(long)"/> waits, in milliseconds,
/// in between attempts to acquire the lock.
/// </summary>
public static long LOCK_POLL_INTERVAL = 1000;
/// <summary>
/// Pass this value to <see cref="Obtain(long)"/> to try
/// forever to obtain the lock.
/// </summary>
public const long LOCK_OBTAIN_WAIT_FOREVER = -1;
/// <summary>
/// Creates a new instance with the ability to specify the <see cref="With{T}.DoBody()"/> method
/// through the <paramref name="doBody"/> argument
/// <para/>
/// Simple example:
/// <code>
/// var result = Lock.With.NewAnonymous<string>(
/// @lock: directory.MakeLock("my.lock"),
/// lockWaitTimeout: Lock.LOCK_OBTAIN_WAIT_FOREVER,
/// doBody: () =>
/// {
/// //... code to execute while locked ...
/// return "the result";
/// }).Run();
/// </code>
/// <para/>
/// The result of the operation is the value that is returned from <paramref name="doBody"/>
/// (i.e. () => { return "the result"; }). The type of <typeparam name="T"/> determines the
/// return type of the operation.
/// </summary>
/// <param name="lock"> the <see cref="Lock"/> instance to use </param>
/// <param name="lockWaitTimeout"> length of time to wait in
/// milliseconds or
/// <see cref="LOCK_OBTAIN_WAIT_FOREVER"/> to retry forever </param>
/// <param name="doBody"> a delegate method that </param>
/// <returns>The value that is returned from the <paramref name="doBody"/> delegate method (i.e. () => { return theObject; })</returns>
public static With<T> NewAnonymous<T>(Lock @lock, int lockWaitTimeout, Func<T> doBody)
{
return new AnonymousWith<T>(@lock, lockWaitTimeout, doBody);
}
/// <summary>
/// Attempts to obtain exclusive access and immediately return
/// upon success or failure. Use <see cref="Dispose()"/> to
/// release the lock. </summary>
/// <returns> true iff exclusive access is obtained </returns>
public abstract bool Obtain();
/// <summary>
/// If a lock obtain called, this failureReason may be set
/// with the "root cause" <see cref="Exception"/> as to why the lock was
/// not obtained.
/// </summary>
protected internal Exception FailureReason { get; set; }
/// <summary>
/// Attempts to obtain an exclusive lock within amount of
/// time given. Polls once per <see cref="LOCK_POLL_INTERVAL"/>
/// (currently 1000) milliseconds until <paramref name="lockWaitTimeout"/> is
/// passed.
/// </summary>
/// <param name="lockWaitTimeout"> length of time to wait in
/// milliseconds or
/// <see cref="LOCK_OBTAIN_WAIT_FOREVER"/> to retry forever </param>
/// <returns> <c>true</c> if lock was obtained </returns>
/// <exception cref="LockObtainFailedException"> if lock wait times out </exception>
/// <exception cref="ArgumentException"> if <paramref name="lockWaitTimeout"/> is
/// out of bounds </exception>
/// <exception cref="IOException"> if <see cref="Obtain()"/> throws <see cref="IOException"/> </exception>
public bool Obtain(long lockWaitTimeout)
{
FailureReason = null;
bool locked = Obtain();
if (lockWaitTimeout < 0 && lockWaitTimeout != LOCK_OBTAIN_WAIT_FOREVER)
{
throw new ArgumentException("lockWaitTimeout should be LOCK_OBTAIN_WAIT_FOREVER or a non-negative number (got " + lockWaitTimeout + ")");
}
long maxSleepCount = lockWaitTimeout / LOCK_POLL_INTERVAL;
long sleepCount = 0;
while (!locked)
{
if (lockWaitTimeout != LOCK_OBTAIN_WAIT_FOREVER && sleepCount++ >= maxSleepCount)
{
string reason = "Lock obtain timed out: " + this.ToString();
if (FailureReason != null)
{
reason += ": " + FailureReason;
}
LockObtainFailedException e = new LockObtainFailedException(reason);
e = FailureReason != null
? new LockObtainFailedException(reason, FailureReason)
: new LockObtainFailedException(reason);
throw e;
}
//#if FEATURE_THREAD_INTERRUPT
// try
// {
//#endif
Thread.Sleep(TimeSpan.FromMilliseconds(LOCK_POLL_INTERVAL));
//#if FEATURE_THREAD_INTERRUPT // LUCENENET NOTE: Senseless to catch and rethrow the same exception type
// }
// catch (ThreadInterruptedException ie)
// {
// throw new ThreadInterruptedException(ie.ToString(), ie);
// }
//#endif
locked = Obtain();
}
return locked;
}
/// <summary>
/// Releases exclusive access. </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases exclusive access. </summary>
protected abstract void Dispose(bool disposing);
/// <summary>
/// Returns <c>true</c> if the resource is currently locked. Note that one must
/// still call <see cref="Obtain()"/> before using the resource.
/// </summary>
public abstract bool IsLocked();
/// <summary>
/// Utility class for executing code with exclusive access. </summary>
public abstract class With<T> // LUCENENET specific - made generic so we don't need to deal with casting
{
private Lock @lock;
private long lockWaitTimeout;
/// <summary>
/// Constructs an executor that will grab the named <paramref name="lock"/>. </summary>
/// <param name="lock"> the <see cref="Lock"/> instance to use </param>
/// <param name="lockWaitTimeout"> length of time to wait in
/// milliseconds or
/// <see cref="LOCK_OBTAIN_WAIT_FOREVER"/> to retry forever </param>
public With(Lock @lock, long lockWaitTimeout)
{
this.@lock = @lock;
this.lockWaitTimeout = lockWaitTimeout;
}
/// <summary>
/// Code to execute with exclusive access. </summary>
protected abstract T DoBody();
/// <summary>
/// Calls <see cref="DoBody"/> while <i>lock</i> is obtained. Blocks if lock
/// cannot be obtained immediately. Retries to obtain lock once per second
/// until it is obtained, or until it has tried ten times. Lock is released when
/// <see cref="DoBody"/> exits. </summary>
/// <exception cref="LockObtainFailedException"> if lock could not
/// be obtained </exception>
/// <exception cref="IOException"> if <see cref="Lock.Obtain()"/> throws <see cref="IOException"/> </exception>
public virtual T Run()
{
bool locked = false;
try
{
locked = @lock.Obtain(lockWaitTimeout);
return DoBody();
}
finally
{
if (locked)
{
@lock.Dispose();
}
}
}
}
/// <summary>
/// LUCENENET specific class to simulate the anonymous creation of a With class in Java
/// by using deletate methods.
/// </summary>
private class AnonymousWith<T> : With<T>
{
private readonly Func<T> doBody;
public AnonymousWith(Lock @lock, int lockWaitTimeout, Func<T> doBody)
: base(@lock, lockWaitTimeout)
{
this.doBody = doBody ?? throw new ArgumentNullException(nameof(doBody));
}
protected override T DoBody()
{
return doBody();
}
}
}
}
| |
// 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.Composition.Diagnostics;
using System.ComponentModel.Composition.Primitives;
using System.ComponentModel.Composition.ReflectionModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using Microsoft.Internal;
using Microsoft.Internal.Collections;
namespace System.ComponentModel.Composition.Hosting
{
public partial class CatalogExportProvider : ExportProvider, IDisposable
{
private class InnerCatalogExportProvider : ExportProvider
{
private CatalogExportProvider _outerExportProvider;
public InnerCatalogExportProvider(CatalogExportProvider outerExportProvider)
{
if(outerExportProvider == null)
{
throw new ArgumentNullException(nameof(outerExportProvider));
}
_outerExportProvider = outerExportProvider;
}
protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition)
{
return _outerExportProvider.InternalGetExportsCore(definition, atomicComposition);
}
}
private readonly CompositionLock _lock;
private Dictionary<ComposablePartDefinition, CatalogPart> _activatedParts = new Dictionary<ComposablePartDefinition, CatalogPart>();
private HashSet<ComposablePartDefinition> _rejectedParts = new HashSet<ComposablePartDefinition>();
private ConditionalWeakTable<object, List<ComposablePart>> _gcRoots;
private HashSet<IDisposable> _partsToDispose = new HashSet<IDisposable>();
private ComposablePartCatalog _catalog;
private volatile bool _isDisposed = false;
private volatile bool _isRunning = false;
private bool _disableSilentRejection = false;
private ExportProvider _sourceProvider;
private ImportEngine _importEngine;
private CompositionOptions _compositionOptions;
private ExportProvider _innerExportProvider;
/// <summary>
/// Initializes a new instance of the <see cref="CatalogExportProvider"/> class.
/// </summary>
/// <param name="catalog">
/// The <see cref="ComposablePartCatalog"/> that the <see cref="CatalogExportProvider"/>
/// uses to produce <see cref="Export"/> objects.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="catalog"/> is <see langword="null"/>.
/// </exception>
public CatalogExportProvider(ComposablePartCatalog catalog)
: this(catalog, CompositionOptions.Default)
{
}
public CatalogExportProvider(ComposablePartCatalog catalog, bool isThreadSafe)
: this(catalog, isThreadSafe ? CompositionOptions.IsThreadSafe : CompositionOptions.Default)
{
}
public CatalogExportProvider(ComposablePartCatalog catalog, CompositionOptions compositionOptions)
{
Requires.NotNull(catalog, nameof(catalog));
if (compositionOptions > (CompositionOptions.DisableSilentRejection | CompositionOptions.IsThreadSafe | CompositionOptions.ExportCompositionService))
{
throw new ArgumentOutOfRangeException(nameof(compositionOptions));
}
_catalog = catalog;
_compositionOptions = compositionOptions;
var notifyCatalogChanged = _catalog as INotifyComposablePartCatalogChanged;
if (notifyCatalogChanged != null)
{
notifyCatalogChanged.Changing += OnCatalogChanging;
}
CompositionScopeDefinition scopeDefinition = _catalog as CompositionScopeDefinition;
if (scopeDefinition != null)
{
_innerExportProvider = new AggregateExportProvider(new ScopeManager(this, scopeDefinition), new InnerCatalogExportProvider(this));
}
else
{
_innerExportProvider = new InnerCatalogExportProvider(this);
}
_lock = new CompositionLock(compositionOptions.HasFlag(CompositionOptions.IsThreadSafe));
_disableSilentRejection = compositionOptions.HasFlag(CompositionOptions.DisableSilentRejection);
}
/// <summary>
/// Gets the composable part catalog that the provider users to
/// produce exports.
/// </summary>
/// <value>
/// The <see cref="ComposablePartCatalog"/> that the
/// <see cref="CatalogExportProvider"/>
/// uses to produce <see cref="Export"/> objects.
/// </value>
/// <exception cref="ObjectDisposedException">
/// The <see cref="CompositionContainer"/> has been disposed of.
/// </exception>
public ComposablePartCatalog Catalog
{
get
{
ThrowIfDisposed();
Contract.Ensures(Contract.Result<ComposablePartCatalog>() != null);
return _catalog;
}
}
/// <summary>
/// Gets the export provider which provides the provider access to additional
/// exports.
/// </summary>
/// <value>
/// The <see cref="ExportProvider"/> which provides the
/// <see cref="CatalogExportProvider"/> access to additional
/// <see cref="Export"/> objects. The default is <see langword="null"/>.
/// </value>
/// <exception cref="ArgumentNullException">
/// <paramref name="value"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="InvalidOperationException">
/// This property has already been set.
/// <para>
/// -or-
/// </para>
/// The methods on the <see cref="CatalogExportProvider"/>
/// have already been accessed.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The <see cref="CatalogExportProvider"/> has been disposed of.
/// </exception>
/// <remarks>
/// This property must be set before accessing any methods on the
/// <see cref="CatalogExportProvider"/>.
/// </remarks>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "EnsureCanSet ensures that the property is set only once, Dispose is not required")]
public ExportProvider SourceProvider
{
get
{
ThrowIfDisposed();
using (_lock.LockStateForRead())
{
return _sourceProvider;
}
}
set
{
ThrowIfDisposed();
Requires.NotNull(value, nameof(value));
ImportEngine newImportEngine = null;
AggregateExportProvider aggregateExportProvider = null;
ExportProvider sourceProvider = value;
bool isThrowing = true;
try
{
newImportEngine = new ImportEngine(sourceProvider, _compositionOptions);
sourceProvider.ExportsChanging += OnExportsChangingInternal;
using (_lock.LockStateForWrite())
{
EnsureCanSet(_sourceProvider);
_sourceProvider = sourceProvider;
_importEngine = newImportEngine;
isThrowing = false;
}
}
finally
{
if (isThrowing)
{
sourceProvider.ExportsChanging -= OnExportsChangingInternal;
newImportEngine.Dispose();
if (aggregateExportProvider != null)
{
aggregateExportProvider.Dispose();
}
}
}
}
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (!_isDisposed)
{
//Note: We do not dispose _lock on dispose because DisposePart needs it to check isDisposed state
// to eliminate race conditions between it and Dispose
INotifyComposablePartCatalogChanged catalogToUnsubscribeFrom = null;
HashSet<IDisposable> partsToDispose = null;
ImportEngine importEngine = null;
ExportProvider sourceProvider = null;
AggregateExportProvider aggregateExportProvider = null;
try
{
using (_lock.LockStateForWrite())
{
if (!_isDisposed)
{
catalogToUnsubscribeFrom = _catalog as INotifyComposablePartCatalogChanged;
_catalog = null;
aggregateExportProvider = _innerExportProvider as AggregateExportProvider;
_innerExportProvider = null;
sourceProvider = _sourceProvider;
_sourceProvider = null;
importEngine = _importEngine;
_importEngine = null;
partsToDispose = _partsToDispose;
_gcRoots = null;
_isDisposed = true;
}
}
}
finally
{
if (catalogToUnsubscribeFrom != null)
{
catalogToUnsubscribeFrom.Changing -= OnCatalogChanging;
}
if (aggregateExportProvider != null)
{
aggregateExportProvider.Dispose();
}
if (sourceProvider != null)
{
sourceProvider.ExportsChanging -= OnExportsChangingInternal;
}
if (importEngine != null)
{
importEngine.Dispose();
}
if (partsToDispose != null)
{
foreach (var part in partsToDispose)
{
part.Dispose();
}
}
}
}
}
}
/// <summary>
/// Returns all exports that match the conditions of the specified import.
/// </summary>
/// <param name="definition">The <see cref="ImportDefinition"/> that defines the conditions of the
/// <see cref="Export"/> to get.</param>
/// <returns></returns>
/// <result>
/// An <see cref="IEnumerable{T}"/> of <see cref="Export"/> objects that match
/// the conditions defined by <see cref="ImportDefinition"/>, if found; otherwise, an
/// empty <see cref="IEnumerable{T}"/>.
/// </result>
/// <remarks>
/// <note type="inheritinfo">
/// The implementers should not treat the cardinality-related mismatches as errors, and are not
/// expected to throw exceptions in those cases.
/// For instance, if the import requests exactly one export and the provider has no matching exports or more than one,
/// it should return an empty <see cref="IEnumerable{T}"/> of <see cref="Export"/>.
/// </note>
/// </remarks>
protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition)
{
ThrowIfDisposed();
EnsureRunning();
if (_innerExportProvider == null)
{
throw new Exception(SR.Diagnostic_InternalExceptionMessage);
}
IEnumerable<Export> exports;
_innerExportProvider.TryGetExports(definition, atomicComposition, out exports);
return exports;
}
private IEnumerable<Export> InternalGetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition)
{
ThrowIfDisposed();
EnsureRunning();
// Use the version of the catalog appropriate to this atomicComposition
ComposablePartCatalog currentCatalog = atomicComposition.GetValueAllowNull(_catalog);
IPartCreatorImportDefinition partCreatorDefinition = definition as IPartCreatorImportDefinition;
bool isExportFactory = false;
if (partCreatorDefinition != null)
{
definition = partCreatorDefinition.ProductImportDefinition;
isExportFactory = true;
}
CreationPolicy importPolicy = definition.GetRequiredCreationPolicy();
List<Export> exports = new List<Export>();
bool ensureRejection = EnsureRejection(atomicComposition);
foreach (var partDefinitionAndExportDefinition in currentCatalog.GetExports(definition))
{
bool isPartRejected = ensureRejection && IsRejected(partDefinitionAndExportDefinition.Item1, atomicComposition);
if (!isPartRejected)
{
exports.Add(CreateExport(partDefinitionAndExportDefinition.Item1, partDefinitionAndExportDefinition.Item2, isExportFactory, importPolicy));
}
}
return exports;
}
private Export CreateExport(ComposablePartDefinition partDefinition, ExportDefinition exportDefinition, bool isExportFactory, CreationPolicy importPolicy)
{
if (isExportFactory)
{
return new PartCreatorExport(this,
partDefinition,
exportDefinition);
}
else
{
return CatalogExport.CreateExport(this,
partDefinition,
exportDefinition,
importPolicy);
}
}
private void OnExportsChangingInternal(object sender, ExportsChangeEventArgs e)
{
UpdateRejections(e.AddedExports.Concat(e.RemovedExports), e.AtomicComposition);
}
private static ExportDefinition[] GetExportsFromPartDefinitions(IEnumerable<ComposablePartDefinition> partDefinitions)
{
List<ExportDefinition> exports = new List<ExportDefinition>();
foreach (var partDefinition in partDefinitions)
{
foreach (var export in partDefinition.ExportDefinitions)
{
exports.Add(export);
// While creating a PartCreatorExportDefinition for every changed definition may not be the most
// efficient way to do this the PartCreatorExportDefinition is very efficient and doesn't do any
// real work unless its metadata is pulled on. If this turns out to be a bottleneck then we
// will need to start tracking all the PartCreator's we hand out and only send those which we
// have handed out. In fact we could do the same thing for all the Exports if we wished but
// that requires a cache management which we don't want to do at this point.
exports.Add(new PartCreatorExportDefinition(export));
}
}
return exports.ToArray();
}
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
private void OnCatalogChanging(object sender, ComposablePartCatalogChangeEventArgs e)
{
using (var atomicComposition = new AtomicComposition(e.AtomicComposition))
{
// Save the preview catalog to use in place of the original while handling
// this event
atomicComposition.SetValue(_catalog,
new CatalogChangeProxy(_catalog, e.AddedDefinitions, e.RemovedDefinitions));
IEnumerable<ExportDefinition> addedExports = GetExportsFromPartDefinitions(e.AddedDefinitions);
IEnumerable<ExportDefinition> removedExports = GetExportsFromPartDefinitions(e.RemovedDefinitions);
// Remove any parts based on eliminated definitions (in a atomicComposition-friendly
// fashion)
foreach (var definition in e.RemovedDefinitions)
{
CatalogPart removedPart = null;
bool removed = false;
using (_lock.LockStateForRead())
{
removed = _activatedParts.TryGetValue(definition, out removedPart);
}
if (removed)
{
var capturedDefinition = definition;
DisposePart(null, removedPart, atomicComposition);
atomicComposition.AddCompleteActionAllowNull(() =>
{
using (_lock.LockStateForWrite())
{
_activatedParts.Remove(capturedDefinition);
}
});
}
}
UpdateRejections(addedExports.ConcatAllowingNull(removedExports), atomicComposition);
OnExportsChanging(
new ExportsChangeEventArgs(addedExports, removedExports, atomicComposition));
atomicComposition.AddCompleteAction(() => OnExportsChanged(
new ExportsChangeEventArgs(addedExports, removedExports, null)));
atomicComposition.Complete();
}
}
private CatalogPart GetComposablePart(ComposablePartDefinition partDefinition, bool isSharedPart)
{
ThrowIfDisposed();
EnsureRunning();
CatalogPart catalogPart = null;
if (isSharedPart)
{
catalogPart = GetSharedPart(partDefinition);
}
else
{
ComposablePart part = partDefinition.CreatePart();
catalogPart = new CatalogPart(part);
IDisposable disposablePart = part as IDisposable;
if (disposablePart != null)
{
using (_lock.LockStateForWrite())
{
_partsToDispose.Add(disposablePart);
}
}
}
return catalogPart;
}
private CatalogPart GetSharedPart(ComposablePartDefinition partDefinition)
{
CatalogPart catalogPart = null;
// look up the part
using (_lock.LockStateForRead())
{
if (_activatedParts.TryGetValue(partDefinition, out catalogPart))
{
return catalogPart;
}
}
// create a part outside of the lock
ComposablePart newPart = partDefinition.CreatePart();
IDisposable disposableNewPart = newPart as IDisposable;
using (_lock.LockStateForWrite())
{
// check if the part is still not there
if (!_activatedParts.TryGetValue(partDefinition, out catalogPart))
{
catalogPart = new CatalogPart(newPart);
_activatedParts.Add(partDefinition, catalogPart);
if (disposableNewPart != null)
{
_partsToDispose.Add(disposableNewPart);
}
// indiacate the the part has been added
newPart = null;
disposableNewPart = null;
}
}
// if disposableNewPart != null, this means we have created a new instance of something disposable and not used it
// Dispose of it now
if (disposableNewPart != null)
{
disposableNewPart.Dispose();
}
return catalogPart;
}
private object GetExportedValue(CatalogPart part, ExportDefinition export, bool isSharedPart)
{
ThrowIfDisposed();
EnsureRunning();
if (part == null)
{
throw new ArgumentNullException(nameof(part));
}
if (export == null)
{
throw new ArgumentNullException(nameof(export));
}
// We don't protect against thread racing here, as "importsSatisfied" is merely an optimization
// if two threads satisfy imports twice, the results is the same, just the perf hit is heavier.
bool importsSatisfied = part.ImportsSatisfied;
ImportEngine importEngine = importsSatisfied ? null : _importEngine;
object exportedValue = CompositionServices.GetExportedValueFromComposedPart(
importEngine, part.Part, export);
if (!importsSatisfied)
{
// and set "ImportsSatisfied" to true
part.ImportsSatisfied = true;
}
// Only hold conditional references for recomposable non-shared parts because we are
// already holding strong references to the shared parts.
if (exportedValue != null && !isSharedPart && part.Part.IsRecomposable())
{
PreventPartCollection(exportedValue, part.Part);
}
return exportedValue;
}
private void ReleasePart(object exportedValue, CatalogPart catalogPart, AtomicComposition atomicComposition)
{
ThrowIfDisposed();
EnsureRunning();
DisposePart(exportedValue, catalogPart, atomicComposition);
}
private void DisposePart(object exportedValue, CatalogPart catalogPart, AtomicComposition atomicComposition)
{
if (catalogPart == null)
{
throw new ArgumentNullException(nameof(catalogPart));
}
if (_isDisposed)
return;
ImportEngine importEngine = null;
using (_lock.LockStateForWrite())
{
if (_isDisposed)
return;
importEngine = _importEngine;
}
if (importEngine != null)
{
importEngine.ReleaseImports(catalogPart.Part, atomicComposition);
}
if (exportedValue != null)
{
atomicComposition.AddCompleteActionAllowNull(() =>
{
AllowPartCollection(exportedValue);
});
}
IDisposable diposablePart = catalogPart.Part as IDisposable;
if (diposablePart != null)
{
atomicComposition.AddCompleteActionAllowNull(() =>
{
bool removed = false;
if (_isDisposed)
return;
using (_lock.LockStateForWrite())
{
if (_isDisposed)
return;
removed = _partsToDispose.Remove(diposablePart);
}
if (removed)
{
diposablePart.Dispose();
}
});
}
}
private void PreventPartCollection(object exportedValue, ComposablePart part)
{
if (exportedValue == null)
{
throw new ArgumentNullException(nameof(exportedValue));
}
if (part == null)
{
throw new ArgumentNullException(nameof(part));
}
using (_lock.LockStateForWrite())
{
List<ComposablePart> partList;
ConditionalWeakTable<object, List<ComposablePart>> gcRoots = _gcRoots;
if (gcRoots == null)
{
gcRoots = new ConditionalWeakTable<object, List<ComposablePart>>();
}
if (!gcRoots.TryGetValue(exportedValue, out partList))
{
partList = new List<ComposablePart>();
gcRoots.Add(exportedValue, partList);
}
partList.Add(part);
if (_gcRoots == null)
{
Thread.MemoryBarrier();
_gcRoots = gcRoots;
}
}
}
private void AllowPartCollection(object gcRoot)
{
if (_gcRoots != null)
{
using (_lock.LockStateForWrite())
{
_gcRoots.Remove(gcRoot);
}
}
}
private bool IsRejected(ComposablePartDefinition definition, AtomicComposition atomicComposition)
{
// Check to see if we're currently working on the definition in question.
// Recursive queries always answer optimistically, as if the definition hasn't
// been rejected - because if it is we can discard all decisions that were based
// on the faulty assumption in the first place.
var forceRejectionTest = false;
if (atomicComposition != null)
{
AtomicCompositionQueryState state = QueryPartState(atomicComposition, definition);
switch (state)
{
case AtomicCompositionQueryState.TreatAsRejected:
return true;
case AtomicCompositionQueryState.TreatAsValidated:
return false;
case AtomicCompositionQueryState.NeedsTesting:
forceRejectionTest = true;
break;
default:
if (state != AtomicCompositionQueryState.Unknown)
{
throw new Exception(SR.Diagnostic_InternalExceptionMessage);
}
// Need to do the work to determine the state
break;
}
}
if (!forceRejectionTest)
{
// Next, anything that has been activated is not rejected
using (_lock.LockStateForRead())
{
if (_activatedParts.ContainsKey(definition))
{
return false;
}
// Last stop before doing the hard work: check a specific registry of rejected parts
if (_rejectedParts.Contains(definition))
{
return true;
}
}
}
// Determine whether or not the definition's imports can be satisfied
return DetermineRejection(definition, atomicComposition);
}
private bool EnsureRejection(AtomicComposition atomicComposition)
{
return !(_disableSilentRejection && (atomicComposition == null));
}
private bool DetermineRejection(ComposablePartDefinition definition, AtomicComposition parentAtomicComposition)
{
ChangeRejectedException exception = null;
// if there is no active atomic composition and rejection is disabled, there's no need to do any of the below
if (!EnsureRejection(parentAtomicComposition))
{
return false;
}
using (var localAtomicComposition = new AtomicComposition(parentAtomicComposition))
{
// The part definition we're currently working on is treated optimistically
// as if we know it hasn't been rejected. This handles recursion, and if we
// later decide that it has been rejected we'll discard all nested progress so
// all side-effects of the mistake are erased.
//
// Note that this means that recursive failures that would be detected by the
// import engine are not discovered by rejection currently. Loops among
// prerequisites, runaway import chains involving factories, and prerequisites
// that cannot be fully satisfied still result in runtime errors. Doing
// otherwise would be possible but potentially expensive - and could be a v2
// improvement if deemed worthwhile.
UpdateAtomicCompositionQueryForPartEquals(localAtomicComposition,
definition, AtomicCompositionQueryState.TreatAsValidated);
var newPart = definition.CreatePart();
try
{
_importEngine.PreviewImports(newPart, localAtomicComposition);
// Reuse the partially-fleshed out part the next time we need a shared
// instance to keep the expense of pre-validation to a minimum. Note that
// _activatedParts holds references to both shared and non-shared parts.
// The non-shared parts will only be used for rejection purposes only but
// the shared parts will be handed out when requested via GetExports as
// well as be used for rejection purposes.
localAtomicComposition.AddCompleteActionAllowNull(() =>
{
using (_lock.LockStateForWrite())
{
if (!_activatedParts.ContainsKey(definition))
{
_activatedParts.Add(definition, new CatalogPart(newPart));
IDisposable newDisposablePart = newPart as IDisposable;
if (newDisposablePart != null)
{
_partsToDispose.Add(newDisposablePart);
}
}
}
});
// Success! Complete any recursive work that was conditioned on this part's validation
localAtomicComposition.Complete();
return false;
}
catch (ChangeRejectedException ex)
{
exception = ex;
}
}
// If we've reached this point then this part has been rejected so we need to
// record the rejection in our parent composition or execute it immediately if
// one doesn't exist.
parentAtomicComposition.AddCompleteActionAllowNull(() =>
{
using (_lock.LockStateForWrite())
{
_rejectedParts.Add(definition);
}
CompositionTrace.PartDefinitionRejected(definition, exception);
});
if (parentAtomicComposition != null)
{
UpdateAtomicCompositionQueryForPartEquals(parentAtomicComposition,
definition, AtomicCompositionQueryState.TreatAsRejected);
}
return true;
}
private void UpdateRejections(IEnumerable<ExportDefinition> changedExports, AtomicComposition atomicComposition)
{
using (var localAtomicComposition = new AtomicComposition(atomicComposition))
{
// Reconsider every part definition that has been previously
// rejected to see if any of them can be added back.
var affectedRejections = new HashSet<ComposablePartDefinition>();
ComposablePartDefinition[] rejectedParts;
using (_lock.LockStateForRead())
{
rejectedParts = _rejectedParts.ToArray();
}
foreach (var definition in rejectedParts)
{
if (QueryPartState(localAtomicComposition, definition) == AtomicCompositionQueryState.TreatAsValidated)
{
continue;
}
foreach (var import in definition.ImportDefinitions.Where(ImportEngine.IsRequiredImportForPreview))
{
if (changedExports.Any(export => import.IsConstraintSatisfiedBy(export)))
{
affectedRejections.Add(definition);
break;
}
}
}
UpdateAtomicCompositionQueryForPartInHashSet(localAtomicComposition,
affectedRejections, AtomicCompositionQueryState.NeedsTesting);
// Determine if any of the resurrectable parts is now available so that we can
// notify listeners of the exact changes to exports
var resurrectedExports = new List<ExportDefinition>();
foreach (var partDefinition in affectedRejections)
{
if (!IsRejected(partDefinition, localAtomicComposition))
{
// Notify listeners of the newly available exports and
// prepare to remove the rejected part from the list of rejections
resurrectedExports.AddRange(partDefinition.ExportDefinitions);
// Capture the local so that the closure below refers to the current definition
// in the loop and not the value of 'partDefinition' when the closure executes
var capturedPartDefinition = partDefinition;
localAtomicComposition.AddCompleteAction(() =>
{
using (_lock.LockStateForWrite())
{
_rejectedParts.Remove(capturedPartDefinition);
}
CompositionTrace.PartDefinitionResurrected(capturedPartDefinition);
});
}
}
// Notify anyone sourcing exports that the resurrected exports have appeared
if (resurrectedExports.Any())
{
OnExportsChanging(
new ExportsChangeEventArgs(resurrectedExports, Array.Empty<ExportDefinition>(), localAtomicComposition));
localAtomicComposition.AddCompleteAction(() => OnExportsChanged(
new ExportsChangeEventArgs(resurrectedExports, Array.Empty<ExportDefinition>(), null)));
}
localAtomicComposition.Complete();
}
}
[DebuggerStepThrough]
private void ThrowIfDisposed()
{
if (_isDisposed)
{
throw ExceptionBuilder.CreateObjectDisposed(this);
}
}
/// <summary>
/// EnsureCanRun must be called from within a lock.
/// </summary>
[DebuggerStepThrough]
private void EnsureCanRun()
{
if ((_sourceProvider == null) || (_importEngine == null))
{
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, SR.ObjectMustBeInitialized, "SourceProvider")); // NOLOC
}
}
[DebuggerStepThrough]
private void EnsureRunning()
{
if (!_isRunning)
{
using (_lock.LockStateForWrite())
{
if (!_isRunning)
{
EnsureCanRun();
_isRunning = true;
}
}
}
}
/// <summary>
/// EnsureCanSet<T> must be called from within a lock.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="currentValue"></param>
[DebuggerStepThrough]
private void EnsureCanSet<T>(T currentValue)
where T : class
{
if ((_isRunning) || (currentValue != null))
{
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, SR.ObjectAlreadyInitialized));
}
}
private AtomicCompositionQueryState QueryPartState(AtomicComposition atomicComposition, ComposablePartDefinition definition)
{
PartQueryStateNode node = GetPartQueryStateNode(atomicComposition);
if (node == null)
{
return AtomicCompositionQueryState.Unknown;
}
else
{
return node.GetQueryState(definition);
}
}
private PartQueryStateNode GetPartQueryStateNode(AtomicComposition atomicComposition)
{
PartQueryStateNode node;
atomicComposition.TryGetValue(this, out node);
return node;
}
private void UpdateAtomicCompositionQueryForPartEquals(
AtomicComposition atomicComposition,
ComposablePartDefinition part,
AtomicCompositionQueryState state)
{
PartQueryStateNode previousNode = GetPartQueryStateNode(atomicComposition);
atomicComposition.SetValue(this, new PartEqualsQueryStateNode(part, previousNode, state));
}
private void UpdateAtomicCompositionQueryForPartInHashSet(
AtomicComposition atomicComposition,
HashSet<ComposablePartDefinition> hashset,
AtomicCompositionQueryState state)
{
PartQueryStateNode previousNode = GetPartQueryStateNode(atomicComposition);
atomicComposition.SetValue(this, new PartInHashSetQueryStateNode(hashset, previousNode, state));
}
private enum AtomicCompositionQueryState
{
Unknown,
TreatAsRejected,
TreatAsValidated,
NeedsTesting
};
private abstract class PartQueryStateNode
{
private readonly PartQueryStateNode _previousNode;
private readonly AtomicCompositionQueryState _state;
protected PartQueryStateNode(PartQueryStateNode previousNode, AtomicCompositionQueryState state)
{
_previousNode = previousNode;
_state = state;
}
protected abstract bool IsMatchingDefinition(ComposablePartDefinition part, int partHashCode);
public AtomicCompositionQueryState GetQueryState(ComposablePartDefinition definition)
{
int hashCode = definition.GetHashCode();
PartQueryStateNode node = this;
do
{
if (node.IsMatchingDefinition(definition, hashCode))
{
return node._state;
}
node = node._previousNode;
}
while (node != null);
return AtomicCompositionQueryState.Unknown;
}
}
private class PartEqualsQueryStateNode : PartQueryStateNode
{
private ComposablePartDefinition _part;
private int _hashCode;
public PartEqualsQueryStateNode(ComposablePartDefinition part, PartQueryStateNode previousNode, AtomicCompositionQueryState state) :
base(previousNode, state)
{
_part = part;
_hashCode = part.GetHashCode();
}
protected override bool IsMatchingDefinition(ComposablePartDefinition part, int partHashCode)
{
if (partHashCode != _hashCode)
{
return false;
}
return _part.Equals(part);
}
}
private class PartInHashSetQueryStateNode : PartQueryStateNode
{
private HashSet<ComposablePartDefinition> _parts;
public PartInHashSetQueryStateNode(HashSet<ComposablePartDefinition> parts, PartQueryStateNode previousNode, AtomicCompositionQueryState state) :
base(previousNode, state)
{
_parts = parts;
}
protected override bool IsMatchingDefinition(ComposablePartDefinition part, int partHashCode)
{
return _parts.Contains(part);
}
}
private class CatalogPart
{
private volatile bool _importsSatisfied = false;
public CatalogPart(ComposablePart part)
{
Part = part;
}
public ComposablePart Part { get; private set; }
public bool ImportsSatisfied
{
get
{
return _importsSatisfied;
}
set
{
_importsSatisfied = value;
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using AutoMapper;
using Moq;
using NUnit.Framework;
using ReMi.Common.Constants.ReleaseExecution;
using ReMi.Common.Utils;
using ReMi.Common.Utils.Repository;
using ReMi.TestUtils.UnitTests;
using ReMi.DataAccess.BusinessEntityGateways.ReleaseExecution;
using ReMi.DataAccess.Exceptions;
using ReMi.DataAccess.Exceptions.ReleaseExecution;
using ReMi.DataEntities.Auth;
using ReMi.DataEntities.Metrics;
using ReMi.DataEntities.ReleaseCalendar;
using SignOff = ReMi.DataEntities.ReleaseExecution.SignOff;
namespace ReMi.DataAccess.Tests.ReleaseExecution
{
public class SignOffGatewayTests : TestClassFor<SignOffGateway>
{
private Mock<IRepository<SignOff>> _signOffRepositoryMock;
private Mock<IRepository<ReleaseWindow>> _releaseWindowRepositoryMock;
private Mock<IRepository<Account>> _accountRepositoryMock;
private Mock<IRepository<Metric>> _metricsRepositoryMock;
private Mock<IMappingEngine> _mapperMock;
private List<SignOff> _signOffs;
private List<ReleaseWindow> _releaseWindows;
private List<Account> _accounts;
protected override SignOffGateway ConstructSystemUnderTest()
{
return new SignOffGateway
{
SignOffRepository = _signOffRepositoryMock.Object,
ReleaseWindowRepository = _releaseWindowRepositoryMock.Object,
AccountRepository = _accountRepositoryMock.Object,
MetricRepository = _metricsRepositoryMock.Object,
Mapper = _mapperMock.Object
};
}
protected override void TestInitialize()
{
_signOffRepositoryMock = new Mock<IRepository<SignOff>>();
_metricsRepositoryMock = new Mock<IRepository<Metric>>();
_releaseWindowRepositoryMock = new Mock<IRepository<ReleaseWindow>>();
_accountRepositoryMock = new Mock<IRepository<Account>>();
_mapperMock = new Mock<IMappingEngine>();
_accounts = new List<Account>
{
new Account {AccountId = RandomData.RandomInt(30, 89), ExternalId = Guid.NewGuid()},
new Account {AccountId = RandomData.RandomInt(90, 189), ExternalId = Guid.NewGuid()},
new Account {AccountId = RandomData.RandomInt(200, 289), ExternalId = Guid.NewGuid()}
};
_accountRepositoryMock.SetupEntities(_accounts);
_releaseWindows = new List<ReleaseWindow>
{
new ReleaseWindow {ReleaseWindowId = RandomData.RandomInt(66, 99), ExternalId = Guid.NewGuid(), Metrics = new List<Metric>()}
};
_releaseWindowRepositoryMock.SetupEntities(_releaseWindows);
_signOffs = new List<SignOff>
{
new SignOff
{
AccountId = _accounts[0].AccountId,
Account = new Account{ExternalId = Guid.NewGuid()},
ReleaseWindowId = _releaseWindows[0].ReleaseWindowId,
SignedOff = SystemTime.Now.AddHours(-1),
ExternalId = Guid.NewGuid(),
ReleaseWindow = _releaseWindows[0]
},
new SignOff
{
AccountId = _accounts[1].AccountId,
Account = new Account{ExternalId = Guid.NewGuid()},
ReleaseWindowId = _releaseWindows[0].ReleaseWindowId,
ExternalId = Guid.NewGuid(),
ReleaseWindow = _releaseWindows[0]
}
};
_signOffRepositoryMock.SetupEntities(_signOffs);
base.TestInitialize();
}
[Test, ExpectedException(typeof(SignOffNotFoundException))]
public void SignOff_ShouldThrowException_WhenSignOffNotFound()
{
Sut.SignOff(Guid.NewGuid(), Guid.NewGuid(), String.Empty);
}
[Test]
public void SignOff_ShouldUpdateSignersRepository()
{
Sut.SignOff(_signOffs[1].Account.ExternalId, _releaseWindows[0].ExternalId, "this is description");
_signOffRepositoryMock.Verify(
s =>
s.Update(
It.Is<SignOff>(
q =>
q.ExternalId == _signOffs[1].ExternalId && q.SignedOff != null &&
q.Comment == "this is description")));
}
[Test, ExpectedException(typeof(SignOffNotFoundException))]
public void RemoveSigner_ShouldThrowException_WhenRemovedSignerNotFound()
{
Sut.RemoveSigner(Guid.NewGuid());
}
[Test]
public void RemoveSigner_ShouldRemoveSigner()
{
Sut.RemoveSigner(_signOffs[1].ExternalId);
_signOffRepositoryMock.Verify(
s => s.Delete(_signOffs[1]));
}
[Test, ExpectedException(typeof(ReleaseWindowNotFoundException))]
public void AddSigners_ShouldThrowException_WhenWindowNotFound()
{
Sut.AddSigners(new List<BusinessEntities.ReleaseExecution.SignOff>(), Guid.NewGuid());
}
[Test]
public void AddSigners_ShouldAddSigners()
{
Sut.AddSigners(new List<BusinessEntities.ReleaseExecution.SignOff>
{
new BusinessEntities.ReleaseExecution.SignOff
{
ExternalId = Guid.NewGuid(),
Signer = new BusinessEntities.Auth.Account
{
ExternalId = _accounts[2].ExternalId
}
}
}, _releaseWindows[0].ExternalId);
_signOffRepositoryMock.Verify(
s =>
s.Insert(
It.Is<List<SignOff>>(sg => sg.Any(i => i.AccountId == _accounts[2].AccountId) && sg.Count == 1)));
}
[Test, ExpectedException(typeof(ReleaseWindowNotFoundException))]
public void GetSigners_ShouldThrowException_WhenWindowNotFound()
{
Sut.GetSignOffs(Guid.NewGuid());
}
[Test]
public void GetSigners_ShouldWorkCorrectly()
{
Sut.GetSignOffs(_releaseWindows[0].ExternalId);
_mapperMock.Verify(
m =>
m.Map<List<SignOff>, List<BusinessEntities.ReleaseExecution.SignOff>>(
It.Is<List<SignOff>>(
s =>
s.Count == 2 && s.Any(i => i.ExternalId == _signOffs[0].ExternalId) &&
s.Any(i => i.ExternalId == _signOffs[1].ExternalId))));
}
[Test, ExpectedException(typeof(ReleaseWindowNotFoundException))]
public void Check_ShouldThrowException_WhenWindowNotFound()
{
Sut.CheckSigningOff(Guid.NewGuid());
}
[Test]
public void Check_ShouldReturnFalse_WhenOneUserHasNotSignedOff()
{
var result = Sut.CheckSigningOff(_releaseWindows[0].ExternalId);
Assert.IsFalse(result);
_releaseWindowRepositoryMock.Verify(x => x.Update(It.IsAny<ReleaseWindow>()), Times.Never);
}
[Test]
public void Check_ShouldReturnTrueAndInsertMetric_WhenReleaseIsFullySignedOff()
{
_signOffs = new List<SignOff>
{
new SignOff
{
AccountId = _accounts[0].AccountId,
ReleaseWindowId = _releaseWindows[0].ReleaseWindowId,
SignedOff = SystemTime.Now.AddHours(-1),
ExternalId = Guid.NewGuid(),
ReleaseWindow = _releaseWindows[0]
},
new SignOff
{
AccountId = _accounts[1].AccountId,
ReleaseWindowId = _releaseWindows[0].ReleaseWindowId,
ExternalId = Guid.NewGuid(),
ReleaseWindow = _releaseWindows[0],
SignedOff = SystemTime.Now.AddMinutes(-50)
}
};
_signOffRepositoryMock.SetupEntities(_signOffs);
_metricsRepositoryMock.Setup(x => x.Insert(It.Is<Metric>(m => m.ReleaseWindowId == _releaseWindows[0].ReleaseWindowId)))
.Callback((Metric m) => _releaseWindows[0].Metrics.Add(m));
var result = Sut.CheckSigningOff(_releaseWindows[0].ExternalId);
Assert.IsTrue(result);
_metricsRepositoryMock.Verify(x => x.Insert(It.IsAny<Metric>()), Times.Once);
_metricsRepositoryMock.Verify(x => x.Update(It.IsAny<Metric>()), Times.Never);
}
[Test]
public void Check_ShouldReturnTrueAndUpdateMetric_WhenReleaseIsFullySignedOffAndMetricExists()
{
_signOffs = new List<SignOff>
{
new SignOff
{
AccountId = _accounts[0].AccountId,
ReleaseWindowId = _releaseWindows[0].ReleaseWindowId,
SignedOff = SystemTime.Now.AddHours(-1),
ExternalId = Guid.NewGuid(),
ReleaseWindow = _releaseWindows[0]
},
new SignOff
{
AccountId = _accounts[1].AccountId,
ReleaseWindowId = _releaseWindows[0].ReleaseWindowId,
ExternalId = Guid.NewGuid(),
ReleaseWindow = _releaseWindows[0],
SignedOff = SystemTime.Now.AddMinutes(-50)
}
};
var metric = new Metric
{
ExternalId = Guid.NewGuid(),
MetricType = MetricType.SignOff,
ReleaseWindowId = _releaseWindows[0].ReleaseWindowId,
ReleaseWindow = new ReleaseWindow { ExternalId = _releaseWindows[0].ExternalId }
};
_signOffRepositoryMock.SetupEntities(_signOffs);
_metricsRepositoryMock.SetupEntities(new[] { metric });
_releaseWindows[0].Metrics.Add(metric);
var result = Sut.CheckSigningOff(_releaseWindows[0].ExternalId);
Assert.IsTrue(result);
_metricsRepositoryMock.Verify(x => x.Insert(It.IsAny<Metric>()), Times.Never);
_metricsRepositoryMock.Verify(x => x.Update(It.IsAny<Metric>()), Times.Once);
_metricsRepositoryMock.Verify(x => x.Update(It.Is<Metric>(m => m.MetricType == MetricType.SignOff && m.ExecutedOn.HasValue)));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
#if __UNIFIED__
using Foundation;
using UIKit;
#else
using MonoTouch.Foundation;
using MonoTouch.UIKit;
#endif
using MonoTouch.Dialog;
using SDWebImage;
namespace SDWebImageMTDialogSample
{
// The UIApplicationDelegate for the application. This class is responsible for launching the
// User Interface of the application, as well as listening (and optionally responding) to
// application events from iOS.
[Register ("AppDelegate")]
public partial class AppDelegate : UIApplicationDelegate
{
// class-level declarations
UIWindow window;
DialogViewController dvcController;
UINavigationController navController;
List<string> objects;
public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
window = new UIWindow (UIScreen.MainScreen.Bounds);
InitListOfImages ();
var root = new RootElement ("SDWebImage Sample") {
new Section ()
};
int count = 0;
foreach (var item in objects) {
count++;
string url = item;
var imgElement = new ImageLoaderStringElement (
caption: string.Format ("Image #{0}", count),
tapped: () => { HandleTapped (url); },
imageUrl: new NSUrl (url),
placeholder: UIImage.FromBundle ("placeholder")
);
root[0].Add (imgElement);
}
dvcController = new DialogViewController (UITableViewStyle.Plain, root);
dvcController.NavigationItem.RightBarButtonItem = new UIBarButtonItem ("Clear Cache", UIBarButtonItemStyle.Plain, ClearCache);
navController = new UINavigationController (dvcController);
window.RootViewController = navController;
window.MakeKeyAndVisible ();
return true;
}
void HandleTapped (string url)
{
string largeImageURL = url.Replace ("small", "source");
var dvcDetails = new DetailViewController (new NSUrl (largeImageURL));
navController.PushViewController (dvcDetails, true);
}
void ClearCache (object sender, EventArgs e)
{
SDWebImageManager.SharedManager.ImageCache.ClearMemory ();
SDWebImageManager.SharedManager.ImageCache.ClearDisk ();
}
void InitListOfImages ()
{
objects = new List<string> ()
{
@"http://assets.sbnation.com/assets/2512203/dogflops.gif",
@"http://www.ioncannon.net/wp-content/uploads/2011/06/test2.webp",
@"http://www.ioncannon.net/wp-content/uploads/2011/06/test9.webp",
@"http://static2.dmcdn.net/static/video/451/838/44838154:jpeg_preview_small.jpg?20120509163826",
@"http://static2.dmcdn.net/static/video/656/177/44771656:jpeg_preview_small.jpg?20120509154705",
@"http://static2.dmcdn.net/static/video/629/228/44822926:jpeg_preview_small.jpg?20120509181018",
@"http://static2.dmcdn.net/static/video/116/367/44763611:jpeg_preview_small.jpg?20120509101749",
@"http://static2.dmcdn.net/static/video/340/086/44680043:jpeg_preview_small.jpg?20120509180118",
@"http://static2.dmcdn.net/static/video/666/645/43546666:jpeg_preview_small.jpg?20120412153140",
@"http://static2.dmcdn.net/static/video/771/577/44775177:jpeg_preview_small.jpg?20120509183230",
@"http://static2.dmcdn.net/static/video/810/508/44805018:jpeg_preview_small.jpg?20120508125339",
@"http://static2.dmcdn.net/static/video/152/008/44800251:jpeg_preview_small.jpg?20120508103336",
@"http://static2.dmcdn.net/static/video/694/741/35147496:jpeg_preview_small.jpg?20120508111445",
@"http://static2.dmcdn.net/static/video/988/667/44766889:jpeg_preview_small.jpg?20120508130425",
@"http://static2.dmcdn.net/static/video/282/467/44764282:jpeg_preview_small.jpg?20120507130637",
@"http://static2.dmcdn.net/static/video/754/657/44756457:jpeg_preview_small.jpg?20120507093012",
@"http://static2.dmcdn.net/static/video/831/107/44701138:jpeg_preview_small.jpg?20120506133917",
@"http://static2.dmcdn.net/static/video/411/057/44750114:jpeg_preview_small.jpg?20120507014914",
@"http://static2.dmcdn.net/static/video/894/547/44745498:jpeg_preview_small.jpg?20120509183004",
@"http://static2.dmcdn.net/static/video/082/947/44749280:jpeg_preview_small.jpg?20120507015022",
@"http://static2.dmcdn.net/static/video/833/347/44743338:jpeg_preview_small.jpg?20120509183004",
@"http://static2.dmcdn.net/static/video/683/666/44666386:jpeg_preview_small.jpg?20120505111208",
@"http://static2.dmcdn.net/static/video/595/946/44649595:jpeg_preview_small.jpg?20120507194104",
@"http://static2.dmcdn.net/static/video/984/935/44539489:jpeg_preview_small.jpg?20120501184650",
@"http://static2.dmcdn.net/static/video/440/416/44614044:jpeg_preview_small.jpg?20120505174152",
@"http://static2.dmcdn.net/static/video/561/977/20779165:jpeg_preview_small.jpg?20120423161805",
@"http://static2.dmcdn.net/static/video/104/546/44645401:jpeg_preview_small.jpg?20120507185246",
@"http://static2.dmcdn.net/static/video/671/636/44636176:jpeg_preview_small.jpg?20120504021339",
@"http://static2.dmcdn.net/static/video/142/746/44647241:jpeg_preview_small.jpg?20120504104451",
@"http://static2.dmcdn.net/static/video/776/860/44068677:jpeg_preview_small.jpg?20120507185251",
@"http://static2.dmcdn.net/static/video/026/626/44626620:jpeg_preview_small.jpg?20120503203036",
@"http://static2.dmcdn.net/static/video/364/663/39366463:jpeg_preview_small.jpg?20120509163505",
@"http://static2.dmcdn.net/static/video/392/895/44598293:jpeg_preview_small.jpg?20120503165252",
@"http://static2.dmcdn.net/static/video/620/865/44568026:jpeg_preview_small.jpg?20120507185121",
@"http://static2.dmcdn.net/static/video/031/395/44593130:jpeg_preview_small.jpg?20120507185139",
@"http://static2.dmcdn.net/static/video/676/495/44594676:jpeg_preview_small.jpg?20120503121341",
@"http://static2.dmcdn.net/static/video/025/195/44591520:jpeg_preview_small.jpg?20120503132132",
@"http://static2.dmcdn.net/static/video/993/665/44566399:jpeg_preview_small.jpg?20120503182623",
@"http://static2.dmcdn.net/static/video/137/635/44536731:jpeg_preview_small.jpg?20120501165940",
@"http://static2.dmcdn.net/static/video/611/794/44497116:jpeg_preview_small.jpg?20120507184954",
@"http://static2.dmcdn.net/static/video/732/790/44097237:jpeg_preview_small.jpg?20120430162348",
@"http://static2.dmcdn.net/static/video/064/991/44199460:jpeg_preview_small.jpg?20120430101250",
@"http://static2.dmcdn.net/static/video/404/094/44490404:jpeg_preview_small.jpg?20120507184948",
@"http://static2.dmcdn.net/static/video/413/120/44021314:jpeg_preview_small.jpg?20120507180850",
@"http://static2.dmcdn.net/static/video/200/584/44485002:jpeg_preview_small.jpg?20120507184941",
@"http://static2.dmcdn.net/static/video/551/318/42813155:jpeg_preview_small.jpg?20120412153202",
@"http://static2.dmcdn.net/static/video/524/750/44057425:jpeg_preview_small.jpg?20120501220912",
@"http://static2.dmcdn.net/static/video/124/843/44348421:jpeg_preview_small.jpg?20120507184551",
@"http://static2.dmcdn.net/static/video/496/394/42493694:jpeg_preview_small.jpg?20120430105337",
@"http://static2.dmcdn.net/static/video/548/883/44388845:jpeg_preview_small.jpg?20120428212713",
@"http://static2.dmcdn.net/static/video/282/533/44335282:jpeg_preview_small.jpg?20120427102844",
@"http://static2.dmcdn.net/static/video/257/132/44231752:jpeg_preview_small.jpg?20120428212609",
@"http://static2.dmcdn.net/static/video/480/193/44391084:jpeg_preview_small.jpg?20120501143214",
@"http://static2.dmcdn.net/static/video/903/432/44234309:jpeg_preview_small.jpg?20120427200002",
@"http://static2.dmcdn.net/static/video/646/573/44375646:jpeg_preview_small.jpg?20120507184652",
@"http://static2.dmcdn.net/static/video/709/573/44375907:jpeg_preview_small.jpg?20120507184652",
@"http://static2.dmcdn.net/static/video/885/633/44336588:jpeg_preview_small.jpg?20120507184540",
@"http://static2.dmcdn.net/static/video/732/523/44325237:jpeg_preview_small.jpg?20120426110308",
@"http://static2.dmcdn.net/static/video/935/132/44231539:jpeg_preview_small.jpg?20120426115744",
@"http://static2.dmcdn.net/static/video/941/129/43921149:jpeg_preview_small.jpg?20120426094640",
@"http://static2.dmcdn.net/static/video/775/942/44249577:jpeg_preview_small.jpg?20120425011228",
@"http://static2.dmcdn.net/static/video/868/332/44233868:jpeg_preview_small.jpg?20120429152901",
@"http://static2.dmcdn.net/static/video/959/732/44237959:jpeg_preview_small.jpg?20120425133534",
@"http://static2.dmcdn.net/static/video/383/402/44204383:jpeg_preview_small.jpg?20120424185842",
@"http://static2.dmcdn.net/static/video/971/932/44239179:jpeg_preview_small.jpg?20120424154419",
@"http://static2.dmcdn.net/static/video/096/991/44199690:jpeg_preview_small.jpg?20120423162001",
@"http://static2.dmcdn.net/static/video/661/450/44054166:jpeg_preview_small.jpg?20120507180921",
@"http://static2.dmcdn.net/static/video/419/322/44223914:jpeg_preview_small.jpg?20120424112858",
@"http://static2.dmcdn.net/static/video/673/391/44193376:jpeg_preview_small.jpg?20120507181450",
@"http://static2.dmcdn.net/static/video/907/781/44187709:jpeg_preview_small.jpg?20120423103507",
@"http://static2.dmcdn.net/static/video/446/571/44175644:jpeg_preview_small.jpg?20120423033122",
@"http://static2.dmcdn.net/static/video/146/671/44176641:jpeg_preview_small.jpg?20120428235503",
@"http://static2.dmcdn.net/static/video/463/571/44175364:jpeg_preview_small.jpg?20120428235503",
@"http://static2.dmcdn.net/static/video/442/471/44174244:jpeg_preview_small.jpg?20120428235502",
@"http://static2.dmcdn.net/static/video/523/471/44174325:jpeg_preview_small.jpg?20120422205107",
@"http://static2.dmcdn.net/static/video/977/159/43951779:jpeg_preview_small.jpg?20120420182100",
@"http://static2.dmcdn.net/static/video/875/880/40088578:jpeg_preview_small.jpg?20120501131026",
@"http://static2.dmcdn.net/static/video/434/992/38299434:jpeg_preview_small.jpg?20120503193356",
@"http://static2.dmcdn.net/static/video/448/798/42897844:jpeg_preview_small.jpg?20120418155203",
@"http://static2.dmcdn.net/static/video/374/690/44096473:jpeg_preview_small.jpg?20120507181124",
@"http://static2.dmcdn.net/static/video/284/313/43313482:jpeg_preview_small.jpg?20120420184511",
@"http://static2.dmcdn.net/static/video/682/060/44060286:jpeg_preview_small.jpg?20120421122436",
@"http://static2.dmcdn.net/static/video/701/750/44057107:jpeg_preview_small.jpg?20120420112918",
@"http://static2.dmcdn.net/static/video/790/850/44058097:jpeg_preview_small.jpg?20120424114522",
@"http://static2.dmcdn.net/static/video/153/617/43716351:jpeg_preview_small.jpg?20120419190650",
@"http://static2.dmcdn.net/static/video/394/633/37336493:jpeg_preview_small.jpg?20111109151109",
@"http://static2.dmcdn.net/static/video/893/330/44033398:jpeg_preview_small.jpg?20120419123322",
@"http://static2.dmcdn.net/static/video/395/046/42640593:jpeg_preview_small.jpg?20120418103546",
@"http://static2.dmcdn.net/static/video/913/040/44040319:jpeg_preview_small.jpg?20120419164908",
@"http://static2.dmcdn.net/static/video/090/020/44020090:jpeg_preview_small.jpg?20120418185934",
@"http://static2.dmcdn.net/static/video/349/299/43992943:jpeg_preview_small.jpg?20120418112749",
@"http://static2.dmcdn.net/static/video/530/189/43981035:jpeg_preview_small.jpg?20120419013834",
@"http://static2.dmcdn.net/static/video/763/469/43964367:jpeg_preview_small.jpg?20120425111931",
@"http://static2.dmcdn.net/static/video/961/455/43554169:jpeg_preview_small.jpg?20120418110127",
@"http://static2.dmcdn.net/static/video/666/889/43988666:jpeg_preview_small.jpg?20120507180735",
@"http://static2.dmcdn.net/static/video/160/459/43954061:jpeg_preview_small.jpg?20120501202847",
@"http://static2.dmcdn.net/static/video/352/069/43960253:jpeg_preview_small.jpg?20120503175747",
@"http://static2.dmcdn.net/static/video/096/502/43205690:jpeg_preview_small.jpg?20120417142655",
@"http://static2.dmcdn.net/static/video/257/119/43911752:jpeg_preview_small.jpg?20120416101238",
@"http://static2.dmcdn.net/static/video/874/098/43890478:jpeg_preview_small.jpg?20120415193608",
@"http://static2.dmcdn.net/static/video/406/148/43841604:jpeg_preview_small.jpg?20120416123145",
@"http://static2.dmcdn.net/static/video/463/885/43588364:jpeg_preview_small.jpg?20120409130206",
@"http://static2.dmcdn.net/static/video/176/845/38548671:jpeg_preview_small.jpg?20120414200742",
@"http://static2.dmcdn.net/static/video/447/848/51848744:jpeg_preview_small.jpg?20121105223446",
@"http://static2.dmcdn.net/static/video/337/848/51848733:jpeg_preview_small.jpg?20121105223433",
@"http://static2.dmcdn.net/static/video/707/848/51848707:jpeg_preview_small.jpg?20121105223428",
@"http://static2.dmcdn.net/static/video/102/848/51848201:jpeg_preview_small.jpg?20121105223411",
@"http://static2.dmcdn.net/static/video/817/848/51848718:jpeg_preview_small.jpg?20121105223402",
@"http://static2.dmcdn.net/static/video/007/848/51848700:jpeg_preview_small.jpg?20121105223345",
@"http://static2.dmcdn.net/static/video/696/848/51848696:jpeg_preview_small.jpg?20121105223355",
@"http://static2.dmcdn.net/static/video/296/848/51848692:jpeg_preview_small.jpg?20121105223337",
@"http://static2.dmcdn.net/static/video/080/848/51848080:jpeg_preview_small.jpg?20121105223653",
@"http://static2.dmcdn.net/static/video/386/848/51848683:jpeg_preview_small.jpg?20121105223343",
@"http://static2.dmcdn.net/static/video/876/848/51848678:jpeg_preview_small.jpg?20121105223301",
@"http://static2.dmcdn.net/static/video/866/848/51848668:jpeg_preview_small.jpg?20121105223244",
@"http://static2.dmcdn.net/static/video/572/548/51845275:jpeg_preview_small.jpg?20121105223229",
@"http://static2.dmcdn.net/static/video/972/548/51845279:jpeg_preview_small.jpg?20121105223227",
@"http://static2.dmcdn.net/static/video/112/548/51845211:jpeg_preview_small.jpg?20121105223226",
@"http://static2.dmcdn.net/static/video/549/448/51844945:jpeg_preview_small.jpg?20121105223223",
@"http://static2.dmcdn.net/static/video/166/848/51848661:jpeg_preview_small.jpg?20121105223228",
@"http://static2.dmcdn.net/static/video/856/848/51848658:jpeg_preview_small.jpg?20121105223223",
@"http://static2.dmcdn.net/static/video/746/848/51848647:jpeg_preview_small.jpg?20121105223204",
@"http://static2.dmcdn.net/static/video/446/848/51848644:jpeg_preview_small.jpg?20121105223204",
@"http://static2.dmcdn.net/static/video/726/848/51848627:jpeg_preview_small.jpg?20121105223221",
@"http://static2.dmcdn.net/static/video/436/848/51848634:jpeg_preview_small.jpg?20121105223445",
@"http://static2.dmcdn.net/static/video/836/848/51848638:jpeg_preview_small.jpg?20121105223144",
@"http://static2.dmcdn.net/static/video/036/848/51848630:jpeg_preview_small.jpg?20121105223125",
@"http://static2.dmcdn.net/static/video/026/848/51848620:jpeg_preview_small.jpg?20121105223102",
@"http://static2.dmcdn.net/static/video/895/848/51848598:jpeg_preview_small.jpg?20121105223112",
@"http://static2.dmcdn.net/static/video/116/848/51848611:jpeg_preview_small.jpg?20121105223052",
@"http://static2.dmcdn.net/static/video/006/848/51848600:jpeg_preview_small.jpg?20121105223043",
@"http://static2.dmcdn.net/static/video/432/548/51845234:jpeg_preview_small.jpg?20121105223022",
@"http://static2.dmcdn.net/static/video/785/848/51848587:jpeg_preview_small.jpg?20121105223031",
@"http://static2.dmcdn.net/static/video/975/848/51848579:jpeg_preview_small.jpg?20121105223012",
@"http://static2.dmcdn.net/static/video/965/848/51848569:jpeg_preview_small.jpg?20121105222952",
@"http://static2.dmcdn.net/static/video/365/848/51848563:jpeg_preview_small.jpg?20121105222943",
@"http://static2.dmcdn.net/static/video/755/848/51848557:jpeg_preview_small.jpg?20121105222943",
@"http://static2.dmcdn.net/static/video/722/248/51842227:jpeg_preview_small.jpg?20121105222908",
@"http://static2.dmcdn.net/static/video/155/848/51848551:jpeg_preview_small.jpg?20121105222913",
@"http://static2.dmcdn.net/static/video/345/848/51848543:jpeg_preview_small.jpg?20121105222907",
@"http://static2.dmcdn.net/static/video/535/848/51848535:jpeg_preview_small.jpg?20121105222848",
@"http://static2.dmcdn.net/static/video/035/848/51848530:jpeg_preview_small.jpg?20121105222837",
@"http://static2.dmcdn.net/static/video/525/848/51848525:jpeg_preview_small.jpg?20121105222826",
@"http://static2.dmcdn.net/static/video/233/848/51848332:jpeg_preview_small.jpg?20121105223414",
@"http://static2.dmcdn.net/static/video/125/848/51848521:jpeg_preview_small.jpg?20121105222809",
@"http://static2.dmcdn.net/static/video/005/848/51848500:jpeg_preview_small.jpg?20121105222802",
@"http://static2.dmcdn.net/static/video/015/848/51848510:jpeg_preview_small.jpg?20121105222755",
@"http://static2.dmcdn.net/static/video/121/548/51845121:jpeg_preview_small.jpg?20121105222850",
@"http://static2.dmcdn.net/static/video/205/848/51848502:jpeg_preview_small.jpg?20121105222737",
@"http://static2.dmcdn.net/static/video/697/448/51844796:jpeg_preview_small.jpg?20121105222818",
@"http://static2.dmcdn.net/static/video/494/848/51848494:jpeg_preview_small.jpg?20121105222724",
@"http://static2.dmcdn.net/static/video/806/448/51844608:jpeg_preview_small.jpg?20121105222811",
@"http://static2.dmcdn.net/static/video/729/348/51843927:jpeg_preview_small.jpg?20121105222805",
@"http://static2.dmcdn.net/static/video/865/148/51841568:jpeg_preview_small.jpg?20121105222803",
@"http://static2.dmcdn.net/static/video/481/548/51845184:jpeg_preview_small.jpg?20121105222700",
@"http://static2.dmcdn.net/static/video/190/548/51845091:jpeg_preview_small.jpg?20121105222656",
@"http://static2.dmcdn.net/static/video/128/448/51844821:jpeg_preview_small.jpg?20121105222656",
@"http://static2.dmcdn.net/static/video/784/848/51848487:jpeg_preview_small.jpg?20121105222704",
@"http://static2.dmcdn.net/static/video/182/448/51844281:jpeg_preview_small.jpg?20121105222652",
@"http://static2.dmcdn.net/static/video/801/848/51848108:jpeg_preview_small.jpg?20121105222907",
@"http://static2.dmcdn.net/static/video/974/848/51848479:jpeg_preview_small.jpg?20121105222657",
@"http://static2.dmcdn.net/static/video/274/848/51848472:jpeg_preview_small.jpg?20121105222644",
@"http://static2.dmcdn.net/static/video/954/848/51848459:jpeg_preview_small.jpg?20121105222637",
@"http://static2.dmcdn.net/static/video/554/848/51848455:jpeg_preview_small.jpg?20121105222615",
@"http://static2.dmcdn.net/static/video/944/848/51848449:jpeg_preview_small.jpg?20121105222558",
@"http://static2.dmcdn.net/static/video/144/848/51848441:jpeg_preview_small.jpg?20121105222556",
@"http://static2.dmcdn.net/static/video/134/848/51848431:jpeg_preview_small.jpg?20121105222539",
@"http://static2.dmcdn.net/static/video/624/848/51848426:jpeg_preview_small.jpg?20121105222523",
@"http://static2.dmcdn.net/static/video/281/448/51844182:jpeg_preview_small.jpg?20121105222502",
@"http://static2.dmcdn.net/static/video/414/848/51848414:jpeg_preview_small.jpg?20121105222516",
@"http://static2.dmcdn.net/static/video/171/848/51848171:jpeg_preview_small.jpg?20121105223449",
@"http://static2.dmcdn.net/static/video/904/848/51848409:jpeg_preview_small.jpg?20121105222514",
@"http://static2.dmcdn.net/static/video/004/848/51848400:jpeg_preview_small.jpg?20121105222443",
@"http://static2.dmcdn.net/static/video/693/848/51848396:jpeg_preview_small.jpg?20121105222439",
@"http://static2.dmcdn.net/static/video/401/848/51848104:jpeg_preview_small.jpg?20121105222832",
@"http://static2.dmcdn.net/static/video/957/648/51846759:jpeg_preview_small.jpg?20121105223109",
@"http://static2.dmcdn.net/static/video/603/848/51848306:jpeg_preview_small.jpg?20121105222324",
@"http://static2.dmcdn.net/static/video/990/848/51848099:jpeg_preview_small.jpg?20121105222807",
@"http://static2.dmcdn.net/static/video/929/448/51844929:jpeg_preview_small.jpg?20121105222216",
@"http://static2.dmcdn.net/static/video/320/548/51845023:jpeg_preview_small.jpg?20121105222214",
@"http://static2.dmcdn.net/static/video/387/448/51844783:jpeg_preview_small.jpg?20121105222212",
@"http://static2.dmcdn.net/static/video/833/248/51842338:jpeg_preview_small.jpg?20121105222209",
@"http://static2.dmcdn.net/static/video/993/348/51843399:jpeg_preview_small.jpg?20121105222012",
@"http://static2.dmcdn.net/static/video/660/848/51848066:jpeg_preview_small.jpg?20121105222754",
@"http://static2.dmcdn.net/static/video/471/848/51848174:jpeg_preview_small.jpg?20121105223419",
@"http://static2.dmcdn.net/static/video/255/748/51847552:jpeg_preview_small.jpg?20121105222420",
@"http://static2.dmcdn.net/static/video/257/448/51844752:jpeg_preview_small.jpg?20121105221728",
@"http://static2.dmcdn.net/static/video/090/848/51848090:jpeg_preview_small.jpg?20121105223020",
@"http://static2.dmcdn.net/static/video/807/448/51844708:jpeg_preview_small.jpg?20121105221654",
@"http://static2.dmcdn.net/static/video/196/448/51844691:jpeg_preview_small.jpg?20121105222110",
@"http://static2.dmcdn.net/static/video/406/448/51844604:jpeg_preview_small.jpg?20121105221647",
@"http://static2.dmcdn.net/static/video/865/348/51843568:jpeg_preview_small.jpg?20121105221644",
@"http://static2.dmcdn.net/static/video/932/448/51844239:jpeg_preview_small.jpg?20121105221309",
@"http://static2.dmcdn.net/static/video/967/438/51834769:jpeg_preview_small.jpg?20121105221020",
@"http://static2.dmcdn.net/static/video/362/348/51843263:jpeg_preview_small.jpg?20121105220855",
@"http://static2.dmcdn.net/static/video/777/448/51844777:jpeg_preview_small.jpg?20121105220715",
@"http://static2.dmcdn.net/static/video/567/348/51843765:jpeg_preview_small.jpg?20121105220708",
@"http://static2.dmcdn.net/static/video/905/248/51842509:jpeg_preview_small.jpg?20121105220640",
@"http://static2.dmcdn.net/static/video/857/748/51847758:jpeg_preview_small.jpg?20121105221003",
@"http://static2.dmcdn.net/static/video/578/348/51843875:jpeg_preview_small.jpg?20121105220350",
@"http://static2.dmcdn.net/static/video/214/448/51844412:jpeg_preview_small.jpg?20121105220415",
@"http://static2.dmcdn.net/static/video/264/748/51847462:jpeg_preview_small.jpg?20121105220635",
@"http://static2.dmcdn.net/static/video/817/748/51847718:jpeg_preview_small.jpg?20121105220233",
@"http://static2.dmcdn.net/static/video/784/848/51848487:jpeg_preview_small.jpg?20121105222704",
@"http://static2.dmcdn.net/static/video/182/448/51844281:jpeg_preview_small.jpg?20121105222652",
@"http://static2.dmcdn.net/static/video/801/848/51848108:jpeg_preview_small.jpg?20121105222907",
@"http://static2.dmcdn.net/static/video/974/848/51848479:jpeg_preview_small.jpg?20121105222657",
@"http://static2.dmcdn.net/static/video/274/848/51848472:jpeg_preview_small.jpg?20121105222644",
@"http://static2.dmcdn.net/static/video/954/848/51848459:jpeg_preview_small.jpg?20121105222637",
@"http://static2.dmcdn.net/static/video/554/848/51848455:jpeg_preview_small.jpg?20121105222615",
@"http://static2.dmcdn.net/static/video/944/848/51848449:jpeg_preview_small.jpg?20121105222558",
@"http://static2.dmcdn.net/static/video/144/848/51848441:jpeg_preview_small.jpg?20121105222556",
@"http://static2.dmcdn.net/static/video/134/848/51848431:jpeg_preview_small.jpg?20121105222539",
@"http://static2.dmcdn.net/static/video/624/848/51848426:jpeg_preview_small.jpg?20121105222523",
@"http://static2.dmcdn.net/static/video/281/448/51844182:jpeg_preview_small.jpg?20121105222502",
@"http://static2.dmcdn.net/static/video/414/848/51848414:jpeg_preview_small.jpg?20121105222516",
@"http://static2.dmcdn.net/static/video/171/848/51848171:jpeg_preview_small.jpg?20121105223449",
@"http://static2.dmcdn.net/static/video/904/848/51848409:jpeg_preview_small.jpg?20121105222514",
@"http://static2.dmcdn.net/static/video/004/848/51848400:jpeg_preview_small.jpg?20121105222443",
@"http://static2.dmcdn.net/static/video/693/848/51848396:jpeg_preview_small.jpg?20121105222439",
@"http://static2.dmcdn.net/static/video/401/848/51848104:jpeg_preview_small.jpg?20121105222832",
@"http://static2.dmcdn.net/static/video/957/648/51846759:jpeg_preview_small.jpg?20121105223109",
@"http://static2.dmcdn.net/static/video/603/848/51848306:jpeg_preview_small.jpg?20121105222324",
@"http://static2.dmcdn.net/static/video/990/848/51848099:jpeg_preview_small.jpg?20121105222807",
@"http://static2.dmcdn.net/static/video/929/448/51844929:jpeg_preview_small.jpg?20121105222216",
@"http://static2.dmcdn.net/static/video/320/548/51845023:jpeg_preview_small.jpg?20121105222214",
@"http://static2.dmcdn.net/static/video/387/448/51844783:jpeg_preview_small.jpg?20121105222212",
@"http://static2.dmcdn.net/static/video/833/248/51842338:jpeg_preview_small.jpg?20121105222209",
@"http://static2.dmcdn.net/static/video/993/348/51843399:jpeg_preview_small.jpg?20121105222012",
@"http://static2.dmcdn.net/static/video/660/848/51848066:jpeg_preview_small.jpg?20121105222754",
@"http://static2.dmcdn.net/static/video/471/848/51848174:jpeg_preview_small.jpg?20121105223419",
@"http://static2.dmcdn.net/static/video/255/748/51847552:jpeg_preview_small.jpg?20121105222420",
@"http://static2.dmcdn.net/static/video/257/448/51844752:jpeg_preview_small.jpg?20121105221728",
@"http://static2.dmcdn.net/static/video/090/848/51848090:jpeg_preview_small.jpg?20121105224514",
@"http://static2.dmcdn.net/static/video/807/448/51844708:jpeg_preview_small.jpg?20121105221654",
@"http://static2.dmcdn.net/static/video/196/448/51844691:jpeg_preview_small.jpg?20121105222110",
@"http://static2.dmcdn.net/static/video/406/448/51844604:jpeg_preview_small.jpg?20121105221647",
@"http://static2.dmcdn.net/static/video/865/348/51843568:jpeg_preview_small.jpg?20121105221644",
@"http://static2.dmcdn.net/static/video/932/448/51844239:jpeg_preview_small.jpg?20121105221309",
@"http://static2.dmcdn.net/static/video/967/438/51834769:jpeg_preview_small.jpg?20121105221020",
@"http://static2.dmcdn.net/static/video/362/348/51843263:jpeg_preview_small.jpg?20121105220855",
@"http://static2.dmcdn.net/static/video/777/448/51844777:jpeg_preview_small.jpg?20121105220715",
@"http://static2.dmcdn.net/static/video/567/348/51843765:jpeg_preview_small.jpg?20121105220708",
@"http://static2.dmcdn.net/static/video/905/248/51842509:jpeg_preview_small.jpg?20121105220640",
@"http://static2.dmcdn.net/static/video/857/748/51847758:jpeg_preview_small.jpg?20121105221003",
@"http://static2.dmcdn.net/static/video/578/348/51843875:jpeg_preview_small.jpg?20121105220350",
@"http://static2.dmcdn.net/static/video/214/448/51844412:jpeg_preview_small.jpg?20121105220415",
@"http://static2.dmcdn.net/static/video/264/748/51847462:jpeg_preview_small.jpg?20121105220635",
@"http://static2.dmcdn.net/static/video/817/748/51847718:jpeg_preview_small.jpg?20121105220233",
@"http://static2.dmcdn.net/static/video/807/748/51847708:jpeg_preview_small.jpg?20121105220241",
@"http://static2.dmcdn.net/static/video/199/838/51838991:jpeg_preview_small.jpg?20121105220605",
@"http://static2.dmcdn.net/static/video/776/748/51847677:jpeg_preview_small.jpg?20121105220150",
@"http://static2.dmcdn.net/static/video/986/748/51847689:jpeg_preview_small.jpg?20121105224514",
@"http://static2.dmcdn.net/static/video/915/748/51847519:jpeg_preview_small.jpg?20121105222216",
@"http://static2.dmcdn.net/static/video/983/448/51844389:jpeg_preview_small.jpg?20121105220116",
@"http://static2.dmcdn.net/static/video/751/348/51843157:jpeg_preview_small.jpg?20121105220104",
@"http://static2.dmcdn.net/static/video/192/538/51835291:jpeg_preview_small.jpg?20121105220103",
@"http://static2.dmcdn.net/static/video/596/448/51844695:jpeg_preview_small.jpg?20121105220033",
@"http://static2.dmcdn.net/static/video/750/648/51846057:jpeg_preview_small.jpg?20121105221259",
@"http://static2.dmcdn.net/static/video/441/148/51841144:jpeg_preview_small.jpg?20121105215911",
@"http://static2.dmcdn.net/static/video/860/448/51844068:jpeg_preview_small.jpg?20121105215905",
@"http://static2.dmcdn.net/static/video/995/748/51847599:jpeg_preview_small.jpg?20121105215939",
@"http://static2.dmcdn.net/static/video/774/748/51847477:jpeg_preview_small.jpg?20121105223414",
@"http://static2.dmcdn.net/static/video/498/648/51846894:jpeg_preview_small.jpg?20121105221807",
@"http://static2.dmcdn.net/static/video/011/748/51847110:jpeg_preview_small.jpg?20121105221118",
@"http://static2.dmcdn.net/static/video/794/748/51847497:jpeg_preview_small.jpg?20121105220829",
@"http://static2.dmcdn.net/static/video/988/648/51846889:jpeg_preview_small.jpg?20121105222149",
@"http://static2.dmcdn.net/static/video/769/548/51845967:jpeg_preview_small.jpg?20121105215601",
@"http://static2.dmcdn.net/static/video/225/448/51844522:jpeg_preview_small.jpg?20121105215552",
@"http://static2.dmcdn.net/static/video/172/308/51803271:jpeg_preview_small.jpg?20121105215455",
@"http://static2.dmcdn.net/static/video/994/748/51847499:jpeg_preview_small.jpg?20121105220343",
@"http://static2.dmcdn.net/static/video/852/748/51847258:jpeg_preview_small.jpg?20121105221031",
@"http://static2.dmcdn.net/static/video/671/838/51838176:jpeg_preview_small.jpg?20121105215421",
@"http://static2.dmcdn.net/static/video/172/448/51844271:jpeg_preview_small.jpg?20121105215420",
@"http://static2.dmcdn.net/static/video/735/448/51844537:jpeg_preview_small.jpg?20121105215437",
@"http://static2.dmcdn.net/static/video/834/448/51844438:jpeg_preview_small.jpg?20121105215431",
@"http://static2.dmcdn.net/static/video/613/448/51844316:jpeg_preview_small.jpg?20121105215431",
@"http://static2.dmcdn.net/static/video/581/748/51847185:jpeg_preview_small.jpg?20121105220637",
@"http://static2.dmcdn.net/static/video/407/648/51846704:jpeg_preview_small.jpg?20121105220316",
@"http://static2.dmcdn.net/static/video/460/448/51844064:jpeg_preview_small.jpg?20121105215245",
@"http://static2.dmcdn.net/static/video/298/648/51846892:jpeg_preview_small.jpg?20121105220953",
@"http://static2.dmcdn.net/static/video/053/748/51847350:jpeg_preview_small.jpg?20121105221113",
@"http://static2.dmcdn.net/static/video/996/448/51844699:jpeg_preview_small.jpg?20121105222807",
@"http://static2.dmcdn.net/static/video/451/448/51844154:jpeg_preview_small.jpg?20121105221955",
@"http://static2.dmcdn.net/static/video/049/648/51846940:jpeg_preview_small.jpg?20121105215910",
@"http://static2.dmcdn.net/static/video/091/748/51847190:jpeg_preview_small.jpg?20121105215617",
@"http://static2.dmcdn.net/static/video/573/748/51847375:jpeg_preview_small.jpg?20121105223420",
@"http://static2.dmcdn.net/static/video/103/248/51842301:jpeg_preview_small.jpg?20121105215014",
@"http://static2.dmcdn.net/static/video/991/548/51845199:jpeg_preview_small.jpg?20121105215407",
@"http://static2.dmcdn.net/static/video/872/648/51846278:jpeg_preview_small.jpg?20121105220635",
@"http://static2.dmcdn.net/static/video/813/748/51847318:jpeg_preview_small.jpg?20121105214729",
@"http://static2.dmcdn.net/static/video/153/448/51844351:jpeg_preview_small.jpg?20121105214622",
@"http://static2.dmcdn.net/static/video/328/648/51846823:jpeg_preview_small.jpg?20121105214944",
@"http://static2.dmcdn.net/static/video/892/748/51847298:jpeg_preview_small.jpg?20121105224514",
@"http://static2.dmcdn.net/static/video/640/048/51840046:jpeg_preview_small.jpg?20121105214430",
@"http://static2.dmcdn.net/static/video/153/648/51846351:jpeg_preview_small.jpg?20121105214426",
@"http://static2.dmcdn.net/static/video/769/248/51842967:jpeg_preview_small.jpg?20121105214255",
@"http://static2.dmcdn.net/static/video/720/448/51844027:jpeg_preview_small.jpg?20121105214248",
@"http://static2.dmcdn.net/static/video/895/048/51840598:jpeg_preview_small.jpg?20121105214234",
@"http://static2.dmcdn.net/static/video/893/348/51843398:jpeg_preview_small.jpg?20121105214157",
@"http://static2.dmcdn.net/static/video/351/748/51847153:jpeg_preview_small.jpg?20121105214106",
@"http://static2.dmcdn.net/static/video/364/648/51846463:jpeg_preview_small.jpg?20121105215005",
@"http://static2.dmcdn.net/static/video/269/938/51839962:jpeg_preview_small.jpg?20121105214014"
};
}
}
}
| |
// 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.ServiceModel.Channels;
using System.IdentityModel.Selectors;
using System.Runtime.Diagnostics;
using System.Threading.Tasks;
using System.Runtime;
namespace System.ServiceModel.Security
{
internal class WrapperSecurityCommunicationObject : CommunicationObject
{
private ISecurityCommunicationObject _innerCommunicationObject;
public WrapperSecurityCommunicationObject(ISecurityCommunicationObject innerCommunicationObject)
: base()
{
_innerCommunicationObject = innerCommunicationObject ?? throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(innerCommunicationObject));
SupportsAsyncOpenClose = true;
}
protected override Type GetCommunicationObjectType()
{
return _innerCommunicationObject.GetType();
}
protected override TimeSpan DefaultCloseTimeout
{
get { return _innerCommunicationObject.DefaultCloseTimeout; }
}
protected override TimeSpan DefaultOpenTimeout
{
get { return _innerCommunicationObject.DefaultOpenTimeout; }
}
protected override void OnAbort()
{
_innerCommunicationObject.OnAbort();
}
protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
return OnCloseAsync(timeout).ToApm(callback, state);
}
protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
return OnOpenAsync(timeout).ToApm(callback, state);
}
protected override void OnClose(TimeSpan timeout)
{
_innerCommunicationObject.OnCloseAsync(timeout).GetAwaiter().GetResult();
}
protected override void OnClosed()
{
_innerCommunicationObject.OnClosed();
base.OnClosed();
}
protected override void OnClosing()
{
_innerCommunicationObject.OnClosing();
base.OnClosing();
}
protected override void OnEndClose(IAsyncResult result)
{
result.ToApmEnd();
}
protected override void OnEndOpen(IAsyncResult result)
{
result.ToApmEnd();
}
protected override void OnFaulted()
{
_innerCommunicationObject.OnFaulted();
base.OnFaulted();
}
protected override void OnOpen(TimeSpan timeout)
{
_innerCommunicationObject.OnOpenAsync(timeout).GetAwaiter().GetResult();
}
protected override void OnOpened()
{
_innerCommunicationObject.OnOpened();
base.OnOpened();
}
protected override void OnOpening()
{
_innerCommunicationObject.OnOpening();
base.OnOpening();
}
new internal void ThrowIfDisposedOrImmutable()
{
base.ThrowIfDisposedOrImmutable();
}
protected internal override Task OnCloseAsync(TimeSpan timeout)
{
return _innerCommunicationObject.OnCloseAsync(timeout);
}
protected internal override Task OnOpenAsync(TimeSpan timeout)
{
return _innerCommunicationObject.OnOpenAsync(timeout);
}
}
internal abstract class CommunicationObjectSecurityTokenProvider : SecurityTokenProvider, IAsyncCommunicationObject, ISecurityCommunicationObject
{
private EventTraceActivity _eventTraceActivity;
protected CommunicationObjectSecurityTokenProvider()
{
CommunicationObject = new WrapperSecurityCommunicationObject(this);
}
internal EventTraceActivity EventTraceActivity
{
get
{
if (_eventTraceActivity == null)
{
_eventTraceActivity = EventTraceActivity.GetFromThreadOrCreate();
}
return _eventTraceActivity;
}
}
protected WrapperSecurityCommunicationObject CommunicationObject { get; }
public event EventHandler Closed
{
add { CommunicationObject.Closed += value; }
remove { CommunicationObject.Closed -= value; }
}
public event EventHandler Closing
{
add { CommunicationObject.Closing += value; }
remove { CommunicationObject.Closing -= value; }
}
public event EventHandler Faulted
{
add { CommunicationObject.Faulted += value; }
remove { CommunicationObject.Faulted -= value; }
}
public event EventHandler Opened
{
add { CommunicationObject.Opened += value; }
remove { CommunicationObject.Opened -= value; }
}
public event EventHandler Opening
{
add { CommunicationObject.Opening += value; }
remove { CommunicationObject.Opening -= value; }
}
public CommunicationState State
{
get { return CommunicationObject.State; }
}
public virtual TimeSpan DefaultOpenTimeout
{
get { return ServiceDefaults.OpenTimeout; }
}
public virtual TimeSpan DefaultCloseTimeout
{
get { return ServiceDefaults.CloseTimeout; }
}
// communication object
public void Abort()
{
CommunicationObject.Abort();
}
public void Close()
{
CommunicationObject.Close();
}
public Task CloseAsync(TimeSpan timeout)
{
return ((IAsyncCommunicationObject)CommunicationObject).CloseAsync(timeout);
}
public void Close(TimeSpan timeout)
{
CommunicationObject.Close(timeout);
}
public IAsyncResult BeginClose(AsyncCallback callback, object state)
{
return CommunicationObject.BeginClose(callback, state);
}
public IAsyncResult BeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
return CommunicationObject.BeginClose(timeout, callback, state);
}
public void EndClose(IAsyncResult result)
{
CommunicationObject.EndClose(result);
}
public void Open()
{
CommunicationObject.Open();
}
public Task OpenAsync(TimeSpan timeout)
{
return ((IAsyncCommunicationObject)CommunicationObject).OpenAsync(timeout);
}
public void Open(TimeSpan timeout)
{
CommunicationObject.Open(timeout);
}
public IAsyncResult BeginOpen(AsyncCallback callback, object state)
{
return CommunicationObject.BeginOpen(callback, state);
}
public IAsyncResult BeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
return CommunicationObject.BeginOpen(timeout, callback, state);
}
public void EndOpen(IAsyncResult result)
{
CommunicationObject.EndOpen(result);
}
public void Dispose()
{
Close();
}
// ISecurityCommunicationObject methods
public virtual void OnAbort()
{
}
public virtual Task OnCloseAsync(TimeSpan timeout)
{
return Task.CompletedTask;
}
public virtual void OnClosed()
{
}
public virtual void OnClosing()
{
}
public virtual void OnFaulted()
{
OnAbort();
}
public virtual Task OnOpenAsync(TimeSpan timeout)
{
return Task.CompletedTask;
}
public virtual void OnOpened()
{
}
public virtual void OnOpening()
{
}
}
internal abstract class CommunicationObjectSecurityTokenAuthenticator : SecurityTokenAuthenticator, ICommunicationObject, ISecurityCommunicationObject
{
protected CommunicationObjectSecurityTokenAuthenticator()
{
CommunicationObject = new WrapperSecurityCommunicationObject(this);
}
protected WrapperSecurityCommunicationObject CommunicationObject { get; }
public event EventHandler Closed
{
add { CommunicationObject.Closed += value; }
remove { CommunicationObject.Closed -= value; }
}
public event EventHandler Closing
{
add { CommunicationObject.Closing += value; }
remove { CommunicationObject.Closing -= value; }
}
public event EventHandler Faulted
{
add { CommunicationObject.Faulted += value; }
remove { CommunicationObject.Faulted -= value; }
}
public event EventHandler Opened
{
add { CommunicationObject.Opened += value; }
remove { CommunicationObject.Opened -= value; }
}
public event EventHandler Opening
{
add { CommunicationObject.Opening += value; }
remove { CommunicationObject.Opening -= value; }
}
public CommunicationState State
{
get { return CommunicationObject.State; }
}
public virtual TimeSpan DefaultOpenTimeout
{
get { return ServiceDefaults.OpenTimeout; }
}
public virtual TimeSpan DefaultCloseTimeout
{
get { return ServiceDefaults.CloseTimeout; }
}
// communication object
public void Abort()
{
CommunicationObject.Abort();
}
public void Close()
{
CommunicationObject.Close();
}
public void Close(TimeSpan timeout)
{
CommunicationObject.Close(timeout);
}
public IAsyncResult BeginClose(AsyncCallback callback, object state)
{
return CommunicationObject.BeginClose(callback, state);
}
public IAsyncResult BeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
return CommunicationObject.BeginClose(timeout, callback, state);
}
public void EndClose(IAsyncResult result)
{
CommunicationObject.EndClose(result);
}
public void Open()
{
CommunicationObject.Open();
}
public void Open(TimeSpan timeout)
{
CommunicationObject.Open(timeout);
}
public IAsyncResult BeginOpen(AsyncCallback callback, object state)
{
return CommunicationObject.BeginOpen(callback, state);
}
public IAsyncResult BeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
return CommunicationObject.BeginOpen(timeout, callback, state);
}
public void EndOpen(IAsyncResult result)
{
CommunicationObject.EndOpen(result);
}
public void Dispose()
{
Close();
}
// ISecurityCommunicationObject methods
public virtual void OnAbort()
{
}
public IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
return new OperationWithTimeoutAsyncResult(OnClose, timeout, callback, state);
}
public IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
return new OperationWithTimeoutAsyncResult(OnOpen, timeout, callback, state);
}
public virtual void OnClose(TimeSpan timeout)
{
}
public Task OnCloseAsync(TimeSpan timeout)
{
return Task.CompletedTask;
}
public virtual void OnClosed()
{
}
public virtual void OnClosing()
{
}
public void OnEndClose(IAsyncResult result)
{
OperationWithTimeoutAsyncResult.End(result);
}
public void OnEndOpen(IAsyncResult result)
{
OperationWithTimeoutAsyncResult.End(result);
}
public virtual void OnFaulted()
{
OnAbort();
}
public virtual void OnOpen(TimeSpan timeout)
{
}
public Task OnOpenAsync(TimeSpan timeout)
{
return Task.CompletedTask;
}
public virtual void OnOpened()
{
}
public virtual void OnOpening()
{
}
}
}
| |
// Copyright (C) 2014 - 2016 Stephan Bouchard - All Rights Reserved
// This code can only be used under the standard Unity Asset Store End User License Agreement
// A Copy of the EULA APPENDIX 1 is available at http://unity3d.com/company/legal/as_terms
using UnityEngine;
using UnityEditor;
using UnityEditorInternal;
using System.Collections;
using System.Collections.Generic;
namespace TMPro.EditorUtilities
{
[CustomPropertyDrawer(typeof(TMP_FontWeights))]
public class FontWeightDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
SerializedProperty prop_regular = property.FindPropertyRelative("regularTypeface");
SerializedProperty prop_italic = property.FindPropertyRelative("italicTypeface");
float width = position.width;
position.width = 125;
EditorGUI.LabelField(position, label);
// NORMAL FACETYPE
if (label.text[0] == '4') GUI.enabled = false;
position.x = 140; position.width = (width - 140) / 2;
EditorGUI.PropertyField(position, prop_regular, GUIContent.none);
// ITALIC FACETYPE
GUI.enabled = true;
position.x += position.width + 17;
EditorGUI.PropertyField(position, prop_italic, GUIContent.none);
}
}
[CustomEditor(typeof(TMP_FontAsset))]
public class TMP_FontAssetEditor : Editor
{
private struct UI_PanelState
{
public static bool fontInfoPanel = true;
public static bool fontWeightPanel = true;
public static bool fallbackFontAssetPanel = true;
public static bool glyphInfoPanel = false;
public static bool kerningInfoPanel = false;
}
private struct Warning
{
public bool isEnabled;
public double expirationTime;
}
private int m_GlyphPage = 0;
private int m_KerningPage = 0;
private int m_selectedElement = -1;
private string m_dstGlyphID;
private const string k_placeholderUnicodeHex = "<i>Unicode Hex ID</i>";
private string m_unicodeHexLabel = k_placeholderUnicodeHex;
private Warning m_AddGlyphWarning;
private string m_searchPattern;
private List<int> m_searchList;
private bool m_isSearchDirty;
private const string k_UndoRedo = "UndoRedoPerformed";
private SerializedProperty font_atlas_prop;
private SerializedProperty font_material_prop;
private SerializedProperty fontWeights_prop;
//private SerializedProperty fallbackFontAssets_prop;
private ReorderableList m_list;
private SerializedProperty font_normalStyle_prop;
private SerializedProperty font_normalSpacing_prop;
private SerializedProperty font_boldStyle_prop;
private SerializedProperty font_boldSpacing_prop;
private SerializedProperty font_italicStyle_prop;
private SerializedProperty font_tabSize_prop;
private SerializedProperty m_fontInfo_prop;
private SerializedProperty m_glyphInfoList_prop;
private SerializedProperty m_kerningInfo_prop;
private KerningTable m_kerningTable;
private SerializedProperty m_kerningPair_prop;
private TMP_FontAsset m_fontAsset;
private Material[] m_materialPresets;
private bool isAssetDirty = false;
private int errorCode;
private System.DateTime timeStamp;
private string[] uiStateLabel = new string[] { "<i>(Click to expand)</i>", "<i>(Click to collapse)</i>" };
public void OnEnable()
{
font_atlas_prop = serializedObject.FindProperty("atlas");
font_material_prop = serializedObject.FindProperty("material");
fontWeights_prop = serializedObject.FindProperty("fontWeights");
m_list = new ReorderableList(serializedObject, serializedObject.FindProperty("fallbackFontAssets"), true, true, true, true);
m_list.drawElementCallback = (Rect rect, int index, bool isActive, bool isFocused) =>
{
var element = m_list.serializedProperty.GetArrayElementAtIndex(index);
rect.y += 2;
EditorGUI.PropertyField(new Rect(rect.x, rect.y, rect.width, EditorGUIUtility.singleLineHeight), element, GUIContent.none);
};
m_list.drawHeaderCallback = rect =>
{
EditorGUI.LabelField(rect, "<b>Fallback Font Asset List</b>", TMP_UIStyleManager.Label);
};
font_normalStyle_prop = serializedObject.FindProperty("normalStyle");
font_normalSpacing_prop = serializedObject.FindProperty("normalSpacingOffset");
font_boldStyle_prop = serializedObject.FindProperty("boldStyle");
font_boldSpacing_prop = serializedObject.FindProperty("boldSpacing");
font_italicStyle_prop = serializedObject.FindProperty("italicStyle");
font_tabSize_prop = serializedObject.FindProperty("tabSize");
m_fontInfo_prop = serializedObject.FindProperty("m_fontInfo");
m_glyphInfoList_prop = serializedObject.FindProperty("m_glyphInfoList");
m_kerningInfo_prop = serializedObject.FindProperty("m_kerningInfo");
m_kerningPair_prop = serializedObject.FindProperty("m_kerningPair");
m_fontAsset = target as TMP_FontAsset;
m_kerningTable = m_fontAsset.kerningInfo;
m_materialPresets = TMP_EditorUtility.FindMaterialReferences(m_fontAsset);
// Get the UI Skin and Styles for the various Editors
TMP_UIStyleManager.GetUIStyles();
m_searchList = new List<int>();
}
public override void OnInspectorGUI()
{
// Check Warnings
//Debug.Log("OnInspectorGUI Called.");
Event currentEvent = Event.current;
serializedObject.Update();
GUILayout.Label("<b>TextMesh Pro! Font Asset</b>", TMP_UIStyleManager.Section_Label);
// TextMeshPro Font Info Panel
GUILayout.Label("Face Info", TMP_UIStyleManager.Section_Label);
EditorGUI.indentLevel = 1;
GUI.enabled = false; // Lock UI
float labelWidth = EditorGUIUtility.labelWidth = 150f;
float fieldWidth = EditorGUIUtility.fieldWidth;
EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("Name"), new GUIContent("Font Source"));
EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("PointSize"));
GUI.enabled = true;
EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("Scale"));
EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("LineHeight"));
EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("Ascender"));
EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("CapHeight"));
EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("Baseline"));
EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("Descender"));
EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("Underline"));
//EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("UnderlineThickness"));
EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("SuperscriptOffset"));
EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("SubscriptOffset"));
SerializedProperty subSize_prop = m_fontInfo_prop.FindPropertyRelative("SubSize");
EditorGUILayout.PropertyField(subSize_prop, new GUIContent("Super / Subscript Size"));
subSize_prop.floatValue = Mathf.Clamp(subSize_prop.floatValue, 0.25f, 1f);
GUI.enabled = false;
//EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("Padding"));
//GUILayout.Label("Atlas Size");
EditorGUI.indentLevel = 1;
GUILayout.Space(18);
EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("Padding"));
EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("AtlasWidth"), new GUIContent("Width"));
EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("AtlasHeight"), new GUIContent("Height"));
GUI.enabled = true;
EditorGUI.indentLevel = 0;
GUILayout.Space(20);
GUILayout.Label("Font Sub-Assets", TMP_UIStyleManager.Section_Label);
GUI.enabled = false;
EditorGUI.indentLevel = 1;
EditorGUILayout.PropertyField(font_atlas_prop, new GUIContent("Font Atlas:"));
EditorGUILayout.PropertyField(font_material_prop, new GUIContent("Font Material:"));
GUI.enabled = true;
string evt_cmd = Event.current.commandName; // Get Current Event CommandName to check for Undo Events
// FONT SETTINGS
EditorGUI.indentLevel = 0;
if (GUILayout.Button("Font Weights\t" + (UI_PanelState.fontWeightPanel ? uiStateLabel[1] : uiStateLabel[0]), TMP_UIStyleManager.Section_Label))
UI_PanelState.fontWeightPanel = !UI_PanelState.fontWeightPanel;
if (UI_PanelState.fontWeightPanel)
{
EditorGUIUtility.labelWidth = 120;
EditorGUILayout.BeginVertical(TMP_UIStyleManager.SquareAreaBox85G);
EditorGUI.indentLevel = 0;
GUILayout.Label("Select the Font Assets that will be used for the following font weights.", TMP_UIStyleManager.Label);
GUILayout.Space(10f);
EditorGUILayout.BeginHorizontal();
GUILayout.Label("<b>Font Weight</b>", TMP_UIStyleManager.Label, GUILayout.Width(117));
GUILayout.Label("<b>Normal Style</b>", TMP_UIStyleManager.Label);
GUILayout.Label("<b>Italic Style</b>", TMP_UIStyleManager.Label);
EditorGUILayout.EndHorizontal();
//EditorGUILayout.PropertyField(fontWeights_prop.GetArrayElementAtIndex(1), new GUIContent("100 - Thin"));
//EditorGUILayout.PropertyField(fontWeights_prop.GetArrayElementAtIndex(2), new GUIContent("200 - Extra-Light"));
//EditorGUILayout.PropertyField(fontWeights_prop.GetArrayElementAtIndex(3), new GUIContent("300 - Light"));
EditorGUILayout.PropertyField(fontWeights_prop.GetArrayElementAtIndex(4), new GUIContent("400 - Regular"));
//EditorGUILayout.PropertyField(fontWeights_prop.GetArrayElementAtIndex(5), new GUIContent("500 - Medium"));
//EditorGUILayout.PropertyField(fontWeights_prop.GetArrayElementAtIndex(6), new GUIContent("600 - Demi-Bold"));
EditorGUILayout.PropertyField(fontWeights_prop.GetArrayElementAtIndex(7), new GUIContent("700 - Bold"));
//EditorGUILayout.PropertyField(fontWeights_prop.GetArrayElementAtIndex(8), new GUIContent("800 - Heavy"));
//EditorGUILayout.PropertyField(fontWeights_prop.GetArrayElementAtIndex(9), new GUIContent("900 - Black"));
EditorGUILayout.EndVertical();
//EditorGUI.indentLevel = 1;
EditorGUIUtility.labelWidth = 120f;
EditorGUILayout.BeginVertical(TMP_UIStyleManager.SquareAreaBox85G);
GUILayout.Label("Settings used to simulate a typeface when no font asset is available.", TMP_UIStyleManager.Label);
GUILayout.Space(5f);
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PropertyField(font_normalStyle_prop, new GUIContent("Normal Weight"));
font_normalStyle_prop.floatValue = Mathf.Clamp(font_normalStyle_prop.floatValue, -3.0f, 3.0f);
if (GUI.changed || evt_cmd == k_UndoRedo)
{
GUI.changed = false;
// Modify the material property on matching material presets.
for (int i = 0; i < m_materialPresets.Length; i++)
m_materialPresets[i].SetFloat("_WeightNormal", font_normalStyle_prop.floatValue);
}
EditorGUILayout.PropertyField(font_boldStyle_prop, new GUIContent("Bold Weight"), GUILayout.MinWidth(100));
font_boldStyle_prop.floatValue = Mathf.Clamp(font_boldStyle_prop.floatValue, -3.0f, 3.0f);
if (GUI.changed || evt_cmd == k_UndoRedo)
{
GUI.changed = false;
// Modify the material property on matching material presets.
for (int i = 0; i < m_materialPresets.Length; i++)
m_materialPresets[i].SetFloat("_WeightBold", font_boldStyle_prop.floatValue);
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PropertyField(font_normalSpacing_prop, new GUIContent("Spacing Offset"));
font_normalSpacing_prop.floatValue = Mathf.Clamp(font_normalSpacing_prop.floatValue, -100, 100);
if (GUI.changed || evt_cmd == k_UndoRedo)
{
GUI.changed = false;
}
EditorGUILayout.PropertyField(font_boldSpacing_prop, new GUIContent("Bold Spacing"));
font_boldSpacing_prop.floatValue = Mathf.Clamp(font_boldSpacing_prop.floatValue, 0, 100);
if (GUI.changed || evt_cmd == k_UndoRedo)
{
GUI.changed = false;
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PropertyField(font_italicStyle_prop, new GUIContent("Italic Style: "));
font_italicStyle_prop.intValue = Mathf.Clamp(font_italicStyle_prop.intValue, 15, 60);
EditorGUILayout.PropertyField(font_tabSize_prop, new GUIContent("Tab Multiple: "));
EditorGUILayout.EndHorizontal();
EditorGUILayout.EndVertical();
}
GUILayout.Space(5);
// FALLBACK FONT ASSETS
EditorGUI.indentLevel = 0;
if (GUILayout.Button("Fallback Font Assets\t" + (UI_PanelState.fallbackFontAssetPanel ? uiStateLabel[1] : uiStateLabel[0]), TMP_UIStyleManager.Section_Label))
UI_PanelState.fallbackFontAssetPanel = !UI_PanelState.fallbackFontAssetPanel;
if (UI_PanelState.fallbackFontAssetPanel)
{
EditorGUIUtility.labelWidth = 120;
EditorGUILayout.BeginVertical(TMP_UIStyleManager.SquareAreaBox85G);
EditorGUI.indentLevel = 0;
GUILayout.Label("Select the Font Assets that will be searched and used as fallback when characters are missing from this font asset.", TMP_UIStyleManager.Label);
GUILayout.Space(10f);
m_list.DoLayoutList();
EditorGUILayout.EndVertical();
}
// GLYPH INFO TABLE
EditorGUIUtility.labelWidth = labelWidth;
EditorGUIUtility.fieldWidth = fieldWidth;
GUILayout.Space(5);
EditorGUI.indentLevel = 0;
if (GUILayout.Button("Glyph Info\t" + (UI_PanelState.glyphInfoPanel ? uiStateLabel[1] : uiStateLabel[0]), TMP_UIStyleManager.Section_Label))
UI_PanelState.glyphInfoPanel = !UI_PanelState.glyphInfoPanel;
if (UI_PanelState.glyphInfoPanel)
{
int arraySize = m_glyphInfoList_prop.arraySize;
int itemsPerPage = 15;
// Display Glyph Management Tools
EditorGUILayout.BeginVertical(TMP_UIStyleManager.Group_Label, GUILayout.ExpandWidth(true));
{
// Search Bar implementation
#region DISPLAY SEARCH BAR
EditorGUILayout.BeginHorizontal();
{
EditorGUIUtility.labelWidth = 110f;
EditorGUI.BeginChangeCheck();
string searchPattern = EditorGUILayout.TextField("Glyph Search", m_searchPattern, "SearchTextField");
if (EditorGUI.EndChangeCheck() || m_isSearchDirty)
{
if (string.IsNullOrEmpty(searchPattern) == false)
{
//GUIUtility.keyboardControl = 0;
m_searchPattern = searchPattern.ToLower(System.Globalization.CultureInfo.InvariantCulture).Trim();
// Search Glyph Table for potential matches
SearchGlyphTable(m_searchPattern, ref m_searchList);
}
m_isSearchDirty = false;
}
string styleName = string.IsNullOrEmpty(m_searchPattern) ? "SearchCancelButtonEmpty" : "SearchCancelButton";
if (GUILayout.Button(GUIContent.none, styleName))
{
GUIUtility.keyboardControl = 0;
m_searchPattern = string.Empty;
}
}
EditorGUILayout.EndHorizontal();
#endregion
// Display Page Navigation
if (!string.IsNullOrEmpty(m_searchPattern))
arraySize = m_searchList.Count;
DisplayGlyphPageNavigation(arraySize, itemsPerPage);
}
EditorGUILayout.EndVertical();
// Display Glyph Table Elements
#region Glyph Table
if (arraySize > 0)
{
// Display each GlyphInfo entry using the GlyphInfo property drawer.
for (int i = itemsPerPage * m_GlyphPage; i < arraySize && i < itemsPerPage * (m_GlyphPage + 1); i++)
{
// Define the start of the selection region of the element.
Rect elementStartRegion = GUILayoutUtility.GetRect(0f, 0f, GUILayout.ExpandWidth(true));
int elementIndex = i;
if (!string.IsNullOrEmpty(m_searchPattern))
elementIndex = m_searchList[i];
SerializedProperty glyphInfo = m_glyphInfoList_prop.GetArrayElementAtIndex(elementIndex);
EditorGUI.BeginDisabledGroup(i != m_selectedElement);
{
EditorGUILayout.BeginVertical(TMP_UIStyleManager.Group_Label);
EditorGUILayout.PropertyField(glyphInfo);
EditorGUILayout.EndVertical();
}
EditorGUI.EndDisabledGroup();
// Define the end of the selection region of the element.
Rect elementEndRegion = GUILayoutUtility.GetRect(0f, 0f, GUILayout.ExpandWidth(true));
// Check for Item selection
Rect selectionArea = new Rect(elementStartRegion.x, elementStartRegion.y, elementEndRegion.width, elementEndRegion.y - elementStartRegion.y);
if (DoSelectionCheck(selectionArea))
{
m_selectedElement = i;
m_AddGlyphWarning.isEnabled = false;
m_unicodeHexLabel = k_placeholderUnicodeHex;
GUIUtility.keyboardControl = 0;
}
// Draw Selection Highlight and Glyph Options
if (m_selectedElement == i)
{
TMP_EditorUtility.DrawBox(selectionArea, 2f, new Color32(40, 192, 255, 255));
// Draw Glyph management options
Rect controlRect = EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight * 1f);
float optionAreaWidth = controlRect.width * 0.6f;
float btnWidth = optionAreaWidth / 3;
Rect position = new Rect(controlRect.x + controlRect.width * .4f, controlRect.y, btnWidth, controlRect.height);
// Copy Selected Glyph to Target Glyph ID
GUI.enabled = !string.IsNullOrEmpty(m_dstGlyphID);
if (GUI.Button(position, new GUIContent("Copy to")))
{
GUIUtility.keyboardControl = 0;
// Convert Hex Value to Decimal
int dstGlyphID = TMP_TextUtilities.StringToInt(m_dstGlyphID);
//Add new glyph at target Unicode hex id.
if (!AddNewGlyph(elementIndex, dstGlyphID))
{
m_AddGlyphWarning.isEnabled = true;
m_AddGlyphWarning.expirationTime = EditorApplication.timeSinceStartup + 1;
}
m_dstGlyphID = string.Empty;
m_isSearchDirty = true;
TMPro_EventManager.ON_FONT_PROPERTY_CHANGED(true, m_fontAsset);
}
// Target Glyph ID
GUI.enabled = true;
position.x += btnWidth;
GUI.SetNextControlName("GlyphID_Input");
m_dstGlyphID = EditorGUI.TextField(position, m_dstGlyphID);
// Placeholder text
EditorGUI.LabelField(position, new GUIContent(m_unicodeHexLabel, "The Unicode (Hex) ID of the duplicated Glyph"), TMP_UIStyleManager.Label);
// Only filter the input when the destination glyph ID text field has focus.
if (GUI.GetNameOfFocusedControl() == "GlyphID_Input")
{
m_unicodeHexLabel = string.Empty;
//Filter out unwanted characters.
char chr = Event.current.character;
if ((chr < '0' || chr > '9') && (chr < 'a' || chr > 'f') && (chr < 'A' || chr > 'F'))
{
Event.current.character = '\0';
}
}
else
m_unicodeHexLabel = k_placeholderUnicodeHex;
// Remove Glyph
position.x += btnWidth;
if (GUI.Button(position, "Remove"))
{
GUIUtility.keyboardControl = 0;
RemoveGlyphFromList(elementIndex);
m_selectedElement = -1;
m_isSearchDirty = true;
TMPro_EventManager.ON_FONT_PROPERTY_CHANGED(true, m_fontAsset);
return;
}
if (m_AddGlyphWarning.isEnabled && EditorApplication.timeSinceStartup < m_AddGlyphWarning.expirationTime)
{
EditorGUILayout.HelpBox("The Destination Glyph ID already exists", MessageType.Warning);
}
}
}
}
DisplayGlyphPageNavigation(arraySize, itemsPerPage);
}
#endregion
// KERNING TABLE PANEL
#region Kerning Table
GUILayout.Space(5);
if (GUILayout.Button("Kerning Table Info\t" + (UI_PanelState.kerningInfoPanel ? uiStateLabel[1] : uiStateLabel[0]), TMP_UIStyleManager.Section_Label))
UI_PanelState.kerningInfoPanel = !UI_PanelState.kerningInfoPanel;
if (UI_PanelState.kerningInfoPanel)
{
Rect pos;
SerializedProperty kerningPairs_prop = m_kerningInfo_prop.FindPropertyRelative("kerningPairs");
EditorGUILayout.BeginHorizontal();
GUILayout.Label("Left Char", TMP_UIStyleManager.TMP_GUISkin.label);
GUILayout.Label("Right Char", TMP_UIStyleManager.TMP_GUISkin.label);
GUILayout.Label("Offset Value", TMP_UIStyleManager.TMP_GUISkin.label);
GUILayout.Label(GUIContent.none, GUILayout.Width(20));
EditorGUILayout.EndHorizontal();
GUILayout.BeginVertical(TMP_UIStyleManager.TMP_GUISkin.label);
int arraySize = kerningPairs_prop.arraySize;
int itemsPerPage = 25;
if (arraySize > 0)
{
// Display each GlyphInfo entry using the GlyphInfo property drawer.
for (int i = itemsPerPage * m_KerningPage; i < arraySize && i < itemsPerPage * (m_KerningPage + 1); i++)
{
SerializedProperty kerningPair_prop = kerningPairs_prop.GetArrayElementAtIndex(i);
pos = EditorGUILayout.BeginHorizontal();
EditorGUI.PropertyField(new Rect(pos.x, pos.y, pos.width - 20f, pos.height), kerningPair_prop, GUIContent.none);
// Button to Delete Kerning Pair
if (GUILayout.Button("-", GUILayout.ExpandWidth(false)))
{
m_kerningTable.RemoveKerningPair(i);
m_fontAsset.ReadFontDefinition(); // Reload Font Definition.
serializedObject.Update(); // Get an updated version of the SerializedObject.
isAssetDirty = true;
break;
}
EditorGUILayout.EndHorizontal();
}
}
Rect pagePos = EditorGUILayout.GetControlRect(false, 20);
pagePos.width /= 3;
int shiftMultiplier = currentEvent.shift ? 10 : 1;
// Previous Page
if (m_KerningPage > 0) GUI.enabled = true;
else GUI.enabled = false;
if (GUI.Button(pagePos, "Previous Page"))
m_KerningPage -= 1 * shiftMultiplier;
// Page Counter
GUI.enabled = true;
pagePos.x += pagePos.width;
int totalPages = (int)(arraySize / (float)itemsPerPage + 0.999f);
GUI.Label(pagePos, "Page " + (m_KerningPage + 1) + " / " + totalPages, GUI.skin.button);
// Next Page
pagePos.x += pagePos.width;
if (itemsPerPage * (m_GlyphPage + 1) < arraySize) GUI.enabled = true;
else GUI.enabled = false;
if (GUI.Button(pagePos, "Next Page"))
m_KerningPage += 1 * shiftMultiplier;
m_KerningPage = Mathf.Clamp(m_KerningPage, 0, arraySize / itemsPerPage);
GUILayout.EndVertical();
GUILayout.Space(10);
// Add New Kerning Pair Section
GUILayout.BeginVertical(TMP_UIStyleManager.SquareAreaBox85G);
pos = EditorGUILayout.BeginHorizontal();
// Draw Empty Kerning Pair
EditorGUI.PropertyField(new Rect(pos.x, pos.y, pos.width - 20f, pos.height), m_kerningPair_prop);
GUILayout.Label(GUIContent.none, GUILayout.Height(19));
EditorGUILayout.EndHorizontal();
GUILayout.Space(5);
if (GUILayout.Button("Add New Kerning Pair"))
{
int asci_left = m_kerningPair_prop.FindPropertyRelative("AscII_Left").intValue;
int asci_right = m_kerningPair_prop.FindPropertyRelative("AscII_Right").intValue;
float xOffset = m_kerningPair_prop.FindPropertyRelative("XadvanceOffset").floatValue;
errorCode = m_kerningTable.AddKerningPair(asci_left, asci_right, xOffset);
// Sort Kerning Pairs & Reload Font Asset if new kerning pair was added.
if (errorCode != -1)
{
m_kerningTable.SortKerningPairs();
m_fontAsset.ReadFontDefinition(); // Reload Font Definition.
serializedObject.Update(); // Get an updated version of the SerializedObject.
isAssetDirty = true;
}
else
{
timeStamp = System.DateTime.Now.AddSeconds(5);
}
}
if (errorCode == -1)
{
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUILayout.Label("Kerning Pair already <color=#ffff00>exists!</color>", TMP_UIStyleManager.Label);
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
if (System.DateTime.Now > timeStamp)
errorCode = 0;
}
GUILayout.EndVertical();
}
#endregion
if (serializedObject.ApplyModifiedProperties() || evt_cmd == k_UndoRedo || isAssetDirty)
{
//Debug.Log("Serialized properties have changed.");
TMPro_EventManager.ON_FONT_PROPERTY_CHANGED(true, m_fontAsset);
isAssetDirty = false;
EditorUtility.SetDirty(target);
//TMPro_EditorUtility.RepaintAll(); // Consider SetDirty
}
// Clear selection if mouse event was not consumed.
GUI.enabled = true;
if (currentEvent.type == EventType.mouseDown && currentEvent.button == 0)
m_selectedElement = -1;
}
/// <summary>
///
/// </summary>
/// <param name="arraySize"></param>
/// <param name="itemsPerPage"></param>
void DisplayGlyphPageNavigation(int arraySize, int itemsPerPage)
{
Rect pagePos = EditorGUILayout.GetControlRect(false, 20);
pagePos.width /= 3;
int shiftMultiplier = Event.current.shift ? 10 : 1; // Page + Shift goes 10 page forward
// Previous Page
GUI.enabled = m_GlyphPage > 0;
if (GUI.Button(pagePos, "Previous Page"))
{
m_GlyphPage -= 1 * shiftMultiplier;
//m_isNewPage = true;
}
// Page Counter
var pageStyle = new GUIStyle(GUI.skin.button) { normal = { background = null } };
GUI.enabled = true;
pagePos.x += pagePos.width;
int totalPages = (int)(arraySize / (float)itemsPerPage + 0.999f);
GUI.Button(pagePos, "Page " + (m_GlyphPage + 1) + " / " + totalPages, pageStyle);
// Next Page
pagePos.x += pagePos.width;
GUI.enabled = itemsPerPage * (m_GlyphPage + 1) < arraySize;
if (GUI.Button(pagePos, "Next Page"))
{
m_GlyphPage += 1 * shiftMultiplier;
//m_isNewPage = true;
}
// Clamp page range
m_GlyphPage = Mathf.Clamp(m_GlyphPage, 0, arraySize / itemsPerPage);
GUI.enabled = true;
}
/// <summary>
///
/// </summary>
/// <param name="srcGlyphID"></param>
/// <param name="dstGlyphID"></param>
bool AddNewGlyph(int srcIndex, int dstGlyphID)
{
// Make sure Destination Glyph ID doesn't already contain a Glyph
if (m_fontAsset.characterDictionary.ContainsKey(dstGlyphID))
return false;
// Add new element to glyph list.
m_glyphInfoList_prop.arraySize += 1;
// Get a reference to the source glyph.
SerializedProperty sourceGlyph = m_glyphInfoList_prop.GetArrayElementAtIndex(srcIndex);
int dstIndex = m_glyphInfoList_prop.arraySize - 1;
// Get a reference to the target / destination glyph.
SerializedProperty targetGlyph = m_glyphInfoList_prop.GetArrayElementAtIndex(dstIndex);
CopySerializedProperty(sourceGlyph, ref targetGlyph);
// Update the ID of the glyph
targetGlyph.FindPropertyRelative("id").intValue = dstGlyphID;
serializedObject.ApplyModifiedProperties();
m_fontAsset.ReadFontDefinition();
return true;
}
/// <summary>
///
/// </summary>
/// <param name="glyphID"></param>
void RemoveGlyphFromList(int index)
{
if (index > m_glyphInfoList_prop.arraySize)
return;
m_glyphInfoList_prop.DeleteArrayElementAtIndex(index);
serializedObject.ApplyModifiedProperties();
m_fontAsset.ReadFontDefinition();
}
// Check if any of the Style elements were clicked on.
private bool DoSelectionCheck(Rect selectionArea)
{
Event currentEvent = Event.current;
switch (currentEvent.type)
{
case EventType.MouseDown:
if (selectionArea.Contains(currentEvent.mousePosition) && currentEvent.button == 0)
{
currentEvent.Use();
return true;
}
break;
}
return false;
}
/// <summary>
///
/// </summary>
/// <param name="source"></param>
/// <param name="target"></param>
void CopySerializedProperty(SerializedProperty source, ref SerializedProperty target)
{
// TODO : Should make a generic function which copies each of the properties.
target.FindPropertyRelative("id").intValue = source.FindPropertyRelative("id").intValue;
target.FindPropertyRelative("x").floatValue = source.FindPropertyRelative("x").floatValue;
target.FindPropertyRelative("y").floatValue = source.FindPropertyRelative("y").floatValue;
target.FindPropertyRelative("width").floatValue = source.FindPropertyRelative("width").floatValue;
target.FindPropertyRelative("height").floatValue = source.FindPropertyRelative("height").floatValue;
target.FindPropertyRelative("xOffset").floatValue = source.FindPropertyRelative("xOffset").floatValue;
target.FindPropertyRelative("yOffset").floatValue = source.FindPropertyRelative("yOffset").floatValue;
target.FindPropertyRelative("xAdvance").floatValue = source.FindPropertyRelative("xAdvance").floatValue;
target.FindPropertyRelative("scale").floatValue = source.FindPropertyRelative("scale").floatValue;
}
/// <summary>
///
/// </summary>
/// <param name="searchPattern"></param>
/// <returns></returns>
void SearchGlyphTable (string searchPattern, ref List<int> searchResults)
{
if (searchResults == null) searchResults = new List<int>();
searchResults.Clear();
int arraySize = m_glyphInfoList_prop.arraySize;
for (int i = 0; i < arraySize; i++)
{
SerializedProperty sourceGlyph = m_glyphInfoList_prop.GetArrayElementAtIndex(i);
int id = sourceGlyph.FindPropertyRelative("id").intValue;
// Check for potential match against decimal id
if (id.ToString().Contains(searchPattern))
searchResults.Add(i);
if (id.ToString("x").Contains(searchPattern))
searchResults.Add(i);
}
}
}
}
| |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Pathfinding {
using Pathfinding.Util;
/** Implements the funnel algorithm as well as various related methods.
* \see http://digestingduck.blogspot.se/2010/03/simple-stupid-funnel-algorithm.html
* \see FunnelModifier for the component that you can attach to objects to use the funnel algorithm.
*/
public class Funnel {
/** Funnel in which the path to the target will be */
public struct FunnelPortals {
public List<Vector3> left;
public List<Vector3> right;
}
/** Part of a path.
* This is either a sequence of adjacent triangles
* or a link.
* \see NodeLink2
*/
public struct PathPart {
public int startIndex, endIndex;
public Vector3 startPoint, endPoint;
public bool isLink;
}
public static List<PathPart> SplitIntoParts (Path path) {
var nodes = path.path;
var result = ListPool<PathPart>.Claim();
if (nodes == null || nodes.Count == 0) {
return result;
}
// Loop through the path and split it into
// parts joined by links
for (int i = 0; i < nodes.Count; i++) {
if (nodes[i] is TriangleMeshNode || nodes[i] is GridNodeBase) {
var part = new PathPart();
part.startIndex = i;
uint currentGraphIndex = nodes[i].GraphIndex;
// Loop up until we find a node in another graph
// Ignore NodeLink3 nodes
for (; i < nodes.Count; i++) {
if (nodes[i].GraphIndex != currentGraphIndex && !(nodes[i] is NodeLink3Node)) {
break;
}
}
i--;
part.endIndex = i;
// If this is the first part in the path, use the exact start point
// otherwise use the position of the node right before the start of this
// part which is likely the end of the link to this part
if (part.startIndex == 0) {
part.startPoint = path.vectorPath[0];
} else {
part.startPoint = (Vector3)nodes[part.startIndex-1].position;
}
if (part.endIndex == nodes.Count-1) {
part.endPoint = path.vectorPath[path.vectorPath.Count-1];
} else {
part.endPoint = (Vector3)nodes[part.endIndex+1].position;
}
result.Add(part);
} else if (NodeLink2.GetNodeLink(nodes[i]) != null) {
var part = new PathPart();
part.startIndex = i;
var currentGraphIndex = nodes[i].GraphIndex;
for (i++; i < nodes.Count; i++) {
if (nodes[i].GraphIndex != currentGraphIndex) {
break;
}
}
i--;
if (i - part.startIndex == 0) {
// Just ignore it, it might be the case that a NodeLink was the closest node
continue;
} else if (i - part.startIndex != 1) {
throw new System.Exception("NodeLink2 link length greater than two (2) nodes. " + (i - part.startIndex + 1));
}
part.endIndex = i;
part.isLink = true;
part.startPoint = (Vector3)nodes[part.startIndex].position;
part.endPoint = (Vector3)nodes[part.endIndex].position;
result.Add(part);
} else {
throw new System.Exception("Unsupported node type or null node");
}
}
return result;
}
public static FunnelPortals ConstructFunnelPortals (List<GraphNode> nodes, PathPart part) {
// Claim temporary lists and try to find lists with a high capacity
var left = ListPool<Vector3>.Claim(nodes.Count+1);
var right = ListPool<Vector3>.Claim(nodes.Count+1);
if (nodes == null || nodes.Count == 0) {
return new FunnelPortals { left = left, right = right };
}
if (part.endIndex < part.startIndex || part.startIndex < 0 || part.endIndex > nodes.Count) throw new System.ArgumentOutOfRangeException();
// Add start point
left.Add(part.startPoint);
right.Add(part.startPoint);
// Loop through all nodes in the path (except the last one)
for (int i = part.startIndex; i < part.endIndex - 1; i++) {
// Get the portal between path[i] and path[i+1] and add it to the left and right lists
bool portalWasAdded = nodes[i].GetPortal(nodes[i+1], left, right, false);
if (!portalWasAdded) {
// Fallback, just use the positions of the nodes
left.Add((Vector3)nodes[i].position);
right.Add((Vector3)nodes[i].position);
left.Add((Vector3)nodes[i+1].position);
right.Add((Vector3)nodes[i+1].position);
}
}
// Add end point
left.Add(part.endPoint);
right.Add(part.endPoint);
return new FunnelPortals { left = left, right = right };
}
public static void ShrinkPortals (FunnelPortals portals, float shrink) {
if (shrink <= 0.00001f) return;
for (int i = 0; i < portals.left.Count; i++) {
var left = portals.left[i];
var right = portals.right[i];
var length = (left - right).magnitude;
if (length > 0) {
float s = Mathf.Min(shrink / length, 0.4f);
portals.left[i] = Vector3.Lerp(left, right, s);
portals.right[i] = Vector3.Lerp(left, right, 1 - s);
}
}
}
static bool UnwrapHelper (Vector3 portalStart, Vector3 portalEnd, Vector3 prevPoint, Vector3 nextPoint, ref Quaternion mRot, ref Vector3 mOffset) {
// Skip the point if it was on the rotation axis
if (VectorMath.IsColinear(portalStart, portalEnd, nextPoint)) {
return false;
}
var axis = portalEnd - portalStart;
var sqrMagn = axis.sqrMagnitude;
prevPoint -= Vector3.Dot(prevPoint - portalStart, axis)/sqrMagn * axis;
nextPoint -= Vector3.Dot(nextPoint - portalStart, axis)/sqrMagn * axis;
var rot = Quaternion.FromToRotation(nextPoint - portalStart, portalStart - prevPoint);
// The code below is equivalent to these matrix operations (but a lot faster)
// This represents a rotation around a line in 3D space
//mat = mat * Matrix4x4.TRS(portalStart, rot, Vector3.one) * Matrix4x4.TRS(-portalStart, Quaternion.identity, Vector3.one);
mOffset += mRot * (portalStart - rot * portalStart);
mRot *= rot;
return true;
}
/** Unwraps the funnel portals from 3D space to 2D space.
* The result is stored in the \a left and \a right arrays which must have lengths equal to the funnel.left and funnel.right lists.
*
* The input is a funnel like in the image below. It may be rotated and twisted.
* \shadowimage{funnel_unwrap_input.png}
* The output will be a funnel in 2D space like in the image below. All twists and bends will have been straightened out.
* \shadowimage{funnel_unwrap_output.png}
*
* \see Calculate(FunnelPortals,bool,bool)
*/
public static void Unwrap (FunnelPortals funnel, Vector2[] left, Vector2[] right) {
var normal = Vector3.Cross(funnel.right[1] - funnel.left[0], funnel.left[1] - funnel.left[0]);
left[0] = right[0] = Vector2.zero;
var portalLeft = funnel.left[1];
var portalRight = funnel.right[1];
var prevPoint = funnel.left[0];
// The code below is equivalent to this matrix (but a lot faster)
// This represents a rotation around a line in 3D space
// Matrix4x4 m = Matrix4x4.TRS(Vector3.zero, Quaternion.FromToRotation(normal, Vector3.forward), Vector3.one) * Matrix4x4.TRS(-funnel.right[0], Quaternion.identity, Vector3.one);
Quaternion mRot = Quaternion.FromToRotation(normal, Vector3.forward);
Vector3 mOffset = mRot * (-funnel.right[0]);
for (int i = 1; i < funnel.left.Count; i++) {
if (UnwrapHelper(portalLeft, portalRight, prevPoint, funnel.left[i], ref mRot, ref mOffset)) {
prevPoint = portalLeft;
portalLeft = funnel.left[i];
}
left[i] = mRot * funnel.left[i] + mOffset;
if (UnwrapHelper(portalLeft, portalRight, prevPoint, funnel.right[i], ref mRot, ref mOffset)) {
prevPoint = portalRight;
portalRight = funnel.right[i];
}
right[i] = mRot * funnel.right[i] + mOffset;
}
}
/** Try to fix degenerate or invalid funnels.
* \returns The number of vertices at the start of both arrays that should be ignored or -1 if the algorithm failed.
*/
static int FixFunnel (ref Vector2[] left, ref Vector2[] right) {
if (left.Length != right.Length) throw new System.ArgumentException("left and right lists must have equal length");
if (left.Length < 3) {
return -1;
}
int removed = 0;
// Remove identical vertices
while (left[1] == left[2] && right[1] == right[2]) {
// Equivalent to RemoveAt(1) if they would have been lists
left[1] = left[0];
right[1] = right[0];
removed++;
if (left.Length - removed < 3) {
return -1;
}
}
Vector2 swPoint = left[removed + 2];
if (swPoint == left[removed + 1]) {
swPoint = right[removed + 2];
}
//Test
while (VectorMath.IsColinear(left[removed + 0], left[removed + 1], right[removed + 1]) || VectorMath.RightOrColinear(left[removed + 1], right[removed + 1], swPoint) == VectorMath.RightOrColinear(left[removed + 1], right[removed + 1], left[removed + 0])) {
// Equivalent to RemoveAt(1) if they would have been lists
left[removed + 1] = left[removed + 0];
right[removed + 1] = right[removed + 0];
removed++;
if (left.Length - removed < 3) {
return -1;
}
swPoint = left[removed + 2];
if (swPoint == left[removed + 1]) {
swPoint = right[removed + 2];
}
}
// Switch left and right to really be on the "left" and "right" sides
if (!VectorMath.RightOrColinear(left[removed + 0], left[removed + 1], right[removed + 1]) && !VectorMath.IsColinear(left[removed + 0], left[removed + 1], right[removed + 1])) {
var tmp = left;
left = right;
right = tmp;
}
return removed;
}
protected static Vector2 ToXZ (Vector3 p) {
return new Vector2(p.x, p.z);
}
protected static Vector3 FromXZ (Vector2 p) {
return new Vector3(p.x, 0, p.y);
}
/** True if b is to the right of or on the line from (0,0) to a*/
protected static bool RightOrColinear (Vector2 a, Vector2 b) {
return (a.x*b.y - b.x*a.y) <= 0;
}
/** True if b is to the left of or on the line from (0,0) to a */
protected static bool LeftOrColinear (Vector2 a, Vector2 b) {
return (a.x*b.y - b.x*a.y) >= 0;
}
/** Calculate the shortest path through the funnel.
* \param funnel The portals of the funnel. The first and last vertices portals must be single points (so for example left[0] == right[0]).
* \param unwrap Determines if twists and bends should be straightened out before running the funnel algorithm.
* \param splitAtEveryPortal If true, then a vertex will be inserted every time the path crosses a portal
* instead of only at the corners of the path. The result will have exactly one vertex per portal if this is enabled.
* This may introduce vertices with the same position in the output (esp. in corners where many portals meet).
*
* If the unwrap option is disabled the funnel will simply be projected onto the XZ plane.
* If the unwrap option is enabled then the funnel may be oriented arbitrarily and may have twists and bends.
* This makes it possible to support the funnel algorithm in XY space as well as in more complicated cases, such
* as on curved worlds.
* \shadowimage{funnel_unwrap_illustration.png}
*
* \shadowimage{funnel_split_at_every_portal.png}
*
* \see Unwrap
*/
public static List<Vector3> Calculate (FunnelPortals funnel, bool unwrap, bool splitAtEveryPortal) {
var leftArr = new Vector2[funnel.left.Count];
var rightArr = new Vector2[funnel.left.Count];
if (unwrap) {
Unwrap(funnel, leftArr, rightArr);
} else {
// Copy to arrays
for (int i = 0; i < leftArr.Length; i++) {
leftArr[i] = ToXZ(funnel.left[i]);
rightArr[i] = ToXZ(funnel.right[i]);
}
}
var origLeft = leftArr;
int startIndex = FixFunnel(ref leftArr, ref rightArr);
var left3D = funnel.left;
var right3D = funnel.right;
if (origLeft != leftArr) {
// Flipped order
left3D = funnel.right;
right3D = funnel.left;
}
var intermediateResult = ListPool<int>.Claim();
if (startIndex == -1) {
// If funnel algorithm failed, degrade to simple line
intermediateResult.Add(0);
intermediateResult.Add(funnel.left.Count - 1);
} else {
bool lastCorner;
Calculate(leftArr, rightArr, startIndex, intermediateResult, int.MaxValue, out lastCorner);
}
// Get list for the final result
var result = ListPool<Vector3>.Claim(intermediateResult.Count);
Vector2 prev2D = leftArr[0];
var prevIdx = 0;
for (int i = 0; i < intermediateResult.Count; i++) {
var idx = intermediateResult[i];
if (splitAtEveryPortal) {
// Check intersections with every portal segment
var next2D = idx >= 0 ? leftArr[idx] : rightArr[-idx];
for (int j = prevIdx + 1; j < System.Math.Abs(idx); j++) {
var factor = VectorMath.LineIntersectionFactorXZ(FromXZ(leftArr[j]), FromXZ(rightArr[j]), FromXZ(prev2D), FromXZ(next2D));
result.Add(Vector3.Lerp(left3D[j], right3D[j], factor));
}
prevIdx = Mathf.Abs(idx);
prev2D = next2D;
}
if (idx >= 0) {
result.Add(left3D[idx]);
} else {
result.Add(right3D[-idx]);
}
}
// Release lists back to the pool
ListPool<Vector3>.Release(funnel.left);
ListPool<Vector3>.Release(funnel.right);
ListPool<int>.Release(intermediateResult);
return result;
}
/** Funnel algorithm.
* \a funnelPath will be filled with the result.
* The result is the indices of the vertices that were picked, a non-negative value refers to the corresponding index in the
* \a left array, a negative value refers to the corresponding index in the right array.
* So e.g 5 corresponds to left[5] and -2 corresponds to right[2]
*
* \see http://digestingduck.blogspot.se/2010/03/simple-stupid-funnel-algorithm.html
*/
static void Calculate (Vector2[] left, Vector2[] right, int startIndex, List<int> funnelPath, int maxCorners, out bool lastCorner) {
if (left.Length != right.Length) throw new System.ArgumentException();
lastCorner = false;
int apexIndex = startIndex + 0;
int rightIndex = startIndex + 1;
int leftIndex = startIndex + 1;
Vector2 portalApex = left[apexIndex];
Vector2 portalLeft = left[leftIndex];
Vector2 portalRight = right[rightIndex];
funnelPath.Add(apexIndex);
for (int i = startIndex + 2; i < left.Length; i++) {
if (funnelPath.Count >= maxCorners) {
return;
}
if (funnelPath.Count > 2000) {
Debug.LogWarning("Avoiding infinite loop. Remove this check if you have this long paths.");
break;
}
Vector2 pLeft = left[i];
Vector2 pRight = right[i];
if (LeftOrColinear(portalRight - portalApex, pRight - portalApex)) {
if (portalApex == portalRight || RightOrColinear(portalLeft - portalApex, pRight - portalApex)) {
portalRight = pRight;
rightIndex = i;
} else {
portalApex = portalRight = portalLeft;
i = apexIndex = rightIndex = leftIndex;
funnelPath.Add(apexIndex);
continue;
}
}
if (RightOrColinear(portalLeft - portalApex, pLeft - portalApex)) {
if (portalApex == portalLeft || LeftOrColinear(portalRight - portalApex, pLeft - portalApex)) {
portalLeft = pLeft;
leftIndex = i;
} else {
portalApex = portalLeft = portalRight;
i = apexIndex = leftIndex = rightIndex;
// Negative value because we are referring
// to the right side
funnelPath.Add(-apexIndex);
continue;
}
}
}
lastCorner = true;
funnelPath.Add(left.Length-1);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Ical.Net.DataTypes;
using NodaTime;
using NodaTime.TimeZones;
namespace Ical.Net.Utility
{
internal static class DateUtil
{
public static IDateTime StartOfDay(IDateTime dt)
=> dt.AddHours(-dt.Hour).AddMinutes(-dt.Minute).AddSeconds(-dt.Second);
public static IDateTime EndOfDay(IDateTime dt)
=> StartOfDay(dt).AddDays(1).AddTicks(-1);
public static DateTime GetSimpleDateTimeData(IDateTime dt)
=> DateTime.SpecifyKind(dt.Value, dt.IsUtc ? DateTimeKind.Utc : DateTimeKind.Local);
public static DateTime SimpleDateTimeToMatch(IDateTime dt, IDateTime toMatch)
{
if (toMatch.IsUtc && dt.IsUtc)
{
return dt.Value;
}
if (toMatch.IsUtc)
{
return dt.Value.ToUniversalTime();
}
if (dt.IsUtc)
{
return dt.Value.ToLocalTime();
}
return dt.Value;
}
public static IDateTime MatchTimeZone(IDateTime dt1, IDateTime dt2)
{
// Associate the date/time with the first.
var copy = dt2;
copy.AssociateWith(dt1);
// If the dt1 time does not occur in the same time zone as the
// dt2 time, then let's convert it so they can be used in the
// same context (i.e. evaluation).
if (dt1.TzId != null)
{
return string.Equals(dt1.TzId, copy.TzId, StringComparison.OrdinalIgnoreCase)
? copy
: copy.ToTimeZone(dt1.TzId);
}
return dt1.IsUtc
? new CalDateTime(copy.AsUtc)
: new CalDateTime(copy.AsSystemLocal);
}
public static DateTime AddWeeks(DateTime dt, int interval, DayOfWeek firstDayOfWeek)
{
// NOTE: fixes WeeklyUntilWkst2() eval.
// NOTE: simplified the execution of this - fixes bug #3119920 - missing weekly occurences also
dt = dt.AddDays(interval * 7);
while (dt.DayOfWeek != firstDayOfWeek)
{
dt = dt.AddDays(-1);
}
return dt;
}
public static DateTime FirstDayOfWeek(DateTime dt, DayOfWeek firstDayOfWeek, out int offset)
{
offset = 0;
while (dt.DayOfWeek != firstDayOfWeek)
{
dt = dt.AddDays(-1);
offset++;
}
return dt;
}
private static readonly Lazy<Dictionary<string, string>> _windowsMapping
= new Lazy<Dictionary<string, string>>(InitializeWindowsMappings, LazyThreadSafetyMode.PublicationOnly);
private static Dictionary<string, string> InitializeWindowsMappings()
=> TzdbDateTimeZoneSource.Default.WindowsMapping.PrimaryMapping
.ToDictionary(k => k.Key, v => v.Value, StringComparer.OrdinalIgnoreCase);
public static readonly DateTimeZone LocalDateTimeZone = DateTimeZoneProviders.Tzdb.GetSystemDefault();
/// <summary>
/// Use this method to turn a raw string into a NodaTime DateTimeZone. It searches all time zone providers (IANA, BCL, serialization, etc) to see if
/// the string matches. If it doesn't, it walks each provider, and checks to see if the time zone the provider knows about is contained within the
/// target time zone string. Some older icalendar programs would generate nonstandard time zone strings, and this secondary check works around
/// that.
/// </summary>
/// <param name="tzId">A BCL, IANA, or serialization time zone identifier</param>
/// <param name="useLocalIfNotFound">If true, this method will return the system local time zone if tzId doesn't match a known time zone identifier.
/// Otherwise, it will throw an exception.</param>
public static DateTimeZone GetZone(string tzId, bool useLocalIfNotFound = true)
{
if (string.IsNullOrWhiteSpace(tzId))
{
return LocalDateTimeZone;
}
if (tzId.StartsWith("/", StringComparison.OrdinalIgnoreCase))
{
tzId = tzId.Substring(1, tzId.Length - 1);
}
var zone = DateTimeZoneProviders.Tzdb.GetZoneOrNull(tzId);
if (zone != null)
{
return zone;
}
if (_windowsMapping.Value.TryGetValue(tzId, out var ianaZone))
{
return DateTimeZoneProviders.Tzdb.GetZoneOrNull(ianaZone);
}
zone = DateTimeZoneProviders.Serialization.GetZoneOrNull(tzId);
if (zone != null)
{
return zone;
}
//US/Eastern is commonly represented as US-Eastern
var newTzId = tzId.Replace("-", "/");
zone = DateTimeZoneProviders.Serialization.GetZoneOrNull(newTzId);
if (zone != null)
{
return zone;
}
foreach (var providerId in DateTimeZoneProviders.Tzdb.Ids.Where(tzId.Contains))
{
return DateTimeZoneProviders.Tzdb.GetZoneOrNull(providerId);
}
if (_windowsMapping.Value.Keys
.Where(tzId.Contains)
.Any(providerId => _windowsMapping.Value.TryGetValue(providerId, out ianaZone))
)
{
return DateTimeZoneProviders.Tzdb.GetZoneOrNull(ianaZone);
}
foreach (var providerId in DateTimeZoneProviders.Serialization.Ids.Where(tzId.Contains))
{
return DateTimeZoneProviders.Serialization.GetZoneOrNull(providerId);
}
if (useLocalIfNotFound)
{
return LocalDateTimeZone;
}
throw new ArgumentException($"Unrecognized time zone id {tzId}");
}
public static ZonedDateTime AddYears(ZonedDateTime zonedDateTime, int years)
{
var futureDate = zonedDateTime.Date.PlusYears(years);
var futureLocalDateTime = new LocalDateTime(futureDate.Year, futureDate.Month, futureDate.Day, zonedDateTime.Hour, zonedDateTime.Minute,
zonedDateTime.Second);
var zonedFutureDate = new ZonedDateTime(futureLocalDateTime, zonedDateTime.Zone, zonedDateTime.Offset);
return zonedFutureDate;
}
public static ZonedDateTime AddMonths(ZonedDateTime zonedDateTime, int months)
{
var futureDate = zonedDateTime.Date.PlusMonths(months);
var futureLocalDateTime = new LocalDateTime(futureDate.Year, futureDate.Month, futureDate.Day, zonedDateTime.Hour, zonedDateTime.Minute,
zonedDateTime.Second);
var zonedFutureDate = new ZonedDateTime(futureLocalDateTime, zonedDateTime.Zone, zonedDateTime.Offset);
return zonedFutureDate;
}
public static ZonedDateTime ToZonedDateTimeLeniently(DateTime dateTime, string tzId)
{
var zone = GetZone(tzId);
var localDt = LocalDateTime.FromDateTime(dateTime); //19:00 UTC
var lenientZonedDateTime = localDt.InZoneLeniently(zone).WithZone(zone); //15:00 Eastern
return lenientZonedDateTime;
}
public static ZonedDateTime FromTimeZoneToTimeZone(DateTime dateTime, string fromZoneId, string toZoneId)
=> FromTimeZoneToTimeZone(dateTime, GetZone(fromZoneId), GetZone(toZoneId));
public static ZonedDateTime FromTimeZoneToTimeZone(DateTime dateTime, DateTimeZone fromZone, DateTimeZone toZone)
{
var oldZone = LocalDateTime.FromDateTime(dateTime).InZoneLeniently(fromZone);
var newZone = oldZone.WithZone(toZone);
return newZone;
}
public static bool IsSerializationTimeZone(DateTimeZone zone) => DateTimeZoneProviders.Serialization.GetZoneOrNull(zone.Id) != null;
/// <summary>
/// Truncate to the specified TimeSpan's magnitude. For example, to truncate to the nearest second, use TimeSpan.FromSeconds(1)
/// </summary>
/// <param name="dateTime"></param>
/// <param name="timeSpan"></param>
/// <returns></returns>
public static DateTime Truncate(this DateTime dateTime, TimeSpan timeSpan)
=> timeSpan == TimeSpan.Zero
? dateTime
: dateTime.AddTicks(-(dateTime.Ticks % timeSpan.Ticks));
public static int WeekOfMonth(DateTime d)
{
var isExact = d.Day % 7 == 0;
var offset = isExact
? 0
: 1;
return (int) Math.Floor(d.Day / 7.0) + offset;
}
}
}
| |
// -------------------------------------
// Domain : Avariceonline.com
// Author : Nicholas Ventimiglia
// Product : Unity3d Foundation
// Published : 2015
// -------------------------------------
using System;
using System.Linq;
using Foundation.Databinding;
using UnityEngine;
using UnityEngine.UI;
namespace Foundation.Example
{
public enum ExampleQuality
{
Normal,
Good,
Bad,
Fast,
Faster,
Pretty,
Nice,
Ok,
Lovely,
Anime,
FOUNDATION
}
/// <summary>
/// Example Options Menu
/// </summary>
[AddComponentMenu("Foundation/Examples/ExampleOptions")]
public class ExampleOptions : ObservableBehaviour
{
#region UE
protected override void Awake()
{
base.Awake();
Qualities = Enum.GetValues(typeof(ExampleQuality)).Cast<ExampleQuality>().ToArray();
CurrentQuality = ExampleQuality.Fast;
Load();
}
#endregion
#region view logic
private bool _isVisible;
public bool IsVisible
{
get { return _isVisible; }
set
{
if (_isVisible == value)
return;
_isVisible = value;
NotifyProperty("IsVisible", value);
}
}
public void SaveAndClose()
{
Save();
IsVisible = false;
}
#endregion
#region option event
public Text Output;
/// <summary>
/// Raised when an option value changes
/// </summary>
public event Action<string, object> OnOptionChanged;
public override void NotifyProperty(string memberName, object paramater)
{
base.NotifyProperty(memberName, paramater);
if (OnOptionChanged != null)
OnOptionChanged(memberName, paramater);
Output.text = string.Format("{0} = {1}", memberName, paramater);
}
#endregion
#region model
[SerializeField] private float _soundVolume = 1;
public float SoundVolume
{
get { return _soundVolume; }
set
{
if (_soundVolume == value)
return;
_soundVolume = value;
NotifyProperty("SoundVolume", value);
// update service
AudioManager.SetVolume(AudioLayer.Sfx, value);
AudioManager.SetVolume(AudioLayer.UISfx, value);
}
}
[SerializeField] private float _musicVolume = 1;
public float MusicVolume
{
get { return _musicVolume; }
set
{
if (_musicVolume == value)
return;
_musicVolume = value;
NotifyProperty("MusicVolume", value);
// update service
AudioManager.SetVolume(AudioLayer.Music, value);
}
}
[SerializeField] private bool _useCensor = true;
public bool UseCensor
{
get { return _useCensor; }
set { Set(ref _useCensor, value); }
}
[SerializeField] private string _userName = "Player 1";
public string UserName
{
get { return _userName; }
set
{
if (_userName == value)
return;
_userName = value;
NotifyProperty("UserName", value);
// todo update service
}
}
private int _qualityIndex;
public int QualityIndex
{
get { return _qualityIndex; }
set
{
if (_qualityIndex == value)
return;
_qualityIndex = value;
NotifyProperty("QualityIndex", value);
}
}
[SerializeField]
private ExampleQuality[] _quality;
public ExampleQuality[] Qualities
{
get { return _quality; }
set
{
if (_quality == value)
return;
_quality = value;
NotifyProperty("Qualities", value);
}
}
private ExampleQuality _currentQuality;
public ExampleQuality CurrentQuality
{
get { return _currentQuality; }
set
{
if (_currentQuality == value)
return;
_currentQuality = value;
NotifyProperty("CurrentQuality", value);
}
}
#endregion
#region Save / Load
public void Save()
{
PlayerPrefs.SetFloat("ExampleOptions.MusicVolume", MusicVolume);
PlayerPrefs.SetFloat("ExampleOptions.SoundVolume", SoundVolume);
PlayerPrefs.SetInt("ExampleOptions.UseCensor", UseCensor ? 1 : 0);
PlayerPrefs.SetString("ExampleOptions.UserName", UserName);
PlayerPrefs.Save();
}
public void Load()
{
MusicVolume = PlayerPrefs.GetFloat("ExampleOptions.MusicVolume", MusicVolume);
SoundVolume = PlayerPrefs.GetFloat("ExampleOptions.SoundVolume", SoundVolume);
UseCensor = PlayerPrefs.GetInt("ExampleOptions.UseCensor", UseCensor ? 1 : 0) == 1;
UserName = PlayerPrefs.GetString("ExampleOptions.UserName", UserName);
}
#endregion
}
}
| |
using System;
using Microsoft.Win32;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NetOffice.DeveloperToolbox.ToolboxControls.ProjectWizard.ProjectConverters
{
/// <summary>
/// Represents a project converter
/// </summary>
internal abstract class Converter : IDisposable
{
#region Fields
private ProjectOptions _options;
private Guid _tempGuid;
private string _tempPath;
#endregion
#region Ctor
internal Converter(ProjectOptions options)
{
_options = options;
_tempGuid = Guid.NewGuid();
_tempPath = Path.Combine(Path.GetTempPath(), _tempGuid.ToString());
Directory.CreateDirectory(_tempPath);
Directory.CreateDirectory(TempSolutionPath);
Directory.CreateDirectory(TempProjectPath);
Directory.CreateDirectory(TempPropertiesPath);
Directory.CreateDirectory(TempNetOfficePath);
Environments = new EnvironmentVersions();
SolutionFormats = new SolutionFormatVersions();
Tools = new ToolsVersions();
Runtimes = new RuntimeVersions();
}
#endregion
#region Properties
protected internal EnvironmentVersions Environments { get; private set; }
protected internal SolutionFormatVersions SolutionFormats { get; private set; }
protected internal ToolsVersions Tools { get; private set; }
protected internal RuntimeVersions Runtimes { get; private set; }
protected internal ProjectOptions Options
{
get
{
return _options;
}
}
protected internal string TargetSolutionFile
{
get
{
string targetFolder = Path.Combine(_options.ProjectFolder, _options.AssemblyName, _options.AssemblyName + ".sln");
return targetFolder;
}
}
protected internal string TargetSolutionPath
{
get
{
string targetFolder = Path.Combine(_options.ProjectFolder, _options.AssemblyName);
return targetFolder;
}
}
protected internal string TargetProjectPath
{
get
{
string targetFolder = Path.Combine(_options.ProjectFolder, _options.AssemblyName);
targetFolder = Path.Combine(targetFolder, _options.AssemblyName);
return targetFolder;
}
}
protected internal string TempPath
{
get
{
return _tempPath;
}
}
protected internal string TempSolutionPath
{
get
{
string targetFolder = Path.Combine(_tempPath, _options.AssemblyName);
return targetFolder;
}
}
protected internal string TempProjectPath
{
get
{
string targetFolder = Path.Combine(_tempPath, _options.AssemblyName, _options.AssemblyName);
return targetFolder;
}
}
protected internal string TempPropertiesPath
{
get
{
if (Options.Language == ProgrammingLanguage.CSharp)
{
string targetFolder = Path.Combine(_tempPath, _options.AssemblyName, _options.AssemblyName, "Properties");
return targetFolder;
}
else
{
string targetFolder = Path.Combine(_tempPath, _options.AssemblyName, _options.AssemblyName, "My Project");
return targetFolder;
}
}
}
protected internal string TempNetOfficePath
{
get
{
string targetFolder = Path.Combine(_tempPath, _options.AssemblyName, "NetOffice");
return targetFolder;
}
}
protected internal object TryGetRegistryValue(RegistryHive hive, string path, string valueName = "")
{
RegistryKey hiveKey;
switch (hive)
{
case RegistryHive.HKEY_Local_Machine:
hiveKey = Registry.LocalMachine;
break;
case RegistryHive.HKEY_Current_User:
hiveKey = Registry.CurrentUser;
break;
default:
throw new ArgumentOutOfRangeException("hive");
}
RegistryKey subKey = hiveKey.OpenSubKey(path);
if(null != subKey)
{
object result = subKey.GetValue(valueName, null);
subKey.Close();
subKey.Dispose();
return result;
}
else
return null;
}
#endregion
#region Methods
/// <summary>
/// Create a Converter instance depending on project options
/// </summary>
/// <param name="options">conversion options</param>
/// <returns></returns>
public static Converter CreateConverter(ProjectOptions options)
{
ValidateOptions(options);
switch (options.ProjectType)
{
case ProjectType.SimpleAddin:
{
switch (options.Language)
{
case ProgrammingLanguage.CSharp:
if(options.OfficeApps.Length > 1)
return new SimpleMultiAddinConverterCS(options);
else
return new SimpleSingleAddinConverterCS(options);
case ProgrammingLanguage.VB:
if (options.OfficeApps.Length > 1)
return new SimpleMultiAddinConverterVB(options);
else
return new SimpleSingleAddinConverterVB(options);
default:
throw new ArgumentOutOfRangeException("language");
}
}
case ProjectType.NetOfficeAddin:
{
switch (options.Language)
{
case ProgrammingLanguage.CSharp:
if (options.OfficeApps.Length > 1)
return new ToolsMultiAddinConverterCS(options);
else
return new ToolsSingleAddinConverterCS(options);
case ProgrammingLanguage.VB:
if (options.OfficeApps.Length > 1)
return new ToolsMultiAddinConverterVB(options);
else
return new ToolsSingleAddinConverterVB(options);
default:
throw new ArgumentOutOfRangeException("language");
}
}
case ProjectType.WindowsForms:
{
switch (options.Language)
{
case ProgrammingLanguage.CSharp:
return new WindowsFormsConverterCS(options);
case ProgrammingLanguage.VB:
return new WindowsFormsConverterVB(options);
default:
throw new ArgumentOutOfRangeException("language");
}
}
case ProjectType.ClassLibrary:
{
switch (options.Language)
{
case ProgrammingLanguage.CSharp:
return new ClassLibraryConverterCS(options);
case ProgrammingLanguage.VB:
return new ClassLibraryConverterVB(options);
default:
throw new ArgumentOutOfRangeException("language");
}
}
case ProjectType.Console:
{
switch (options.Language)
{
case ProgrammingLanguage.CSharp:
return new ConsoleConverterCS(options);
case ProgrammingLanguage.VB:
return new ConsoleConverterVB(options);
default:
throw new ArgumentOutOfRangeException("language");
}
}
default:
throw new ArgumentOutOfRangeException("ProjectType");
}
}
public static string ConvertLoadBehavoir(int i)
{
switch (i)
{
case 3:
return "LoadBehavior.LoadAtStartup";
case 0:
return "LoadBehavior.DoNotLoad";
case 1:
return "LoadBehavior.LoadOnDemand";
case 16:
return "LoadBehavior.LoadOnce";
default:
return i.ToString();
}
}
/// <summary>
/// Create new solution
/// </summary>
/// <returns>result folder path</returns>
public abstract string CreateSolution();
protected internal string ValidateFileContentFormat(string fileContent)
{
if (Options.Language == ProgrammingLanguage.CSharp)
{
StringBuilder validatedAddinFile = new StringBuilder();
string[] lines = fileContent.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
bool lastLineEmpty = false;
foreach (var item in lines)
{
if (item.Length == 0)
{
if (false == lastLineEmpty)
{
validatedAddinFile.AppendLine(item);
lastLineEmpty = true;
}
}
else
{
string tempItem = item.Replace("\t", String.Empty).Replace(" ", String.Empty);
if (!String.IsNullOrWhiteSpace(tempItem))
{
validatedAddinFile.AppendLine(item);
lastLineEmpty = false;
}
else
lastLineEmpty = true;
if (tempItem == "{")
lastLineEmpty = true;
}
}
fileContent = validatedAddinFile.ToString();
fileContent = fileContent.Replace("#endregion\r\n\r\n\t}\r\n}", "#endregion\r\n\t}\r\n}");
return fileContent;
}
else
{
fileContent = fileContent.Replace("#Region \"", "#Region \" ");
StringBuilder validatedAddinFile = new StringBuilder();
string[] lines = fileContent.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
bool lastLineEmpty = false;
foreach (var item in lines)
{
if (item.Length == 0)
{
if (false == lastLineEmpty)
{
validatedAddinFile.AppendLine(item);
lastLineEmpty = true;
}
}
else
{
string tempItem = item.Replace("\t", String.Empty).Replace(" ", String.Empty);
if (!String.IsNullOrWhiteSpace(tempItem))
{
validatedAddinFile.AppendLine(item);
lastLineEmpty = false;
}
else
lastLineEmpty = true;
if (tempItem == "{")
lastLineEmpty = true;
}
}
fileContent = validatedAddinFile.ToString();
fileContent = fileContent.Replace("#End Region\r\n\r\n\r\n}", "#End Region\r\n\r\n}");
return fileContent;
}
}
protected internal string ReadProjectTemplateFile(string address)
{
return Resources.ResourceUtils.ReadString("ToolboxControls.ProjectWizard.ProjectTemplates." + address);
}
protected internal void MoveTempSolutionFolderToTarget()
{
if (!Directory.Exists(TargetSolutionPath))
FileSystem.DirectoryMove(TempSolutionPath, TargetSolutionPath);
else
throw new InvalidOperationException("Directory already exists.");
}
protected internal string GetNetOfficeProjectReferenceItems()
{
string[] officeApps = Options.OfficeApps;
StringBuilder sb = new StringBuilder();
string templateItem = " <Reference Include=\"%Name%, Version=" + Program.CurrentNetOfficeVersion + ", Culture=neutral, processorArchitecture=MSIL\">\r\n" +
" <SpecificVersion>False</SpecificVersion>\r\n" +
" <HintPath>..\\NetOffice\\%RealName%.dll</HintPath>\r\n" +
" </Reference>";
List<string> apps = CreateValidatedReferenceList(officeApps);
foreach (string app in apps)
sb.Append(templateItem.Replace("%Name%", app).Replace("%RealName%", app + "Api") + Environment.NewLine);
sb.Append(templateItem.Replace("%Name%", "NetOffice").Replace("%RealName%", "NetOffice"));
return sb.ToString();
}
protected internal string GetNetOfficeProjectUsingItems()
{
string[] officeApps = Options.OfficeApps;
ProgrammingLanguage language = Options.Language;
StringBuilder sb = new StringBuilder();
string usingTemplateCSharp = "using %Alias% = NetOffice.%Name%Api;\r\nusing NetOffice.%Name%Api.Enums;";
string usingTemplateVB = "Imports %Alias% = NetOffice.%Name%Api\r\nImports NetOffice.%Name%Api.Enums";
List<string> apps = CreateValidatedReferenceList(officeApps);
if (language == ProgrammingLanguage.CSharp)
sb.Append("using NetOffice;" + Environment.NewLine);
else
sb.Append("Imports NetOffice" + Environment.NewLine);
foreach (string app in apps)
{
if (language == ProgrammingLanguage.CSharp)
sb.Append(usingTemplateCSharp.Replace("%Alias%", app).Replace("%Name%", app) + Environment.NewLine);
else
sb.Append(usingTemplateVB.Replace("%Alias%", app).Replace("%Name%", app) + Environment.NewLine);
}
return sb.ToString();
}
protected internal string GetNetOfficeProjectUsingToolsItems()
{
string[] officeApps = Options.OfficeApps;
ProgrammingLanguage language = Options.Language;
StringBuilder sb = new StringBuilder();
string usingTemplateCSharp = "using %Alias% = NetOffice.%Name%Api;\r\nusing NetOffice.%Name%Api.Enums;";
string usingTemplateVB = "Imports %Alias% = NetOffice.%Name%Api\r\nImports NetOffice.%Name%Api.Enums";
List<string> apps = CreateValidatedReferenceList(officeApps);
if (language == ProgrammingLanguage.CSharp)
{
sb.Append("using NetOffice;" + Environment.NewLine);
sb.Append("using NetOffice.Tools;" + Environment.NewLine);
}
else
{
sb.Append("Imports NetOffice" + Environment.NewLine);
sb.Append("Imports NetOffice.Tools" + Environment.NewLine);
}
foreach (string app in apps)
{
if (language == ProgrammingLanguage.CSharp)
{
if (IsToolsUsing(app))
{
sb.Append(usingTemplateCSharp.Replace("%Alias%", app).Replace("%Name%", app) + Environment.NewLine);
sb.Append("using NetOffice.%Name%Api.Tools;".Replace("%Name%", app) + Environment.NewLine);
}
else
sb.Append(usingTemplateCSharp.Replace("%Alias%", app).Replace("%Name%", app) + Environment.NewLine);
}
else
{
if (IsToolsUsing(app))
{
sb.Append(usingTemplateVB.Replace("%Alias%", app).Replace("%Name%", app) + Environment.NewLine);
sb.Append("Imports NetOffice.%Name%Api.Tools".Replace("%Name%", app) + Environment.NewLine);
}
else
sb.Append(usingTemplateVB.Replace("%Alias%", app).Replace("%Name%", app) + Environment.NewLine);
}
}
return sb.ToString();
}
private bool IsToolsUsing(string app)
{
switch (app)
{
case "Office":
case "Excel":
case "Access":
case "Outlook":
case "Word":
case "MSProject":
case "PowerPoint":
case "Publisher":
return true;
default:
return false;
}
}
protected internal void CopyUsedNetOfficeAssembliesToTempTarget()
{
string[] officeApps = Options.OfficeApps;
NetVersion runtime = Options.NetRuntime;
List<string> apps = CreateValidatedReferenceList(officeApps);
string assembliesFolderPath = Program.DependencySubFolder;
if(!Directory.Exists(assembliesFolderPath))
assembliesFolderPath = Program.DependencyReleaseSubFolder;
string assembliesTempTarget = TempNetOfficePath;
File.Copy(Path.Combine(assembliesFolderPath, "NetOffice.dll"), Path.Combine(assembliesTempTarget, "NetOffice.dll"));
foreach (var item in apps)
File.Copy(Path.Combine(assembliesFolderPath, item + "Api.dll"), Path.Combine(assembliesTempTarget, item + "Api.dll"));
File.Copy(Path.Combine(assembliesFolderPath, "NetOffice.xml"), Path.Combine(assembliesTempTarget, "NetOffice.xml"));
foreach (var item in apps)
File.Copy(Path.Combine(assembliesFolderPath, item + "Api.xml"), Path.Combine(assembliesTempTarget, item + "Api.xml"));
File.Copy(Path.Combine(assembliesFolderPath, "NetOffice.pdb"), Path.Combine(assembliesTempTarget, "NetOffice.pdb"));
foreach (var item in apps)
File.Copy(Path.Combine(assembliesFolderPath, item + "Api.pdb"), Path.Combine(assembliesTempTarget, item + "Api.pdb"));
//if (runtime == NetVersion.Net4 || runtime == NetVersion.Net4Client)
//{
// File.Copy(Path.Combine(assembliesFolderPath, "NetOffice.dll"), Path.Combine(assembliesTempTarget, "NetOffice.dll"));
// foreach (var item in apps)
// File.Copy(Path.Combine(assembliesFolderPath, item + "Api.dll"), Path.Combine(assembliesTempTarget, item + "Api.dll"));
//}
//else
//{
// string targetPackageName = null;
// switch (runtime)
// {
// case NetVersion.Net2:
// targetPackageName = Path.Combine(assembliesFolderPath, "2.0.zip");
// break;
// case NetVersion.Net3:
// case NetVersion.Net35:
// targetPackageName = Path.Combine(assembliesFolderPath, "3.0.zip");
// break;
// case NetVersion.Net45:
// targetPackageName = Path.Combine(assembliesFolderPath, "4.5.zip");
// break;
// default:
// throw new ArgumentOutOfRangeException("runtime");
// }
// using (ZipFile zip = new ZipFile(targetPackageName))
// {
// Stream streamFirst = zip.GetInputStream(zip.GetEntry("NetOffice.dll"));
// FileStream fileStreamFirst = File.Create(Path.Combine(assembliesTempTarget, "NetOffice.dll"));
// streamFirst.CopyTo(fileStreamFirst);
// fileStreamFirst.Close();
// foreach (var item in apps)
// {
// Stream stream = zip.GetInputStream(zip.GetEntry(item + "Api.dll"));
// FileStream fileStream = File.Create(Path.Combine(assembliesTempTarget, item + "Api.dll"));
// stream.CopyTo(fileStream);
// fileStream.Close();
// }
// }
//}
}
private static List<string> CreateValidatedReferenceList(string[] officeApps)
{
List<string> apps = new List<string>();
List<String> dependecies = new List<string>();
foreach (var item in officeApps)
apps.Add(item);
foreach (var item in apps)
{
switch (item)
{
case "Excel":
if (!dependecies.Any(a => a == "Office"))
dependecies.Add("Office");
if (!dependecies.Any(a => a == "VBIDE"))
dependecies.Add("VBIDE");
break;
case "Word":
if (!dependecies.Any(a => a == "Office"))
dependecies.Add("Office");
if (!dependecies.Any(a => a == "VBIDE"))
dependecies.Add("VBIDE");
break;
case "Outlook":
if (!dependecies.Any(a => a == "Office"))
dependecies.Add("Office");
break;
case "PowerPoint":
if (!dependecies.Any(a => a == "Office"))
dependecies.Add("Office");
if (!dependecies.Any(a => a == "VBIDE"))
dependecies.Add("VBIDE");
break;
case "Access":
if (!dependecies.Any(a => a == "Office"))
dependecies.Add("Office");
if (!dependecies.Any(a => a == "VBIDE"))
dependecies.Add("VBIDE");
if (!dependecies.Any(a => a == "DAO"))
dependecies.Add("DAO");
if (!dependecies.Any(a => a == "ADODB"))
dependecies.Add("ADODB");
if (!dependecies.Any(a => a == "OWC10"))
dependecies.Add("OWC10");
if (!dependecies.Any(a => a == "MSDATASRC"))
dependecies.Add("MSDATASRC");
if (!dependecies.Any(a => a == "MSComctlLib"))
dependecies.Add("MSComctlLib");
break;
case "MSProject":
if (!dependecies.Any(a => a == "Office"))
dependecies.Add("Office");
if (!dependecies.Any(a => a == "VBIDE"))
dependecies.Add("VBIDE");
if (!dependecies.Any(a => a == "MSHTML"))
dependecies.Add("MSHTML");
break;
case "Visio":
break;
default:
break;
}
}
foreach (var item in dependecies)
apps.Add(item);
return apps;
}
#endregion
#region IDisposable
public void Dispose()
{
if (Directory.Exists(_tempPath))
Directory.Delete(_tempPath, true);
}
#endregion
#region Privates
private static void ValidateOptions(ProjectOptions options)
{
switch (options.NetRuntime)
{
case NetVersion.Net45:
if (options.IDE != IDE.VS20131517)
throw new ArgumentException("Invalid Framework=>IDE settings");
break;
}
}
#endregion
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System.Linq;
namespace Anima2D
{
[InitializeOnLoad]
public class Gizmos
{
static List<Bone2D> s_Bones = new List<Bone2D>();
static List<Control> s_Controls = new List<Control>();
static Gizmos()
{
EditorApplication.hierarchyWindowChanged += HierarchyWindowChanged;
}
static bool IsVisible(Bone2D bone)
{
return IsVisible(bone.gameObject);
}
static bool IsVisible(GameObject go)
{
return (Tools.visibleLayers & 1 << go.layer) != 0;
}
static bool IsLocked(Bone2D bone)
{
return IsLocked(bone.gameObject);
}
static bool IsLocked(GameObject go)
{
return (Tools.lockedLayers & 1 << go.layer) != 0;
}
[UnityEditor.Callbacks.DidReloadScripts]
static void HierarchyWindowChanged()
{
s_Bones = GameObject.FindObjectsOfType<Bone2D>().ToList();
s_Controls = GameObject.FindObjectsOfType<Control>().ToList();
SceneView.RepaintAll();
}
static float AngleAroundAxis(Vector3 dirA, Vector3 dirB, Vector3 axis)
{
dirA = Vector3.ProjectOnPlane(dirA, axis);
dirB = Vector3.ProjectOnPlane(dirB, axis);
float num = Vector3.Angle(dirA, dirB);
return num * (float)((Vector3.Dot(axis, Vector3.Cross(dirA, dirB)) >= 0f) ? 1 : -1);
}
public static void OnSceneGUI(SceneView sceneview)
{
for (int i = 0; i < s_Bones.Count; i++)
{
Bone2D bone = s_Bones[i];
if(bone && IsVisible(bone))
{
int controlID = GUIUtility.GetControlID("BoneHandle".GetHashCode(),FocusType.Passive);
EventType eventType = Event.current.GetTypeForControl(controlID);
if(!IsLocked(bone))
{
if(eventType == EventType.MouseDown)
{
if(HandleUtility.nearestControl == controlID &&
Event.current.button == 0)
{
GUIUtility.hotControl = controlID;
Event.current.Use();
}
}
if(eventType == EventType.MouseUp)
{
if(GUIUtility.hotControl == controlID &&
Event.current.button == 0)
{
if(EditorGUI.actionKey)
{
List<Object> objects = new List<Object>(Selection.objects);
objects.Add(bone.gameObject);
Selection.objects = objects.ToArray();
}else{
Selection.activeObject = bone;
}
GUIUtility.hotControl = 0;
Event.current.Use();
}
}
if(eventType == EventType.MouseDrag)
{
if(GUIUtility.hotControl == controlID &&
Event.current.button == 0)
{
Handles.matrix = bone.transform.localToWorldMatrix;
Vector3 position = HandlesExtra.GUIToWorld(Event.current.mousePosition);
BoneUtils.OrientToLocalPosition(bone,position,Event.current.shift,"Rotate",true);
EditorUpdater.SetDirty("Rotate");
GUI.changed = true;
Event.current.Use();
}
}
}
if(eventType == EventType.Repaint)
{
if((HandleUtility.nearestControl == controlID && GUIUtility.hotControl == 0) ||
GUIUtility.hotControl == controlID ||
Selection.gameObjects.Contains(bone.gameObject))
{
Color color = Color.yellow;
float outlineSize = HandleUtility.GetHandleSize(bone.transform.position) * 0.015f * bone.color.a;
BoneUtils.DrawBoneOutline(bone,outlineSize,color);
Bone2D outlineBone = bone.child;
color.a *= 0.5f;
while(outlineBone)
{
if(Selection.gameObjects.Contains(outlineBone.gameObject))
{
outlineBone = null;
}else{
if(outlineBone.color.a == 0f)
{
outlineSize = HandleUtility.GetHandleSize(outlineBone.transform.position) * 0.015f * outlineBone.color.a;
BoneUtils.DrawBoneOutline(outlineBone,outlineSize,color);
outlineBone = outlineBone.child;
color.a *= 0.5f;
}else{
outlineBone = null;
}
}
}
}
if(bone.parentBone && !bone.linkedParentBone)
{
Color color = bone.color;
color.a *= 0.25f;
Handles.matrix = Matrix4x4.identity;
BoneUtils.DrawBoneBody(bone.transform.position,bone.parentBone.transform.position,BoneUtils.GetBoneRadius(bone),color);
}
BoneUtils.DrawBoneBody(bone);
Color innerColor = bone.color * 0.25f;
if(bone.attachedIK && bone.attachedIK.isActiveAndEnabled)
{
innerColor = new Color (0f, 0.75f, 0.75f, 1f);
}
innerColor.a = bone.color.a;
BoneUtils.DrawBoneCap(bone,innerColor);
}
if(!IsLocked(bone) && eventType == EventType.Layout)
{
HandleUtility.AddControl(controlID, HandleUtility.DistanceToLine(bone.transform.position,bone.endPosition));
}
}
}
foreach(Control control in s_Controls)
{
if(control && control.isActiveAndEnabled && IsVisible(control.gameObject))
{
Transform transform = control.transform;
if(Selection.activeTransform != transform)
{
if(!control.bone ||
(control.bone && !Selection.transforms.Contains(control.bone.transform)))
{
Handles.matrix = Matrix4x4.identity;
Handles.color = control.color;
if(Tools.current == Tool.Move)
{
EditorGUI.BeginChangeCheck();
Quaternion cameraRotation = Camera.current.transform.rotation;
if(Event.current.type == EventType.Repaint)
{
Camera.current.transform.rotation = transform.rotation;
}
float size = HandleUtility.GetHandleSize(transform.position) / 5f;
//Handles.DrawLine(transform.position + transform.rotation * new Vector3(size,0f,0f), transform.position + transform.rotation * new Vector3(-size,0f,0f));
//Handles.DrawLine(transform.position + transform.rotation * new Vector3(0f,size,0f), transform.position + transform.rotation * new Vector3(0f,-size,0f));
bool guiEnabled = GUI.enabled;
GUI.enabled = !IsLocked(control.gameObject);
#if UNITY_5_6_OR_NEWER
Vector3 newPosition = Handles.FreeMoveHandle(transform.position, transform.rotation, size, Vector3.zero, Handles.RectangleHandleCap);
#else
Vector3 newPosition = Handles.FreeMoveHandle(transform.position, transform.rotation, size, Vector3.zero, Handles.RectangleCap);
#endif
GUI.enabled = guiEnabled;
if(Event.current.type == EventType.Repaint)
{
Camera.current.transform.rotation = cameraRotation;
}
if(EditorGUI.EndChangeCheck())
{
Undo.RecordObject(transform,"Move");
transform.position = newPosition;
if(control.bone)
{
Undo.RecordObject(control.bone.transform,"Move");
control.bone.transform.position = newPosition;
BoneUtils.OrientToChild(control.bone.parentBone,Event.current.shift,"Move",true);
EditorUpdater.SetDirty("Move");
}
}
}else if(Tools.current == Tool.Rotate)
{
EditorGUI.BeginChangeCheck();
float size = HandleUtility.GetHandleSize(transform.position) * 0.5f;
//Handles.DrawLine(transform.position + transform.rotation * new Vector3(size,0f,0f), transform.position + transform.rotation * new Vector3(-size,0f,0f));
//Handles.DrawLine(transform.position + transform.rotation * new Vector3(0f,size,0f), transform.position + transform.rotation * new Vector3(0f,-size,0f));
bool guiEnabled = GUI.enabled;
GUI.enabled = !IsLocked(control.gameObject);
Quaternion newRotation = Handles.Disc(transform.rotation, transform.position, transform.forward, size, false, 0f);
GUI.enabled = guiEnabled;
if(EditorGUI.EndChangeCheck())
{
Undo.RecordObject(transform,"Rotate");
transform.rotation = newRotation;
if(control.bone)
{
Undo.RecordObject(control.bone.transform,"Rotate");
control.bone.transform.rotation = newRotation;
EditorUpdater.SetDirty("Rotate");
}
}
}
}
}
}
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Runtime.Serialization;
using OpenMetaverse;
using Aurora.Framework;
namespace Aurora.ScriptEngine.AuroraDotNetEngine
{
[Serializable]
public class EventAbortException : Exception
{
public EventAbortException()
{
}
protected EventAbortException(
SerializationInfo info,
StreamingContext context)
{
}
}
[Serializable]
public class MinEventDelayException : Exception
{
public MinEventDelayException()
{
}
protected MinEventDelayException(
SerializationInfo info,
StreamingContext context)
{
}
}
[Serializable]
public class SelfDeleteException : Exception
{
public SelfDeleteException()
{
}
protected SelfDeleteException(
SerializationInfo info,
StreamingContext context)
{
}
}
[Serializable]
public class ScriptDeleteException : Exception
{
public ScriptDeleteException()
{
}
protected ScriptDeleteException(
SerializationInfo info,
StreamingContext context)
{
}
}
[Serializable]
public class ScriptPermissionsException : Exception
{
public ScriptPermissionsException(string message)
: base(message)
{
}
protected ScriptPermissionsException(
SerializationInfo info,
StreamingContext context)
{
}
}
public class DetectParams
{
public UUID Group;
public UUID Key;
public int LinkNum;
public string Name;
public LSL_Types.Vector3 OffsetPos;
public UUID Owner;
public LSL_Types.Vector3 Position;
public LSL_Types.Quaternion Rotation;
public int Type;
public LSL_Types.Vector3 Velocity;
private LSL_Types.Vector3 touchBinormal;
private int touchFace;
private LSL_Types.Vector3 touchNormal;
private LSL_Types.Vector3 touchPos;
private LSL_Types.Vector3 touchST;
private LSL_Types.Vector3 touchUV;
public DetectParams()
{
Key = UUID.Zero;
OffsetPos = new LSL_Types.Vector3();
LinkNum = 0;
Group = UUID.Zero;
Name = String.Empty;
Owner = UUID.Zero;
Position = new LSL_Types.Vector3();
Rotation = new LSL_Types.Quaternion();
Type = 0;
Velocity = new LSL_Types.Vector3();
initializeSurfaceTouch();
}
public LSL_Types.Vector3 TouchST
{
get { return touchST; }
}
public LSL_Types.Vector3 TouchNormal
{
get { return touchNormal; }
}
public LSL_Types.Vector3 TouchBinormal
{
get { return touchBinormal; }
}
public LSL_Types.Vector3 TouchPos
{
get { return touchPos; }
}
public LSL_Types.Vector3 TouchUV
{
get { return touchUV; }
}
public int TouchFace
{
get { return touchFace; }
}
// This can be done in two places including the constructor
// so be carefull what gets added here
/*
* Set up the surface touch detected values
*/
public SurfaceTouchEventArgs SurfaceTouchArgs
{
set
{
if (value == null)
{
// Initialise to defaults if no value
initializeSurfaceTouch();
}
else
{
// Set the values from the touch data provided by the client
touchST = new LSL_Types.Vector3(value.STCoord.X, value.STCoord.Y, value.STCoord.Z);
touchUV = new LSL_Types.Vector3(value.UVCoord.X, value.UVCoord.Y, value.UVCoord.Z);
touchNormal = new LSL_Types.Vector3(value.Normal.X, value.Normal.Y, value.Normal.Z);
touchBinormal = new LSL_Types.Vector3(value.Binormal.X, value.Binormal.Y, value.Binormal.Z);
touchPos = new LSL_Types.Vector3(value.Position.X, value.Position.Y, value.Position.Z);
touchFace = value.FaceIndex;
}
}
}
private void initializeSurfaceTouch()
{
touchST = new LSL_Types.Vector3(-1.0, -1.0, 0.0);
touchNormal = new LSL_Types.Vector3();
touchBinormal = new LSL_Types.Vector3();
touchPos = new LSL_Types.Vector3();
touchUV = new LSL_Types.Vector3(-1.0, -1.0, 0.0);
touchFace = -1;
}
public void Populate(IScene scene)
{
ISceneChildEntity part = scene.GetSceneObjectPart(Key);
Vector3 tmp;
if (part == null) // Avatar, maybe?
{
IScenePresence presence = scene.GetScenePresence(Key);
if (presence == null)
return;
Name = presence.Name;
Owner = Key;
tmp = presence.AbsolutePosition;
Position = new LSL_Types.Vector3(
tmp.X,
tmp.Y,
tmp.Z);
Quaternion rtmp = presence.Rotation;
Rotation = new LSL_Types.Quaternion(
rtmp.X,
rtmp.Y,
rtmp.Z,
rtmp.W);
tmp = presence.Velocity;
Velocity = new LSL_Types.Vector3(
tmp.X,
tmp.Y,
tmp.Z);
Type = 0x01; // Avatar
if (presence.Velocity != Vector3.Zero)
Type |= 0x02; // Active
Group = presence.ControllingClient.ActiveGroupId;
return;
}
part = part.ParentEntity.RootChild; // We detect objects only
LinkNum = 0; // Not relevant
Group = part.GroupID;
Name = part.Name;
Owner = part.OwnerID;
Type = part.Velocity == Vector3.Zero ? 0x04 : 0x02;
foreach (ISceneChildEntity child in part.ParentEntity.ChildrenEntities())
if (child.Inventory.ContainsScripts())
Type |= 0x08; // Scripted
tmp = part.AbsolutePosition;
Position = new LSL_Types.Vector3(tmp.X,
tmp.Y,
tmp.Z);
Quaternion wr = part.ParentEntity.GroupRotation;
Rotation = new LSL_Types.Quaternion(wr.X, wr.Y, wr.Z, wr.W);
tmp = part.Velocity;
Velocity = new LSL_Types.Vector3(tmp.X,
tmp.Y,
tmp.Z);
}
}
/// <summary>
/// Holds all the data required to execute a scripting event.
/// </summary>
public class EventParams
{
public DetectParams[] DetectParams;
public string EventName;
public Object[] Params;
public EventParams(string eventName, Object[] eventParams, DetectParams[] detectParams)
{
EventName = eventName;
Params = eventParams;
DetectParams = detectParams;
}
}
/// <summary>
/// Queue item structure
/// </summary>
public class QueueItemStruct
{
public EnumeratorInfo CurrentlyAt;
public ScriptEventsProcData EventsProcData;
public ScriptData ID;
public int RunningNumber;
//The currently running state that this event will be fired under
public string State;
public long VersionID;
//Name of the method to fire
public string functionName;
//Params to give the script event
public DetectParams[] llDetectParams;
//Parameters to fire the function
public object[] param;
public bool Done = false;
public bool InProgress = false;
public int EventNumber = 0;
}
public struct StateQueueItem
{
public bool Create;
public ScriptData ID;
}
// Load/Unload structure
public struct LUStruct
{
public LUType Action;
public bool ClearStateSaves;
public ScriptData ID;
}
public enum LUType
{
Unknown = 0,
Load = 1,
Unload = 2,
Reupload = 3
}
public enum EventPriority
{
FirstStart = 0,
Suspended = 1,
Continued = 2
}
public enum ScriptEventsState
{
Idle = 0,
Sleep = 1,
Suspended = 2,
Running = 3, //?
InExec = 4,
InExecAbort = 5,
Delete = 6,
Deleted = -1 //?
}
public class ScriptEventsProcData
{
public ScriptEventsState State;
public DateTime TimeCheck;
}
public enum LoadPriority
{
FirstStart = 0,
Restart = 1,
Stop = 2
}
/// <summary>
/// Threat Level for a scripting function
/// </summary>
public enum ThreatLevel
{
/// <summary>
/// Function is no threat at all. It doesn't constitute a threat to either users or the system and has no known side effects
/// </summary>
None = 0,
/// <summary>
/// Abuse of this command can cause a nuisance to the region operator, such as log message spew
/// </summary>
Nuisance = 1,
/// <summary>
/// Extreme levels of abuse of this function can cause impaired functioning of the region, or very gullible users can be tricked into experiencing harmless effects
/// </summary>
VeryLow = 2,
/// <summary>
/// Intentional abuse can cause crashes or malfunction under certain circumstances, which can easily be rectified, or certain users can be tricked into certain situations in an avoidable manner.
/// </summary>
Low = 3,
/// <summary>
/// Intentional abuse can cause denial of service and crashes with potential of data or state loss, or trusting users can be tricked into embarrassing or uncomfortable situations.
/// </summary>
Moderate = 4,
/// <summary>
/// Casual abuse can cause impaired functionality or temporary denial of service conditions. Intentional abuse can easily cause crashes with potential data loss, or can be used to trick experienced and cautious users into unwanted situations, or changes global data permanently and without undo ability
/// Malicious scripting can allow theft of content
/// </summary>
High = 5,
/// <summary>
/// Even normal use may, depending on the number of instances, or frequency of use, result in severe service impairment or crash with loss of data, or can be used to cause unwanted or harmful effects on users without giving the user a means to avoid it.
/// </summary>
VeryHigh = 6,
/// <summary>
/// Even casual use is a danger to region stability, or function allows console or OS command execution, or function allows taking money without consent, or allows deletion or modification of user data, or allows the compromise of sensitive data by design.
/// </summary>
Severe = 7,
NoAccess = 8
}
}
| |
using J2N;
using YAF.Lucene.Net.Analysis.TokenAttributes;
using YAF.Lucene.Net.Util;
using System;
using System.Diagnostics;
namespace YAF.Lucene.Net.Analysis
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using Automaton = YAF.Lucene.Net.Util.Automaton.Automaton;
using State = YAF.Lucene.Net.Util.Automaton.State;
using Transition = YAF.Lucene.Net.Util.Automaton.Transition;
// TODO: maybe also toFST? then we can translate atts into FST outputs/weights
/// <summary>
/// Consumes a <see cref="TokenStream"/> and creates an <see cref="Automaton"/>
/// where the transition labels are UTF8 bytes (or Unicode
/// code points if unicodeArcs is true) from the <see cref="ITermToBytesRefAttribute"/>.
/// Between tokens we insert
/// <see cref="POS_SEP"/> and for holes we insert <see cref="HOLE"/>.
///
/// @lucene.experimental
/// </summary>
public class TokenStreamToAutomaton
{
//backing variables
private bool preservePositionIncrements;
private bool unicodeArcs;
/// <summary>
/// Sole constructor. </summary>
public TokenStreamToAutomaton()
{
this.preservePositionIncrements = true;
}
/// <summary>
/// Whether to generate holes in the automaton for missing positions, <c>true</c> by default. </summary>
public virtual bool PreservePositionIncrements
{
get => this.preservePositionIncrements; // LUCENENET specific - properties should always have a getter
set => this.preservePositionIncrements = value;
}
/// <summary>
/// Whether to make transition labels Unicode code points instead of UTF8 bytes,
/// <c>false</c> by default
/// </summary>
public virtual bool UnicodeArcs
{
get => this.unicodeArcs; // LUCENENET specific - properties should always have a getter
set => this.unicodeArcs = value;
}
private class Position : RollingBuffer.IResettable
{
// Any tokens that ended at our position arrive to this state:
internal State arriving;
// Any tokens that start at our position leave from this state:
internal State leaving;
public void Reset()
{
arriving = null;
leaving = null;
}
}
private class Positions : RollingBuffer<Position>
{
public Positions()
: base(NewPosition) { }
protected override Position NewInstance()
{
return NewPosition();
}
private static Position NewPosition()
{
return new Position();
}
}
/// <summary>
/// Subclass & implement this if you need to change the
/// token (such as escaping certain bytes) before it's
/// turned into a graph.
/// </summary>
protected internal virtual BytesRef ChangeToken(BytesRef @in)
{
return @in;
}
/// <summary>
/// We create transition between two adjacent tokens. </summary>
public const int POS_SEP = 0x001f;
/// <summary>
/// We add this arc to represent a hole. </summary>
public const int HOLE = 0x001e;
/// <summary>
/// Pulls the graph (including <see cref="IPositionLengthAttribute"/>
/// from the provided <see cref="TokenStream"/>, and creates the corresponding
/// automaton where arcs are bytes (or Unicode code points
/// if unicodeArcs = true) from each term.
/// </summary>
public virtual Automaton ToAutomaton(TokenStream @in)
{
var a = new Automaton();
bool deterministic = true;
var posIncAtt = @in.AddAttribute<IPositionIncrementAttribute>();
var posLengthAtt = @in.AddAttribute<IPositionLengthAttribute>();
var offsetAtt = @in.AddAttribute<IOffsetAttribute>();
var termBytesAtt = @in.AddAttribute<ITermToBytesRefAttribute>();
BytesRef term = termBytesAtt.BytesRef;
@in.Reset();
// Only temporarily holds states ahead of our current
// position:
RollingBuffer<Position> positions = new Positions();
int pos = -1;
Position posData = null;
int maxOffset = 0;
while (@in.IncrementToken())
{
int posInc = posIncAtt.PositionIncrement;
if (!preservePositionIncrements && posInc > 1)
{
posInc = 1;
}
Debug.Assert(pos > -1 || posInc > 0);
if (posInc > 0)
{
// New node:
pos += posInc;
posData = positions.Get(pos);
Debug.Assert(posData.leaving == null);
if (posData.arriving == null)
{
// No token ever arrived to this position
if (pos == 0)
{
// OK: this is the first token
posData.leaving = a.GetInitialState();
}
else
{
// this means there's a hole (eg, StopFilter
// does this):
posData.leaving = new State();
AddHoles(a.GetInitialState(), positions, pos);
}
}
else
{
posData.leaving = new State();
posData.arriving.AddTransition(new Transition(POS_SEP, posData.leaving));
if (posInc > 1)
{
// A token spanned over a hole; add holes
// "under" it:
AddHoles(a.GetInitialState(), positions, pos);
}
}
positions.FreeBefore(pos);
}
else
{
// note: this isn't necessarily true. its just that we aren't surely det.
// we could optimize this further (e.g. buffer and sort synonyms at a position)
// but thats probably overkill. this is cheap and dirty
deterministic = false;
}
int endPos = pos + posLengthAtt.PositionLength;
termBytesAtt.FillBytesRef();
BytesRef termUTF8 = ChangeToken(term);
int[] termUnicode = null;
Position endPosData = positions.Get(endPos);
if (endPosData.arriving == null)
{
endPosData.arriving = new State();
}
State state = posData.leaving;
int termLen = termUTF8.Length;
if (unicodeArcs)
{
string utf16 = termUTF8.Utf8ToString();
termUnicode = new int[utf16.CodePointCount(0, utf16.Length)];
termLen = termUnicode.Length;
for (int cp, i = 0, j = 0; i < utf16.Length; i += Character.CharCount(cp))
{
termUnicode[j++] = cp = Character.CodePointAt(utf16, i);
}
}
else
{
termLen = termUTF8.Length;
}
for (int byteIDX = 0; byteIDX < termLen; byteIDX++)
{
State nextState = byteIDX == termLen - 1 ? endPosData.arriving : new State();
int c;
if (unicodeArcs)
{
c = termUnicode[byteIDX];
}
else
{
c = termUTF8.Bytes[termUTF8.Offset + byteIDX] & 0xff;
}
state.AddTransition(new Transition(c, nextState));
state = nextState;
}
maxOffset = Math.Max(maxOffset, offsetAtt.EndOffset);
}
@in.End();
State endState = null;
if (offsetAtt.EndOffset > maxOffset)
{
endState = new State();
endState.Accept = true;
}
pos++;
while (pos <= positions.MaxPos)
{
posData = positions.Get(pos);
if (posData.arriving != null)
{
if (endState != null)
{
posData.arriving.AddTransition(new Transition(POS_SEP, endState));
}
else
{
posData.arriving.Accept = true;
}
}
pos++;
}
//toDot(a);
a.IsDeterministic = deterministic;
return a;
}
// for debugging!
/*
private static void toDot(Automaton a) throws IOException {
final String s = a.toDot();
Writer w = new OutputStreamWriter(new FileOutputStream("/tmp/out.dot"));
w.write(s);
w.Dispose();
System.out.println("TEST: saved to /tmp/out.dot");
}
*/
private static void AddHoles(State startState, RollingBuffer<Position> positions, int pos)
{
Position posData = positions.Get(pos);
Position prevPosData = positions.Get(pos - 1);
while (posData.arriving == null || prevPosData.leaving == null)
{
if (posData.arriving == null)
{
posData.arriving = new State();
posData.arriving.AddTransition(new Transition(POS_SEP, posData.leaving));
}
if (prevPosData.leaving == null)
{
if (pos == 1)
{
prevPosData.leaving = startState;
}
else
{
prevPosData.leaving = new State();
}
if (prevPosData.arriving != null)
{
prevPosData.arriving.AddTransition(new Transition(POS_SEP, prevPosData.leaving));
}
}
prevPosData.leaving.AddTransition(new Transition(HOLE, posData.arriving));
pos--;
if (pos <= 0)
{
break;
}
posData = prevPosData;
prevPosData = positions.Get(pos - 1);
}
}
}
}
| |
//-----------------------------------------------------------------
// LogEntry
// Copyright 2009-2012 MrJoy, Inc.
// All rights reserved
//
//-----------------------------------------------------------------
// Models for the execution/result log, and editor history.
//-----------------------------------------------------------------
using UnityEditor;
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
[Serializable]
public enum LogEntryType : int {
Command = 0,
Output = 1,
EvaluationError = 2,
SystemConsole = 3,
ConsoleLog = 10
}
[Serializable]
public class LogEntry {
public LogEntryType logEntryType;
public string command;
public string shortCommand = null;
public bool isExpanded = true;
public bool hasChildren = false;
public bool isExpandable = false;
public List<LogEntry> children;
private char[] newline = new char[] {'\n'};
public string output;
public string error;
private string _stackTrace = null;
public string stackTrace {
get { return _stackTrace; }
set {
string tmp = value;
if(tmp.EndsWith("\n")) {
tmp = tmp.Substring(0, tmp.Length - 1);
}
if(_stackTrace != tmp) {
_filteredStackTrace = null;
_stackTrace = tmp;
}
}
}
private static char[] NEWLINE = new char[] { '\n' },
COLON = new char[] { ':' };
public string _filteredStackTrace = null;
public string filteredStackTrace {
get {
if(_filteredStackTrace == null) {
if(_stackTrace != null) {
string[] traceEntries = _stackTrace.Split(NEWLINE);
List<string> filteredTraceEntries = new List<string>();
foreach(string entry in traceEntries) {
bool filter = false;
int i = entry.IndexOf(") (");
string signature, position;
if(i > 0) {
signature = entry.Substring(0, i + 1);
position = entry.Substring(i + 2, entry.Length - (i + 2));
} else {
// Nada.
signature = entry;
position = "";
}
string[] signaturePieces = signature.Split(COLON, 2);
if(signaturePieces.Length > 1) {
string classDesignation = signaturePieces[0];
string methodSignature = signaturePieces[1];
if((classDesignation == "UnityEngine.Debug" && position == "") ||
(classDesignation.StartsWith("Class") && methodSignature == "Host(Object&)" && position == "") ||
(classDesignation == "Mono.CSharp.Evaluator" && methodSignature == "Evaluate(String, Object&, Boolean&)" && position == "") ||
(classDesignation == "EvaluationHelper" && methodSignature == "Eval(List`1, String)" && position.IndexOf("UnityREPL/Evaluator.cs") >= 0) ||
(classDesignation == "Shell" && methodSignature == "Update()" && position.IndexOf("UnityREPL/Shell.cs") >= 0) ||
(classDesignation == "UnityEditor.EditorApplication" && methodSignature == "Internal_CallUpdateFunctions()" && position == "")
)
filter = true;
} else {
// WTF?!
}
if(!filter)
filteredTraceEntries.Add(entry);
}
StringBuilder sb = new StringBuilder();
foreach(string s in filteredTraceEntries)
sb.Append(s).Append("\n");
string tmp = sb.ToString();
if(tmp.Length > 0)
tmp = tmp.Substring(0, tmp.Length - 1);
_filteredStackTrace = tmp;
} else {
_filteredStackTrace = null;
}
}
return _filteredStackTrace;
}
}
public string condition;
public LogType consoleLogType;
public void Add(LogEntry child) {
if(children == null)
children = new List<LogEntry>();
children.Add(child);
}
public bool OnGUI(bool filterTraces) {
bool retVal = false;
switch(logEntryType) {
case LogEntryType.Command:
if(children != null && children.Count > 0) {
hasChildren = true;
}
if(shortCommand == null) {
command = command.TrimEnd();
string[] commandList = command.Split(newline, 2);
shortCommand = commandList[0];
if(hasChildren || command != shortCommand) {
isExpandable = true;
}
}
if(isExpandable) {
GUILayout.BeginHorizontal();
isExpanded = GUILayout.Toggle(isExpanded, (isExpanded) ? command: shortCommand, LogEntryStyles.FoldoutCommandStyle, GUILayout.ExpandWidth(false));
GUILayout.FlexibleSpace();
retVal = GUILayout.Button("+", GUILayout.ExpandWidth(false));
GUILayout.EndHorizontal();
if(isExpanded && hasChildren) {
GUILayout.BeginHorizontal();
GUILayout.Space(15);
GUILayout.BeginVertical();
foreach(LogEntry le in children)
le.OnGUI(filterTraces);
GUILayout.EndVertical();
GUILayout.EndHorizontal();
}
} else {
GUILayout.BeginHorizontal();
GUILayout.Space(15);
GUILayout.Label(command, LogEntryStyles.DefaultCommandStyle);
GUILayout.FlexibleSpace();
retVal = GUILayout.Button("+", GUILayout.ExpandWidth(false));
GUILayout.EndHorizontal();
}
break;
case LogEntryType.Output:
GUILayout.BeginHorizontal(GUI.skin.box);
GUILayout.Label(output, LogEntryStyles.OutputStyle);
GUILayout.EndHorizontal();
break;
case LogEntryType.EvaluationError:
GUILayout.BeginHorizontal(GUI.skin.box);
GUILayout.Label(error, LogEntryStyles.EvaluationErrorStyle);
GUILayout.EndHorizontal();
break;
case LogEntryType.SystemConsole:
GUILayout.BeginHorizontal(GUI.skin.box);
GUILayout.Label(error, LogEntryStyles.SystemConsoleStyle);
GUILayout.EndHorizontal();
break;
case LogEntryType.ConsoleLog:
GUILayout.BeginHorizontal(GUI.skin.box);
GUILayout.BeginVertical();
GUIStyle logStyle = null;
switch(consoleLogType) {
case LogType.Error: // Debug.LogError(...).
case LogType.Assert: // Unity internal error.
case LogType.Exception: // Uncaught exception.
logStyle = LogEntryStyles.ConsoleLogErrorStyle;
break;
case LogType.Warning: // Debug.LogWarning(...).
logStyle = LogEntryStyles.ConsoleLogWarningStyle;
break;
case LogType.Log: // Debug.Log(...).
logStyle = LogEntryStyles.ConsoleLogNormalStyle;
break;
}
GUILayout.Label(condition, logStyle);
if(!String.IsNullOrEmpty(filterTraces ? filteredStackTrace : stackTrace))
GUILayout.Label(filterTraces ? filteredStackTrace : stackTrace, LogEntryStyles.ConsoleLogStackTraceStyle);
GUILayout.EndVertical();
GUILayout.EndHorizontal();
break;
}
return retVal;
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel
{
/// <summary>
/// Implementations of EnvDTE.FileCodeModel for both languages.
/// </summary>
public sealed partial class FileCodeModel : AbstractCodeModelObject, EnvDTE.FileCodeModel, EnvDTE80.FileCodeModel2, ICodeElementContainer<AbstractCodeElement>, IVBFileCodeModelEvents, ICSCodeModelRefactoring
{
internal static ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel> Create(
CodeModelState state,
object parent,
DocumentId documentId,
ITextManagerAdapter textManagerAdapter)
{
return new FileCodeModel(state, parent, documentId, textManagerAdapter).GetComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>();
}
private readonly ComHandle<object, object> _parentHandle;
/// <summary>
/// Don't use directly. Instead, call <see cref="GetDocumentId()"/>.
/// </summary>
private DocumentId _documentId;
// Note: these are only valid when the underlying file is being renamed. Do not use.
private ProjectId _incomingProjectId;
private string _incomingFilePath;
private Document _previousDocument;
private readonly ITextManagerAdapter _textManagerAdapter;
private readonly CleanableWeakComHandleTable<SyntaxNodeKey, EnvDTE.CodeElement> _codeElementTable;
// These are used during batching.
private bool _batchMode;
private List<AbstractKeyedCodeElement> _batchElements;
private Document _batchDocument;
// track state to make sure we open editor only once
private int _editCount;
private IInvisibleEditor _invisibleEditor;
private SyntaxTree _lastSyntaxTree;
private FileCodeModel(
CodeModelState state,
object parent,
DocumentId documentId,
ITextManagerAdapter textManagerAdapter)
: base(state)
{
Debug.Assert(documentId != null);
Debug.Assert(textManagerAdapter != null);
_parentHandle = new ComHandle<object, object>(parent);
_documentId = documentId;
_textManagerAdapter = textManagerAdapter;
_codeElementTable = new CleanableWeakComHandleTable<SyntaxNodeKey, EnvDTE.CodeElement>();
_batchMode = false;
_batchDocument = null;
_lastSyntaxTree = GetSyntaxTree();
}
internal ITextManagerAdapter TextManagerAdapter
{
get { return _textManagerAdapter; }
}
/// <summary>
/// Internally, we store the DocumentId for the document that the FileCodeModel represents. If the underlying file
/// is renamed, the DocumentId will become invalid because the Roslyn VS workspace treats file renames as a remove/add pair.
/// To work around this, the FileCodeModel is notified when a file rename is about to occur. At that point, the
/// <see cref="_documentId"/> field is null'd out and <see cref="_incomingFilePath"/> is set to the name of the new file.
/// The next time that a FileCodeModel operation occurs that requires the DocumentId, it will be retrieved from the workspace
/// using the <see cref="_incomingFilePath"/>.
/// </summary>
internal void OnRename(string newFilePath)
{
Debug.Assert(_editCount == 0, "FileCodeModel have an open edit and the underlying file is being renamed. This is a bug.");
if (_documentId != null)
{
_previousDocument = Workspace.CurrentSolution.GetDocument(_documentId);
}
_incomingFilePath = newFilePath;
_incomingProjectId = _documentId.ProjectId;
_documentId = null;
}
internal override void Shutdown()
{
if (_invisibleEditor != null)
{
// we are shutting down, so do not worry about editCount. If the editor is still alive, dispose it.
CodeModelService.DetachFormatTrackingToBuffer(_invisibleEditor.TextBuffer);
_invisibleEditor.Dispose();
_invisibleEditor = null;
}
base.Shutdown();
}
private bool TryGetDocumentId(out DocumentId documentId)
{
if (_documentId != null)
{
documentId = _documentId;
return true;
}
documentId = null;
// We don't have DocumentId, so try to retrieve it from the workspace.
if (_incomingProjectId == null || _incomingFilePath == null)
{
return false;
}
var project = ((VisualStudioWorkspaceImpl)this.State.Workspace).DeferredState?.ProjectTracker.GetProject(_incomingProjectId);
if (project == null)
{
return false;
}
var hostDocument = project.GetCurrentDocumentFromPath(_incomingFilePath);
if (hostDocument == null)
{
return false;
}
_documentId = hostDocument.Id;
_incomingProjectId = null;
_incomingFilePath = null;
_previousDocument = null;
documentId = _documentId;
return true;
}
internal DocumentId GetDocumentId()
{
if (_documentId != null)
{
return _documentId;
}
if (TryGetDocumentId(out var documentId))
{
return documentId;
}
throw Exceptions.ThrowEUnexpected();
}
internal void UpdateCodeElementNodeKey(AbstractKeyedCodeElement keyedElement, SyntaxNodeKey oldNodeKey, SyntaxNodeKey newNodeKey)
{
if (!_codeElementTable.TryGetValue(oldNodeKey, out var codeElement))
{
throw new InvalidOperationException($"Could not find {oldNodeKey} in Code Model element table.");
}
_codeElementTable.Remove(oldNodeKey);
var managedElement = ComAggregate.GetManagedObject<AbstractKeyedCodeElement>(codeElement);
if (!object.Equals(managedElement, keyedElement))
{
throw new InvalidOperationException($"Unexpected failure in Code Model while updating node keys {oldNodeKey} -> {newNodeKey}");
}
_codeElementTable.Add(newNodeKey, codeElement);
}
internal void OnCodeElementCreated(SyntaxNodeKey nodeKey, EnvDTE.CodeElement element)
{
// If we're creating an element with the same node key as an element that's already in the table, just remove
// the old element. The old element will continue to function but the new element will replace it in the cache.
if (_codeElementTable.ContainsKey(nodeKey))
{
_codeElementTable.Remove(nodeKey);
}
_codeElementTable.Add(nodeKey, element);
}
internal void OnCodeElementDeleted(SyntaxNodeKey nodeKey)
{
_codeElementTable.Remove(nodeKey);
}
internal T GetOrCreateCodeElement<T>(SyntaxNode node)
{
var nodeKey = CodeModelService.TryGetNodeKey(node);
if (!nodeKey.IsEmpty)
{
// Since the node already has a key, check to see if a code element already
// exists for it. If so, return that element it it's still valid; otherwise,
// remove it from the table.
if (_codeElementTable.TryGetValue(nodeKey, out var codeElement))
{
if (codeElement != null)
{
var element = ComAggregate.TryGetManagedObject<AbstractCodeElement>(codeElement);
if (element.IsValidNode())
{
if (codeElement is T)
{
return (T)codeElement;
}
throw new InvalidOperationException($"Found a valid code element for {nodeKey}, but it is not of type, {typeof(T).ToString()}");
}
}
}
// Go ahead and remove the nodeKey from the table. At this point, we'll be creating a new one.
_codeElementTable.Remove(nodeKey);
}
return (T)CodeModelService.CreateInternalCodeElement(this.State, this, node);
}
private void InitializeEditor()
{
_editCount++;
if (_editCount == 1)
{
Debug.Assert(_invisibleEditor == null);
_invisibleEditor = Workspace.OpenInvisibleEditor(GetDocumentId());
CodeModelService.AttachFormatTrackingToBuffer(_invisibleEditor.TextBuffer);
}
}
private void ReleaseEditor()
{
Debug.Assert(_editCount >= 1);
_editCount--;
if (_editCount == 0)
{
Debug.Assert(_invisibleEditor != null);
CodeModelService.DetachFormatTrackingToBuffer(_invisibleEditor.TextBuffer);
_invisibleEditor.Dispose();
_invisibleEditor = null;
}
}
internal void EnsureEditor(Action action)
{
InitializeEditor();
try
{
action();
}
finally
{
ReleaseEditor();
}
}
internal T EnsureEditor<T>(Func<T> action)
{
InitializeEditor();
try
{
return action();
}
finally
{
ReleaseEditor();
}
}
internal void PerformEdit(Func<Document, Document> action)
{
EnsureEditor(() =>
{
Debug.Assert(_invisibleEditor != null);
var document = GetDocument();
var workspace = document.Project.Solution.Workspace;
var result = action(document);
var formatted = Formatter.FormatAsync(result, Formatter.Annotation).WaitAndGetResult_CodeModel(CancellationToken.None);
formatted = Formatter.FormatAsync(formatted, SyntaxAnnotation.ElasticAnnotation).WaitAndGetResult_CodeModel(CancellationToken.None);
ApplyChanges(workspace, formatted);
});
}
internal T PerformEdit<T>(Func<Document, Tuple<T, Document>> action) where T : SyntaxNode
{
return EnsureEditor(() =>
{
Debug.Assert(_invisibleEditor != null);
var document = GetDocument();
var workspace = document.Project.Solution.Workspace;
var result = action(document);
ApplyChanges(workspace, result.Item2);
return result.Item1;
});
}
private void ApplyChanges(Workspace workspace, Document document)
{
if (IsBatchOpen)
{
_batchDocument = document;
}
else
{
workspace.TryApplyChanges(document.Project.Solution);
}
}
internal Document GetDocument()
{
if (!TryGetDocument(out var document))
{
throw Exceptions.ThrowEFail();
}
return document;
}
internal bool TryGetDocument(out Document document)
{
if (IsBatchOpen && _batchDocument != null)
{
document = _batchDocument;
return true;
}
if (!TryGetDocumentId(out var documentId) && _previousDocument != null)
{
document = _previousDocument;
}
else
{
document = Workspace.CurrentSolution.GetDocument(GetDocumentId());
}
return document != null;
}
internal SyntaxTree GetSyntaxTree()
{
return GetDocument()
.GetSyntaxTreeAsync(CancellationToken.None)
.WaitAndGetResult_CodeModel(CancellationToken.None);
}
internal SyntaxNode GetSyntaxRoot()
{
return GetDocument()
.GetSyntaxRootAsync(CancellationToken.None)
.WaitAndGetResult_CodeModel(CancellationToken.None);
}
internal SemanticModel GetSemanticModel()
{
return GetDocument()
.GetSemanticModelAsync(CancellationToken.None)
.WaitAndGetResult_CodeModel(CancellationToken.None);
}
internal Compilation GetCompilation()
{
return GetDocument().Project
.GetCompilationAsync(CancellationToken.None)
.WaitAndGetResult_CodeModel(CancellationToken.None);
}
internal ProjectId GetProjectId()
{
return GetDocumentId().ProjectId;
}
internal AbstractProject GetAbstractProject()
{
return ((VisualStudioWorkspaceImpl)Workspace).DeferredState.ProjectTracker.GetProject(GetProjectId());
}
internal SyntaxNode LookupNode(SyntaxNodeKey nodeKey)
{
return CodeModelService.LookupNode(nodeKey, GetSyntaxTree());
}
internal TSyntaxNode LookupNode<TSyntaxNode>(SyntaxNodeKey nodeKey)
where TSyntaxNode : SyntaxNode
{
return CodeModelService.LookupNode(nodeKey, GetSyntaxTree()) as TSyntaxNode;
}
public EnvDTE.CodeAttribute AddAttribute(string name, string value, object position)
{
return EnsureEditor(() =>
{
return AddAttribute(GetSyntaxRoot(), name, value, position, target: CodeModelService.AssemblyAttributeString);
});
}
public EnvDTE.CodeClass AddClass(string name, object position, object bases, object implementedInterfaces, EnvDTE.vsCMAccess access)
{
return EnsureEditor(() =>
{
return AddClass(GetSyntaxRoot(), name, position, bases, implementedInterfaces, access);
});
}
public EnvDTE.CodeDelegate AddDelegate(string name, object type, object position, EnvDTE.vsCMAccess access)
{
return EnsureEditor(() =>
{
return AddDelegate(GetSyntaxRoot(), name, type, position, access);
});
}
public EnvDTE.CodeEnum AddEnum(string name, object position, object bases, EnvDTE.vsCMAccess access)
{
return EnsureEditor(() =>
{
return AddEnum(GetSyntaxRoot(), name, position, bases, access);
});
}
public EnvDTE.CodeFunction AddFunction(string name, EnvDTE.vsCMFunction kind, object type, object position, EnvDTE.vsCMAccess access)
{
throw Exceptions.ThrowEFail();
}
public EnvDTE80.CodeImport AddImport(string name, object position, string alias)
{
return EnsureEditor(() =>
{
return AddImport(GetSyntaxRoot(), name, position, alias);
});
}
public EnvDTE.CodeInterface AddInterface(string name, object position, object bases, EnvDTE.vsCMAccess access)
{
return EnsureEditor(() =>
{
return AddInterface(GetSyntaxRoot(), name, position, bases, access);
});
}
public EnvDTE.CodeNamespace AddNamespace(string name, object position)
{
return EnsureEditor(() =>
{
return AddNamespace(GetSyntaxRoot(), name, position);
});
}
public EnvDTE.CodeStruct AddStruct(string name, object position, object bases, object implementedInterfaces, EnvDTE.vsCMAccess access)
{
return EnsureEditor(() =>
{
return AddStruct(GetSyntaxRoot(), name, position, bases, implementedInterfaces, access);
});
}
public EnvDTE.CodeVariable AddVariable(string name, object type, object position, EnvDTE.vsCMAccess access)
{
throw Exceptions.ThrowEFail();
}
public EnvDTE.CodeElement CodeElementFromPoint(EnvDTE.TextPoint point, EnvDTE.vsCMElement scope)
{
// Can't use point.AbsoluteCharOffset because it's calculated by the native
// implementation in GetAbsoluteOffset (in env\msenv\textmgr\autoutil.cpp)
// to only count each newline as a single character. We need to ask for line and
// column and calculate the right offset ourselves. See DevDiv2 530496 for details.
var position = GetPositionFromTextPoint(point);
var result = CodeElementFromPosition(position, scope);
if (result == null)
{
throw Exceptions.ThrowEFail();
}
return result;
}
private int GetPositionFromTextPoint(EnvDTE.TextPoint point)
{
var lineNumber = point.Line - 1;
var column = point.LineCharOffset - 1;
var line = GetDocument().GetTextAsync(CancellationToken.None).WaitAndGetResult_CodeModel(CancellationToken.None).Lines[lineNumber];
var position = line.Start + column;
return position;
}
internal EnvDTE.CodeElement CodeElementFromPosition(int position, EnvDTE.vsCMElement scope)
{
var root = GetSyntaxRoot();
var leftToken = SyntaxFactsService.FindTokenOnLeftOfPosition(root, position);
var rightToken = SyntaxFactsService.FindTokenOnRightOfPosition(root, position);
// We apply a set of heuristics to determine which member we pick to start searching.
var token = leftToken;
if (leftToken != rightToken)
{
if (leftToken.Span.End == position && rightToken.SpanStart == position)
{
// If both tokens are touching, we prefer identifiers and keywords to
// separators. Note that the language doesn't allow both tokens to be a
// keyword or identifier.
if (SyntaxFactsService.IsKeyword(rightToken) ||
SyntaxFactsService.IsIdentifier(rightToken))
{
token = rightToken;
}
}
else if (leftToken.Span.End < position && rightToken.SpanStart <= position)
{
// If only the right token is touching, we have to use it.
token = rightToken;
}
}
// If we ended up using the left token but the position is after that token,
// walk up to the first node who's last token is not the leftToken. By doing this, we
// ensure that we don't find members when the position is actually between them.
// In that case, we should find the enclosing type or namespace.
var parent = token.Parent;
if (token == leftToken && position > token.Span.End)
{
while (parent != null)
{
if (parent.GetLastToken() == token)
{
parent = parent.Parent;
}
else
{
break;
}
}
}
var node = parent != null
? parent.AncestorsAndSelf().FirstOrDefault(n => CodeModelService.MatchesScope(n, scope))
: null;
if (node == null)
{
return null;
}
if (scope == EnvDTE.vsCMElement.vsCMElementAttribute ||
scope == EnvDTE.vsCMElement.vsCMElementImportStmt ||
scope == EnvDTE.vsCMElement.vsCMElementParameter ||
scope == EnvDTE.vsCMElement.vsCMElementOptionStmt ||
scope == EnvDTE.vsCMElement.vsCMElementInheritsStmt ||
scope == EnvDTE.vsCMElement.vsCMElementImplementsStmt ||
(scope == EnvDTE.vsCMElement.vsCMElementFunction && CodeModelService.IsAccessorNode(node)))
{
// Attributes, imports, parameters, Option, Inherits and Implements
// don't have node keys of their own and won't be included in our
// collection of elements. Delegate to the service to create these.
return CodeModelService.CreateInternalCodeElement(State, this, node);
}
return GetOrCreateCodeElement<EnvDTE.CodeElement>(node);
}
public EnvDTE.CodeElements CodeElements
{
get { return NamespaceCollection.Create(this.State, this, this, SyntaxNodeKey.Empty); }
}
public EnvDTE.ProjectItem Parent
{
get { return _parentHandle.Object as EnvDTE.ProjectItem; }
}
public void Remove(object element)
{
var codeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(element);
if (codeElement == null)
{
codeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(this.CodeElements.Item(element));
}
if (codeElement == null)
{
throw new ArgumentException(ServicesVSResources.Element_is_not_valid, nameof(element));
}
codeElement.Delete();
}
int IVBFileCodeModelEvents.StartEdit()
{
try
{
InitializeEditor();
if (_editCount == 1)
{
_batchMode = true;
_batchElements = new List<AbstractKeyedCodeElement>();
}
return VSConstants.S_OK;
}
catch (Exception ex)
{
return Marshal.GetHRForException(ex);
}
}
int IVBFileCodeModelEvents.EndEdit()
{
try
{
if (_editCount == 1)
{
List<ValueTuple<AbstractKeyedCodeElement, SyntaxPath>> elementAndPaths = null;
if (_batchElements.Count > 0)
{
foreach (var element in _batchElements)
{
var node = element.LookupNode();
if (node != null)
{
elementAndPaths = elementAndPaths ?? new List<ValueTuple<AbstractKeyedCodeElement, SyntaxPath>>();
elementAndPaths.Add(ValueTuple.Create(element, new SyntaxPath(node)));
}
}
}
if (_batchDocument != null)
{
// perform expensive operations at once
var newDocument = Simplifier.ReduceAsync(_batchDocument, Simplifier.Annotation, cancellationToken: CancellationToken.None).WaitAndGetResult_CodeModel(CancellationToken.None);
_batchDocument.Project.Solution.Workspace.TryApplyChanges(newDocument.Project.Solution);
// done using batch document
_batchDocument = null;
}
// Ensure the file is prettylisted, even if we didn't make any edits
CodeModelService.EnsureBufferFormatted(_invisibleEditor.TextBuffer);
if (elementAndPaths != null)
{
foreach (var elementAndPath in elementAndPaths)
{
// make sure the element is there.
if (_codeElementTable.TryGetValue(elementAndPath.Item1.NodeKey, out var existingElement))
{
elementAndPath.Item1.ReacquireNodeKey(elementAndPath.Item2, CancellationToken.None);
}
// make sure existing element doesn't go away (weak reference) in the middle of
// updating the node key
GC.KeepAlive(existingElement);
}
}
_batchMode = false;
_batchElements = null;
}
return VSConstants.S_OK;
}
catch (Exception ex)
{
return Marshal.GetHRForException(ex);
}
finally
{
ReleaseEditor();
}
}
public void BeginBatch()
{
IVBFileCodeModelEvents temp = this;
ErrorHandler.ThrowOnFailure(temp.StartEdit());
}
public void EndBatch()
{
IVBFileCodeModelEvents temp = this;
ErrorHandler.ThrowOnFailure(temp.EndEdit());
}
public bool IsBatchOpen
{
get
{
return _batchMode && _editCount > 0;
}
}
public EnvDTE.CodeElement ElementFromID(string id)
{
throw new NotImplementedException();
}
public EnvDTE80.vsCMParseStatus ParseStatus
{
get
{
var syntaxTree = GetSyntaxTree();
return syntaxTree.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)
? EnvDTE80.vsCMParseStatus.vsCMParseStatusError
: EnvDTE80.vsCMParseStatus.vsCMParseStatusComplete;
}
}
public void Synchronize()
{
FireEvents();
}
EnvDTE.CodeElements ICodeElementContainer<AbstractCodeElement>.GetCollection()
{
return CodeElements;
}
internal List<GlobalNodeKey> GetCurrentNodeKeys()
{
var currentNodeKeys = new List<GlobalNodeKey>();
foreach (var element in _codeElementTable.Values)
{
var keyedElement = ComAggregate.TryGetManagedObject<AbstractKeyedCodeElement>(element);
if (keyedElement == null)
{
continue;
}
if (keyedElement.TryLookupNode(out var node))
{
var nodeKey = keyedElement.NodeKey;
currentNodeKeys.Add(new GlobalNodeKey(nodeKey, new SyntaxPath(node)));
}
}
return currentNodeKeys;
}
internal void ResetElementKeys(List<GlobalNodeKey> globalNodeKeys)
{
foreach (var globalNodeKey in globalNodeKeys)
{
ResetElementKey(globalNodeKey);
}
}
private void ResetElementKey(GlobalNodeKey globalNodeKey)
{
// Failure to find the element is not an error -- it just means the code
// element didn't exist...
if (_codeElementTable.TryGetValue(globalNodeKey.NodeKey, out var element))
{
var keyedElement = ComAggregate.GetManagedObject<AbstractKeyedCodeElement>(element);
if (keyedElement != null)
{
keyedElement.ReacquireNodeKey(globalNodeKey.Path, default(CancellationToken));
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Text;
using LoreSoft.MathExpressions.Properties;
using System.Globalization;
using System.Linq;
namespace LoreSoft.MathExpressions
{
/// <summary>
/// Evaluate math expressions
/// </summary>
/// <example>Using the MathEvaluator to calculate a math expression.
/// <code>
/// MathEvaluator eval = new MathEvaluator();
/// //basic math
/// double result = eval.Evaluate("(2 + 1) * (1 + 2)");
/// //calling a function
/// result = eval.Evaluate("sqrt(4)");
/// //evaluate trigonometric
/// result = eval.Evaluate("cos(pi * 45 / 180.0)");
/// //convert inches to feet
/// result = eval.Evaluate("12 [in->ft]");
/// //use variable
/// result = eval.Evaluate("answer * 10");
/// </code>
/// </example>
public class MathEvaluator : IDisposable
{
/// <summary>The name of the answer variable.</summary>
/// <seealso cref="Variables"/>
public const string AnswerVariable = "answer";
//instance scope to optimize reuse
private Stack<string> _symbolStack;
private Queue<IExpression> _expressionQueue;
private Dictionary<string, IExpression> _expressionCache;
private StringBuilder _buffer;
private Stack<double> _calculationStack;
private Stack<double> _parameters;
private List<string> _innerFunctions;
private uint _nestedFunctionDepth;
private uint _nestedGroupDepth;
private StringReader _expressionReader;
private VariableDictionary _variables;
private ReadOnlyCollection<string> _functions;
private char _currentChar;
/// <summary>
/// Initializes a new instance of the <see cref="MathEvaluator"/> class.
/// </summary>
public MathEvaluator()
{
_variables = new VariableDictionary(this);
_innerFunctions = new List<string>(FunctionExpression.GetFunctionNames());
_innerFunctions.Sort();
_functions = new ReadOnlyCollection<string>(_innerFunctions);
_expressionCache = new Dictionary<string, IExpression>(StringComparer.OrdinalIgnoreCase);
_symbolStack = new Stack<string>();
_expressionQueue = new Queue<IExpression>();
_buffer = new StringBuilder();
_calculationStack = new Stack<double>();
_parameters = new Stack<double>(2);
_nestedFunctionDepth = 0;
_nestedGroupDepth = 0;
}
/// <summary>
/// Gets the variables collections.
/// </summary>
/// <value>The variables for <see cref="MathEvaluator"/>.</value>
public VariableDictionary Variables
{
get { return _variables; }
}
/// <summary>Gets the functions available to <see cref="MathEvaluator"/>.</summary>
/// <value>The functions for <see cref="MathEvaluator"/>.</value>
/// <seealso cref="RegisterFunction"/>
public ReadOnlyCollection<string> Functions
{
get { return _functions; }
}
/// <summary>Gets the answer from the last evaluation.</summary>
/// <value>The answer variable value.</value>
/// <seealso cref="Variables"/>
public double Answer
{
get { return _variables[AnswerVariable]; }
}
/// <summary>Evaluates the specified expression.</summary>
/// <param name="expression">The expression to evaluate.</param>
/// <returns>The result of the evaluated expression.</returns>
/// <exception cref="ArgumentNullException">When expression is null or empty.</exception>
/// <exception cref="ParseException">When there is an error parsing the expression.</exception>
public double Evaluate(string expression)
{
if (string.IsNullOrEmpty(expression))
throw new ArgumentNullException("expression");
_expressionReader = new StringReader(expression);
_symbolStack.Clear();
_nestedFunctionDepth = 0;
_nestedGroupDepth = 0;
_expressionQueue.Clear();
ParseExpressionToQueue();
double result = CalculateFromQueue();
_variables[AnswerVariable] = result;
return result;
}
/// <summary>Registers a function for the <see cref="MathEvaluator"/>.</summary>
/// <param name="functionName">Name of the function.</param>
/// <param name="expression">An instance of <see cref="IExpression"/> for the function.</param>
/// <exception cref="ArgumentNullException">When functionName or expression are null.</exception>
/// <exception cref="ArgumentException">When IExpression.Evaluate property is null or the functionName is already registered.</exception>
/// <seealso cref="Functions"/>
/// <seealso cref="IExpression"/>
public void RegisterFunction(string functionName, IExpression expression)
{
if (string.IsNullOrEmpty(functionName))
throw new ArgumentNullException("functionName");
if (expression == null)
throw new ArgumentNullException("expression");
if (expression.Evaluate == null)
throw new ArgumentException(Resources.EvaluatePropertyCanNotBeNull, "expression");
if (_innerFunctions.BinarySearch(functionName) >= 0)
throw new ArgumentException(
string.Format(CultureInfo.CurrentCulture,
Resources.FunctionNameRegistered, functionName), "functionName");
_innerFunctions.Add(functionName);
_innerFunctions.Sort();
_expressionCache.Add(functionName, expression);
}
/// <summary>Determines whether the specified name is a function.</summary>
/// <param name="name">The name of the function.</param>
/// <returns><c>true</c> if the specified name is function; otherwise, <c>false</c>.</returns>
internal bool IsFunction(string name)
{
return (_innerFunctions.BinarySearch(name, StringComparer.OrdinalIgnoreCase) >= 0);
}
private void ParseExpressionToQueue()
{
char lastChar = '\0';
_currentChar = '\0';
do
{
// last non white space char
if (!char.IsWhiteSpace(_currentChar))
lastChar = _currentChar;
_currentChar = (char)_expressionReader.Read();
if (char.IsWhiteSpace(_currentChar))
continue;
if (TryNumber(lastChar))
continue;
if (TryString())
continue;
if (TryStartGroup())
continue;
if (TryComma())
continue;
if (TryOperator())
continue;
if (TryEndGroup())
continue;
if (TryConvert())
continue;
throw new ParseException(Resources.InvalidCharacterEncountered + _currentChar);
} while (_expressionReader.Peek() != -1);
ProcessSymbolStack();
}
private bool TryConvert()
{
if (_currentChar != '[')
return false;
_buffer.Length = 0;
_buffer.Append(_currentChar);
char p = (char)_expressionReader.Peek();
while (char.IsLetter(p) || char.IsWhiteSpace(p) || p == '-' || p == '>' || p == ']')
{
if (!char.IsWhiteSpace(p))
_buffer.Append((char)_expressionReader.Read());
else
_expressionReader.Read();
if (p == ']')
break;
p = (char)_expressionReader.Peek();
}
if (ConvertExpression.IsConvertExpression(_buffer.ToString()))
{
IExpression e = GetExpressionFromSymbol(_buffer.ToString());
_expressionQueue.Enqueue(e);
return true;
}
throw new ParseException(Resources.InvalidConvertionExpression + _buffer);
}
private bool TryString()
{
if (!char.IsLetter(_currentChar))
return false;
_buffer.Length = 0;
_buffer.Append(_currentChar);
char p = (char)_expressionReader.Peek();
while (char.IsLetter(p) || char.IsNumber(p))
{
_buffer.Append((char)_expressionReader.Read());
p = (char)_expressionReader.Peek();
}
if (_variables.ContainsKey(_buffer.ToString()))
{
double value = _variables[_buffer.ToString()];
NumberExpression expression = new NumberExpression(value);
_expressionQueue.Enqueue(expression);
return true;
}
if (IsFunction(_buffer.ToString()))
{
_symbolStack.Push(_buffer.ToString());
_nestedFunctionDepth++;
return true;
}
throw new ParseException(Resources.InvalidVariableEncountered + _buffer);
}
private bool TryStartGroup()
{
if (_currentChar != '(')
return false;
if (PeekNextNonWhitespaceChar() == ',')
{
throw new ParseException(Resources.InvalidCharacterEncountered + ",");
}
_symbolStack.Push(_currentChar.ToString());
_nestedGroupDepth++;
return true;
}
private bool TryComma()
{
if (_currentChar != ',')
return false;
if (_nestedFunctionDepth <= 0 ||
_nestedFunctionDepth < _nestedGroupDepth)
{
throw new ParseException(Resources.InvalidCharacterEncountered + _currentChar);
}
char nextChar = PeekNextNonWhitespaceChar();
if (nextChar == ')' || nextChar == ',')
{
throw new ParseException(Resources.InvalidCharacterEncountered + _currentChar);
}
return true;
}
private char PeekNextNonWhitespaceChar()
{
int next = _expressionReader.Peek();
while (next != -1 && char.IsWhiteSpace((char)next))
{
_expressionReader.Read();
next = _expressionReader.Peek();
}
return (char)next;
}
private bool TryEndGroup()
{
if (_currentChar != ')')
return false;
bool hasStart = false;
while (_symbolStack.Count > 0)
{
string p = _symbolStack.Pop();
if (p == "(")
{
hasStart = true;
if (_symbolStack.Count == 0)
break;
string n = _symbolStack.Peek();
if (IsFunction(n))
{
p = _symbolStack.Pop();
IExpression f = GetExpressionFromSymbol(p);
_expressionQueue.Enqueue(f);
_nestedFunctionDepth--;
}
_nestedGroupDepth--;
break;
}
IExpression e = GetExpressionFromSymbol(p);
_expressionQueue.Enqueue(e);
}
if (!hasStart)
throw new ParseException(Resources.UnbalancedParentheses);
return true;
}
private bool TryOperator()
{
if (!OperatorExpression.IsSymbol(_currentChar))
return false;
bool repeat;
string s = _currentChar.ToString();
do
{
string p = _symbolStack.Count == 0 ? string.Empty : _symbolStack.Peek();
repeat = false;
if (_symbolStack.Count == 0)
_symbolStack.Push(s);
else if (p == "(")
_symbolStack.Push(s);
else if (Precedence(s) > Precedence(p))
_symbolStack.Push(s);
else
{
IExpression e = GetExpressionFromSymbol(_symbolStack.Pop());
_expressionQueue.Enqueue(e);
repeat = true;
}
} while (repeat);
return true;
}
private bool TryNumber(char lastChar)
{
bool isNumber = NumberExpression.IsNumber(_currentChar);
// only negative when last char is group start or symbol
bool isNegative = NumberExpression.IsNegativeSign(_currentChar) &&
(lastChar == '\0' || lastChar == '(' || OperatorExpression.IsSymbol(lastChar));
if (!isNumber && !isNegative)
return false;
_buffer.Length = 0;
_buffer.Append(_currentChar);
char p = (char)_expressionReader.Peek();
while (NumberExpression.IsNumber(p))
{
_currentChar = (char) _expressionReader.Read();
_buffer.Append(_currentChar);
p = (char)_expressionReader.Peek();
}
double value;
if (!(double.TryParse(_buffer.ToString(), out value)))
throw new ParseException(Resources.InvalidNumberFormat + _buffer);
NumberExpression expression = new NumberExpression(value);
_expressionQueue.Enqueue(expression);
return true;
}
private void ProcessSymbolStack()
{
while (_symbolStack.Count > 0)
{
string p = _symbolStack.Pop();
if (p.Length == 1 && p == "(")
throw new ParseException(Resources.UnbalancedParentheses);
IExpression e = GetExpressionFromSymbol(p);
_expressionQueue.Enqueue(e);
}
}
private IExpression GetExpressionFromSymbol(string p)
{
IExpression e;
if (_expressionCache.ContainsKey(p))
e = _expressionCache[p];
else if (OperatorExpression.IsSymbol(p))
{
e = new OperatorExpression(p);
_expressionCache.Add(p, e);
}
else if (FunctionExpression.IsFunction(p))
{
e = new FunctionExpression(p, false);
_expressionCache.Add(p, e);
}
else if (ConvertExpression.IsConvertExpression(p))
{
e = new ConvertExpression(p);
_expressionCache.Add(p, e);
}
else
throw new ParseException(Resources.InvalidSymbolOnStack + p);
return e;
}
private static int Precedence(string c)
{
if (c.Length == 1 && (c[0] == '*' || c[0] == '/' || c[0] == '%'))
return 2;
return 1;
}
private double CalculateFromQueue()
{
double result;
_calculationStack.Clear();
foreach (IExpression expression in _expressionQueue)
{
if (_calculationStack.Count < expression.ArgumentCount)
throw new ParseException(Resources.NotEnoughNumbers + expression);
_parameters.Clear();
for (int i = 0; i < expression.ArgumentCount; i++)
_parameters.Push(_calculationStack.Pop());
_calculationStack.Push(expression.Evaluate.Invoke(_parameters.ToArray()));
}
result = _calculationStack.Pop();
if (_calculationStack.Any())
{
throw new ParseException(String.Format("{0}Items '{1}' were remaining on calculation stack.", Resources.InvalidSymbolOnStack, string.Join(", ", _calculationStack)));
}
return result;
}
#region IDisposable Members
/// <summary>
/// Releases unmanaged and - optionally - managed resources
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases unmanaged and managed resources
/// </summary>
/// <param name="disposing">
/// <c>true</c> to release both managed and unmanaged resources;
/// <c>false</c> to release only unmanaged resources.
/// </param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (_expressionReader != null)
{
_expressionReader.Dispose();
_expressionReader = null;
}
}
}
#endregion
}
}
| |
namespace PokerTell.PokerHand.Tests.Aquisition
{
using Infrastructure.Interfaces.PokerHand;
using Moq;
using NUnit.Framework;
using PokerTell.PokerHand.Aquisition;
using UnitTests;
[TestFixture]
public class AquiredPokerPlayerTests : TestWithLog
{
AquiredPokerPlayer _aquiredPlayer;
const int SmallBlind = 0;
const int BigBlind = 1;
#region SetUp/TearDown
[SetUp]
public void _Init()
{
const double someStack = 1.0;
const string someName = "test";
_aquiredPlayer = new AquiredPokerPlayer(someName, someStack);
}
#endregion
[Test]
public void AddRound_FirstRound_AddsTheRound()
{
var aquiredPokerRound = new AquiredPokerRound();
_aquiredPlayer.AddRound(aquiredPokerRound);
Assert.That(_aquiredPlayer[0], Is.EqualTo(aquiredPokerRound));
}
[Test]
public void AddRound_FirstRound_IncreasesCountToOne()
{
var aquiredPokerRound = new AquiredPokerRound();
_aquiredPlayer.AddRound(aquiredPokerRound);
Assert.That(_aquiredPlayer.Count, Is.EqualTo(1));
}
[Test]
public void AddRound_FourRoundsAddedAlready_PreventsRoundFromBeingAdded()
{
_aquiredPlayer.AddRound();
_aquiredPlayer.AddRound();
_aquiredPlayer.AddRound();
_aquiredPlayer.AddRound();
NotLogged(() => _aquiredPlayer.AddRound());
const int maximumNumberOfRounds = 4;
Assert.That(_aquiredPlayer.Count, Is.EqualTo(maximumNumberOfRounds));
}
[Test]
public void ChipsGained_NoRoundsAdded_ReturnsZero()
{
var aquiredPlayerMock = new AquiredPokerPlayerMock();
Assert.That(aquiredPlayerMock.ChipsGainedProp, Is.EqualTo(0));
}
[Test]
public void ChipsGained_OneRoundAdded_ReturnsChipsGainedInThatRound()
{
const double chipsGainedInRound = 1.0;
var roundStub = new Mock<IAquiredPokerRound>();
roundStub.SetupGet(get => get.ChipsGained).Returns(chipsGainedInRound);
var aquiredPlayerMock = new AquiredPokerPlayerMock();
aquiredPlayerMock.AddRound(roundStub.Object);
Assert.That(aquiredPlayerMock.ChipsGainedProp, Is.EqualTo(chipsGainedInRound));
}
[Test]
public void ChipsGained_TwoRoundsAdded_ReturnsSumOfChipsGainedInThoseRounds()
{
const double chipsGainedInFirstRound = 1.0;
const double chipsGainedInSecondRound = -0.5;
const double expectedGain = chipsGainedInFirstRound + chipsGainedInSecondRound;
var firstRoundStub = new Mock<IAquiredPokerRound>();
var secondRoundStub = new Mock<IAquiredPokerRound>();
firstRoundStub.SetupGet(get => get.ChipsGained).Returns(chipsGainedInFirstRound);
secondRoundStub.SetupGet(get => get.ChipsGained).Returns(chipsGainedInSecondRound);
var aquiredPlayerMock = new AquiredPokerPlayerMock();
aquiredPlayerMock.AddRound(firstRoundStub.Object);
aquiredPlayerMock.AddRound(secondRoundStub.Object);
Assert.That(aquiredPlayerMock.ChipsGainedProp, Is.EqualTo(expectedGain));
}
[Test, Sequential]
public void SetPosition_RelativeSeatIsSmallBlindNoHeadsUpVaryTotalPlayers_SetsPositionToSmallBlind(
[Values(2, 4, 6, 9)] int totalPlayers,
[Values(SmallBlind, SmallBlind, SmallBlind, SmallBlind)] int expectedPosition)
{
const int sbPosition = 0;
_aquiredPlayer.RelativeSeatNumber = sbPosition;
_aquiredPlayer.SetPosition(sbPosition, totalPlayers);
Assert.That(_aquiredPlayer.Position, Is.EqualTo(expectedPosition));
}
[Test, Sequential]
public void SetPosition_RelativeSeatIsSmallBlindNoHeadsUpVaryTotalPlayers_SetsPositionToButton(
[Values(4, 6, 9)] int totalPlayers,
[Values(3, 5, 8)] int expectedPosition)
{
int button = totalPlayers - 1;
const int sbPosition = 0;
_aquiredPlayer.RelativeSeatNumber = button;
_aquiredPlayer.SetPosition(sbPosition, totalPlayers);
Assert.That(_aquiredPlayer.Position, Is.EqualTo(expectedPosition));
}
[Test, Sequential]
public void SetPosition_NinePlayersRelativeSeatIsSmallBlindVarySmallBlindPosition_SetsPositionToSmallBlind(
[Values(4, 6, 8)] int sbPosition,
[Values(SmallBlind, SmallBlind, SmallBlind, SmallBlind)] int expectedPosition)
{
const int totalPlayers = 9;
_aquiredPlayer.RelativeSeatNumber = sbPosition;
_aquiredPlayer.SetPosition(sbPosition, totalPlayers);
Assert.That(_aquiredPlayer.Position, Is.EqualTo(expectedPosition));
}
[Test, Sequential]
public void SetPosition_NinePlayersRelativeSeatIsButtonAndVarySmallBlindPosition_SetsPositionToButton(
[Values(4, 6, 9)] int sbPosition,
[Values(8, 8, 8)] int expectedPosition)
{
const int totalPlayers = 9;
int button = sbPosition - 1;
_aquiredPlayer.RelativeSeatNumber = button;
_aquiredPlayer.SetPosition(sbPosition, totalPlayers);
Assert.That(_aquiredPlayer.Position, Is.EqualTo(expectedPosition));
}
[Test]
public void SetPosition_HeadsUpSmallBlindIsZeroRelativeSeatIsZero_SetsPositionToSmallBlind()
{
const int totalPlayers = 2;
const int sbPosition = 0;
const int expectedPosition = SmallBlind;
_aquiredPlayer.RelativeSeatNumber = sbPosition;
_aquiredPlayer.SetPosition(sbPosition, totalPlayers);
Assert.That(_aquiredPlayer.Position, Is.EqualTo(expectedPosition));
}
[Test]
public void SetPosition_HeadsUpSmallBlindIsOneRelativeSeatIsOne_SetsPositionToSmallBlind()
{
const int totalPlayers = 2;
const int sbPosition = 1;
const int expectedPosition = SmallBlind;
_aquiredPlayer.RelativeSeatNumber = sbPosition;
_aquiredPlayer.SetPosition(sbPosition, totalPlayers);
Assert.That(_aquiredPlayer.Position, Is.EqualTo(expectedPosition));
}
[Test]
public void SetPosition_HeadsUpSmallBlindIsZeroRelativeSeatIsOne_SetsPositionToBigBlind()
{
const int totalPlayers = 2;
const int sbPosition = 0;
const int bbPosition = 1;
const int expectedPosition = BigBlind;
_aquiredPlayer.RelativeSeatNumber = bbPosition;
_aquiredPlayer.SetPosition(sbPosition, totalPlayers);
Assert.That(_aquiredPlayer.Position, Is.EqualTo(expectedPosition));
}
[Test]
public void SetPosition_HeadsUpSmallBlindIsOneRelativeSeatIsZero_SetsPositionToBigBlind()
{
const int totalPlayers = 2;
const int sbPosition = 1;
const int bbPosition = 0;
const int expectedPosition = BigBlind;
_aquiredPlayer.RelativeSeatNumber = bbPosition;
_aquiredPlayer.SetPosition(sbPosition, totalPlayers);
Assert.That(_aquiredPlayer.Position, Is.EqualTo(expectedPosition));
}
[Test]
public void SetPosition_RelativeSeatBiggerThanTotalPlayers_ReturnsFalse()
{
const int totalPlayers = 6;
const int sbPosition = 0;
_aquiredPlayer.RelativeSeatNumber = totalPlayers + 1;
bool returnedValue = true;
NotLogged(() => returnedValue = _aquiredPlayer.SetPosition(sbPosition, totalPlayers));
Assert.That(returnedValue, Is.False);
}
}
internal class AquiredPokerPlayerMock : AquiredPokerPlayer
{
public double ChipsGainedProp
{
get { return ChipsGained(); }
}
}
}
| |
using System.Collections.Generic;
using System.Linq;
using BenchmarkDotNet.Attributes;
namespace MakingDotNETApplicationsFaster.Runners
{
[Config(typeof(CoreConfig))]
public class DotNetLoopPerformanceRunner
{
private const int ArrayLength = 10000;
private readonly int[] _array;
private readonly List<int> _list;
private int _arrayIndex;
public DotNetLoopPerformanceRunner()
{
_array = Enumerable.Range(0, ArrayLength).ToArray();
//array[ArrayLength] = 1; // throws error on runtime: that means that the CLR has to inject bounds checking into array access
_list = _array.ToList();
}
[Benchmark]
public long BaselineLoop()
{
long sum = 0;
for (var i = 0; i < _array.Length; i++)
{
sum += _array[i];
}
return sum;
}
[Benchmark]
public long BaselineLoopIndexPrefix()
{
long sum = 0;
for (var i = 0; i < _array.Length; ++i)
{
sum += _array[i];
}
return sum;
}
[Benchmark]
public long GetSumWhile()
{
long sum = 0;
var i = _array.Length;
while (i-- > 0)
{
sum += _array[i];
}
return sum;
}
[Benchmark]
public unsafe long UnsafeArrayLinearAccessWithPointerIncrement()
{
long sum = 0;
fixed (int* pointer = &_array[0])
{
var current = pointer;
for (var i = 0; i < _array.Length; ++i)
{
sum += *(current++);
}
}
return sum;
}
[Benchmark]
public unsafe long UnsafeArrayLinearAccess()
{
long sum = 0;
fixed (int* pointer = &_array[0])
{
var current = pointer;
for (var i = 0; i < _array.Length; ++i)
{
sum += *(current + i);
}
}
return sum;
}
[Benchmark]
public long GetSumForeach()
{
long sum = 0;
foreach (var val in _array)
{
sum += val;
}
return sum;
}
[Benchmark]
public long GetSumLinq()
{
return _array.Sum();
}
[Benchmark]
public long GetSumOfListFor()
{
long sum = 0;
for (var i = 0; i < _list.Count; i++)
{
sum += _list[i];
}
return sum;
}
[Benchmark]
public long GetSumOfListForeach()
{
long sum = 0;
foreach (var val in _list)
{
sum += val;
}
return sum;
}
[Benchmark]
public long GetSumOfListLinq()
{
return _list.Sum();
}
[Benchmark]
public long GetSumOfIEnumerableForeach()
{
var collection = _array as IEnumerable<int>;
long sum = 0;
foreach (var val in collection)
{
sum += val;
}
return sum;
}
[Benchmark]
public long GetSumLoopUnrollingArray()
{
long sum = 0;
for (var i = 0; i < _array.Length - 4; i += 4)
{
sum += _array[i];
sum += _array[i + 1];
sum += _array[i + 2];
sum += _array[i + 3];
}
return sum;
}
[Benchmark]
public long GetSumLoopUnrollingList()
{
long sum = 0;
for (var i = 0; i < _list.Count - 4; i += 4)
{
sum += _list[i];
sum += _list[i + 1];
sum += _list[i + 2];
sum += _list[i + 3];
}
return sum;
}
[Benchmark]
public long GetSumWithPrecalculatedLength()
{
long sum = 0;
for (var i = 0; i < ArrayLength; i++)
{
sum += _array[i];
}
return sum;
}
[Benchmark]
public long GetSumWithGoToOperator()
{
long sum = 0;
var i = 0;
next:
if (i < ArrayLength)
{
sum+=_array[i];
i++;
goto next;
}
return sum;
}
[Benchmark]
public long GetSumOfRecursion()
{
_arrayIndex = ArrayLength;
return GetSumRecursively();
}
private long GetSumRecursively()
{
if (_arrayIndex <= 0)
{
return 0;
}
return _array[--_arrayIndex] + GetSumRecursively();
}
[Benchmark]
public long GetSumOfTailRecursion()
{
_arrayIndex = ArrayLength - 1;
return GetSumOfTailRecursionInternal(0, _arrayIndex);
}
private long GetSumOfTailRecursionInternal(long sum, int index)
{
if (index < 0)
{
return sum;
}
return GetSumOfTailRecursionInternal(sum + _array[index], index - 1);
}
}
}
| |
using System;
namespace Bearded.Utilities
{
/// <summary>
/// This static class offers a variety of pseudo random methods.
/// The class is threadsafe and uses a different internal random object for each thread.
/// Note that several of the methods are slightly biased for the sake of performance.
/// </summary>
/// <remarks>The actual implementations of the custom random methods can be found in RandomExtensions.</remarks>
public static class StaticRandom
{
#region Threadsafe random
[ThreadStatic]
private static Random random;
/// <summary>
/// The thread safe instance of Random used by StaticRandom
/// </summary>
// is internal for use as default random in Linq.Extensions
internal static Random Random { get { return random ?? (random = new Random()); } }
/// <summary>
/// Overrides the Random object for the calling thread by one with the given seed.
/// </summary>
/// <param name="seed">The seed</param>
public static void SeedWith(int seed)
{
random = new Random(seed);
}
#endregion
#region Int()
/// <summary>
/// Returns a random integer.
/// </summary>
public static int Int()
{
return Random.Next();
}
/// <summary>
/// Returns a (biased) random integer in the interval [0, upper bound[.
/// </summary>
/// <param name="max">The exclusive upper bound.</param>
public static int Int(int max)
{
return Random.Next(max);
}
/// <summary>
/// Returns random (biased) integer in the interval [lower bound, upper bound[.
/// </summary>
/// <param name="min">The inclusive lower bound.</param>
/// <param name="max">The exclusive upper bound.</param>
public static int Int(int min, int max)
{
return Random.Next(min, max);
}
#endregion
#region Long()
/// <summary>
/// Returns random (biased) long integer.
/// </summary>
/// <returns></returns>
public static long Long()
{
return Random.NextLong();
}
/// <summary>
/// Returns random (biased) long integer in the interval [0, upper bound[.
/// </summary>
/// <param name="max">The exclusive upper bound.</param>
public static long Long(long max)
{
return Random.NextLong(max);
}
/// <summary>
/// Returns random (biased) long integer in the interval [lower bound, upper bound[.
/// </summary>
/// <param name="min">The inclusive lower bound.</param>
/// <param name="max">The exclusive upper bound.</param>
public static long Long(long min, long max)
{
return Random.NextLong(min, max);
}
#endregion
#region Double()
/// <summary>
/// Returns a random double in the interval [0, 1[.
/// </summary>
/// <returns></returns>
public static double Double()
{
return Random.NextDouble();
}
/// <summary>
/// Returns a random double in the interval [0, upper bound[.
/// </summary>
/// <param name="max">The exclusive upper bound.</param>
public static double Double(double max)
{
return Random.NextDouble(max);
}
/// <summary>
/// Returns a random double in the interval [lower bound, upper bound[.
/// </summary>
/// <param name="min">The inclusive lower bound.</param>
/// <param name="max">The exclusive upper bound.</param>
public static double Double(double min, double max)
{
return Random.NextDouble(min, max);
}
#endregion
#region NormalDouble()
/// <summary>
/// Generates a random double using the standard normal distribution.
/// </summary>
public static double NormalDouble()
{
return Random.NormalDouble();
}
/// <summary>
/// Generates a random double using the normal distribution with the given mean and deviation.
/// </summary>
/// <param name="mean">The expected value.</param>
/// <param name="deviation">The standard deviation.</param>
public static double NormalDouble(double mean, double deviation)
{
return Random.NormalDouble(mean, deviation);
}
#endregion
#region Float()
/// <summary>
/// Returns random float in the interval [0, 1[.
/// </summary>
public static float Float()
{
return Random.NextFloat();
}
/// <summary>
/// Returns a random float in the interval [0, upper bound[.
/// </summary>
/// <param name="max">The exclusive upper bound.</param>
public static float Float(float max)
{
return Random.NextFloat(max);
}
/// <summary>
/// Returns a random float in the interval [lower bound, upper bound[.
/// </summary>
/// <param name="min">The inclusive lower bound.</param>
/// <param name="max">The exclusive upper bound.</param>
public static float Float(float min, float max)
{
return Random.NextFloat(min, max);
}
#endregion
#region NormalFloat()
/// <summary>
/// Generates a random float using the standard normal distribution.
/// </summary>
public static float NormalFloat()
{
return Random.NormalFloat();
}
/// <summary>
/// Generates a random float using the normal distribution with the given mean and deviation.
/// </summary>
/// <param name="mean">The expected value.</param>
/// <param name="deviation">The standard deviation.</param>
public static float NormalFloat(float mean, float deviation)
{
return Random.NormalFloat(mean, deviation);
}
#endregion
#region Various
/// <summary>
/// Returns -1 or 1 randomly.
/// </summary>
public static int Sign()
{
return Random.NextSign();
}
/// <summary>
/// Returns a random boolean value.
/// </summary>
/// <param name="probability">The probability with which to return true.</param>
/// <returns>Always returns true for probabilities greater or equal to 1 and false for probabilities less or equal to 0.</returns>
public static bool Bool(double probability = 0.5)
{
return Random.NextBool(probability);
}
/// <summary>
/// Returns an integer with a given expected value. Will always return either the floor or ceil of the given value.
/// </summary>
/// <param name="value">The expected value.</param>
public static int Discretise(float value)
{
return Random.Discretise(value);
}
#endregion
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) Under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You Under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed Under the License is distributed on an "AS Is" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations Under the License.
==================================================================== */
namespace NPOI.HSSF.Model
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using NPOI.HSSF.Record;
using NPOI.SS.Formula;
using NPOI.SS.Formula.PTG;
using NPOI.Util;
using NPOI.SS.UserModel;
/**
* Link Table (OOO pdf reference: 4.10.3 ) <p/>
*
* The main data of all types of references is stored in the Link Table inside the Workbook Globals
* Substream (4.2.5). The Link Table itself is optional and occurs only, if there are any
* references in the document.
* <p/>
*
* In BIFF8 the Link Table consists of
* <ul>
* <li>zero or more EXTERNALBOOK Blocks<p/>
* each consisting of
* <ul>
* <li>exactly one EXTERNALBOOK (0x01AE) record</li>
* <li>zero or more EXTERNALNAME (0x0023) records</li>
* <li>zero or more CRN Blocks<p/>
* each consisting of
* <ul>
* <li>exactly one XCT (0x0059)record</li>
* <li>zero or more CRN (0x005A) records (documentation says one or more)</li>
* </ul>
* </li>
* </ul>
* </li>
* <li>zero or one EXTERNSHEET (0x0017) record</li>
* <li>zero or more DEFINEDNAME (0x0018) records</li>
* </ul>
*
*
* @author Josh Micich
*/
public class LinkTable
{
// TODO make this class into a record aggregate
private static ExternSheetRecord ReadExtSheetRecord(RecordStream rs)
{
List<ExternSheetRecord> temp = new List<ExternSheetRecord>(2);
while (rs.PeekNextClass() == typeof(ExternSheetRecord))
{
temp.Add((ExternSheetRecord)rs.GetNext());
}
int nItems = temp.Count;
if (nItems < 1)
{
throw new Exception("Expected an EXTERNSHEET record but got ("
+ rs.PeekNextClass().Name + ")");
}
if (nItems == 1)
{
// this is the normal case. There should be just one ExternSheetRecord
return temp[0];
}
// Some apps generate multiple ExternSheetRecords (see bug 45698).
// It seems like the best thing to do might be to combine these into one
ExternSheetRecord[] esrs = new ExternSheetRecord[nItems];
esrs = temp.ToArray();
return ExternSheetRecord.Combine(esrs);
}
private class CRNBlock
{
private CRNCountRecord _countRecord;
private CRNRecord[] _crns;
public CRNBlock(RecordStream rs)
{
_countRecord = (CRNCountRecord)rs.GetNext();
int nCRNs = _countRecord.NumberOfCRNs;
CRNRecord[] crns = new CRNRecord[nCRNs];
for (int i = 0; i < crns.Length; i++)
{
crns[i] = (CRNRecord)rs.GetNext();
}
_crns = crns;
}
public CRNRecord[] GetCrns()
{
return (CRNRecord[])_crns.Clone();
}
}
private class ExternalBookBlock
{
private SupBookRecord _externalBookRecord;
internal ExternalNameRecord[] _externalNameRecords;
private CRNBlock[] _crnBlocks;
/**
* Create a new block for registering add-in functions
*
* @see org.apache.poi.hssf.model.LinkTable#addNameXPtg(String)
*/
public ExternalBookBlock()
{
_externalBookRecord = SupBookRecord.CreateAddInFunctions();
_externalNameRecords = new ExternalNameRecord[0];
_crnBlocks = new CRNBlock[0];
}
public ExternalBookBlock(RecordStream rs)
{
_externalBookRecord = (SupBookRecord)rs.GetNext();
ArrayList temp = new ArrayList();
while (rs.PeekNextClass() == typeof(ExternalNameRecord))
{
temp.Add(rs.GetNext());
}
_externalNameRecords = (ExternalNameRecord[])temp.ToArray(typeof(ExternalNameRecord));
temp.Clear();
while (rs.PeekNextClass() == typeof(CRNCountRecord))
{
temp.Add(new CRNBlock(rs));
}
_crnBlocks = (CRNBlock[])temp.ToArray(typeof(CRNBlock));
}
/**
* Create a new block for external references.
*/
public ExternalBookBlock(String url, String[] sheetNames)
{
_externalBookRecord = SupBookRecord.CreateExternalReferences(url, sheetNames);
_crnBlocks = new CRNBlock[0];
}
/**
* Create a new block for internal references. It is called when constructing a new LinkTable.
*
* @see org.apache.poi.hssf.model.LinkTable#LinkTable(int, WorkbookRecordList)
*/
public ExternalBookBlock(int numberOfSheets)
{
_externalBookRecord = SupBookRecord.CreateInternalReferences((short)numberOfSheets);
_externalNameRecords = new ExternalNameRecord[0];
_crnBlocks = new CRNBlock[0];
}
public int NumberOfNames
{
get
{
return _externalNameRecords.Length;
}
}
public int AddExternalName(ExternalNameRecord rec)
{
ExternalNameRecord[] tmp = new ExternalNameRecord[_externalNameRecords.Length + 1];
Array.Copy(_externalNameRecords, 0, tmp, 0, _externalNameRecords.Length);
tmp[tmp.Length - 1] = rec;
_externalNameRecords = tmp;
return _externalNameRecords.Length - 1;
}
public SupBookRecord GetExternalBookRecord()
{
return _externalBookRecord;
}
public String GetNameText(int definedNameIndex)
{
return _externalNameRecords[definedNameIndex].Text;
}
/**
* Performs case-insensitive search
* @return -1 if not found
*/
public int GetIndexOfName(String name)
{
for (int i = 0; i < _externalNameRecords.Length; i++)
{
if (_externalNameRecords[i].Text.Equals(name, StringComparison.OrdinalIgnoreCase))
{
return i;
}
}
return -1;
}
public int GetNameIx(int definedNameIndex)
{
return _externalNameRecords[definedNameIndex].Ix;
}
}
private ExternalBookBlock[] _externalBookBlocks;
private ExternSheetRecord _externSheetRecord;
private List<NameRecord> _definedNames;
private int _recordCount;
private WorkbookRecordList _workbookRecordList; // TODO - would be nice to Remove this
public LinkTable(List<Record> inputList, int startIndex, WorkbookRecordList workbookRecordList, Dictionary<String, NameCommentRecord> commentRecords)
{
_workbookRecordList = workbookRecordList;
RecordStream rs = new RecordStream(inputList, startIndex);
ArrayList temp = new ArrayList();
while (rs.PeekNextClass() == typeof(SupBookRecord))
{
temp.Add(new ExternalBookBlock(rs));
}
//_externalBookBlocks = new ExternalBookBlock[temp.Count];
_externalBookBlocks = (ExternalBookBlock[])temp.ToArray(typeof(ExternalBookBlock));
temp.Clear();
if (_externalBookBlocks.Length > 0)
{
// If any ExternalBookBlock present, there is always 1 of ExternSheetRecord
if (rs.PeekNextClass() != typeof(ExternSheetRecord))
{
// not quite - if written by google docs
_externSheetRecord = null;
}
else
{
_externSheetRecord = ReadExtSheetRecord(rs);
}
}
else
{
_externSheetRecord = null;
}
_definedNames = new List<NameRecord>();
// collect zero or more DEFINEDNAMEs id=0x18
while (true)
{
Type nextClass = rs.PeekNextClass();
if (nextClass == typeof(NameRecord))
{
NameRecord nr = (NameRecord)rs.GetNext();
_definedNames.Add(nr);
}
else if (nextClass == typeof(NameCommentRecord))
{
NameCommentRecord ncr = (NameCommentRecord)rs.GetNext();
//commentRecords.Add(ncr.NameText, ncr);
commentRecords[ncr.NameText] = ncr;
}
else
{
break;
}
}
_recordCount = rs.GetCountRead();
for (int i = startIndex; i < startIndex + _recordCount; i++)
{
_workbookRecordList.Records.Add(inputList[i]);
}
}
public LinkTable(int numberOfSheets, WorkbookRecordList workbookRecordList)
{
_workbookRecordList = workbookRecordList;
_definedNames = new List<NameRecord>();
_externalBookBlocks = new ExternalBookBlock[] {
new ExternalBookBlock(numberOfSheets),
};
_externSheetRecord = new ExternSheetRecord();
_recordCount = 2;
// tell _workbookRecordList about the 2 new records
SupBookRecord supbook = _externalBookBlocks[0].GetExternalBookRecord();
int idx = FindFirstRecordLocBySid(CountryRecord.sid);
if (idx < 0)
{
throw new Exception("CountryRecord not found");
}
_workbookRecordList.Add(idx + 1, _externSheetRecord);
_workbookRecordList.Add(idx + 1, supbook);
}
/**
* TODO - would not be required if calling code used RecordStream or similar
*/
public int RecordCount
{
get { return _recordCount; }
}
public NameRecord GetSpecificBuiltinRecord(byte builtInCode, int sheetNumber)
{
IEnumerator<NameRecord> iterator = _definedNames.GetEnumerator();
while (iterator.MoveNext())
{
NameRecord record = iterator.Current;
//print areas are one based
if (record.BuiltInName == builtInCode && record.SheetNumber == sheetNumber)
{
return record;
}
}
return null;
}
public void RemoveBuiltinRecord(byte name, int sheetIndex)
{
//the name array is smaller so searching through it should be faster than
//using the FindFirstXXXX methods
NameRecord record = GetSpecificBuiltinRecord(name, sheetIndex);
if (record != null)
{
_definedNames.Remove(record);
}
// TODO - do we need "Workbook.records.Remove(...);" similar to that in Workbook.RemoveName(int namenum) {}?
}
/**
* @param extRefIndex as from a {@link Ref3DPtg} or {@link Area3DPtg}
* @return -1 if the reference is to an external book
*/
public int GetFirstInternalSheetIndexForExtIndex(int extRefIndex)
{
if (extRefIndex >= _externSheetRecord.NumOfRefs || extRefIndex < 0)
{
return -1;
}
return _externSheetRecord.GetFirstSheetIndexFromRefIndex(extRefIndex);
}
/**
* @param extRefIndex as from a {@link Ref3DPtg} or {@link Area3DPtg}
* @return -1 if the reference is to an external book
*/
public int GetLastInternalSheetIndexForExtIndex(int extRefIndex)
{
if (extRefIndex >= _externSheetRecord.NumOfRefs || extRefIndex < 0)
{
return -1;
}
return _externSheetRecord.GetLastSheetIndexFromRefIndex(extRefIndex);
}
[Obsolete]
public void UpdateIndexToInternalSheet(int extRefIndex, int offset)
{
_externSheetRecord.AdjustIndex(extRefIndex, offset);
}
public void RemoveSheet(int sheetIdx)
{
_externSheetRecord.RemoveSheet(sheetIdx);
}
public int NumNames
{
get
{
return _definedNames.Count;
}
}
private int ExtendExternalBookBlocks(ExternalBookBlock newBlock)
{
ExternalBookBlock[] tmp = new ExternalBookBlock[_externalBookBlocks.Length + 1];
Array.Copy(_externalBookBlocks, 0, tmp, 0, _externalBookBlocks.Length);
tmp[tmp.Length - 1] = newBlock;
_externalBookBlocks = tmp;
return (_externalBookBlocks.Length - 1);
}
private int FindRefIndexFromExtBookIndex(int extBookIndex)
{
return _externSheetRecord.FindRefIndexFromExtBookIndex(extBookIndex);
}
/**
* Finds the external name definition for the given name,
* optionally restricted by externsheet index, and returns
* (if found) as a NameXPtg.
* @param sheetRefIndex The Extern Sheet Index to look for, or -1 if any
*/
public NameXPtg GetNameXPtg(String name, int sheetRefIndex)
{
// first find any external book block that contains the name:
for (int i = 0; i < _externalBookBlocks.Length; i++)
{
int definedNameIndex = _externalBookBlocks[i].GetIndexOfName(name);
if (definedNameIndex < 0)
{
continue;
}
// Found one
int thisSheetRefIndex = FindRefIndexFromExtBookIndex(i);
if (thisSheetRefIndex >= 0)
{
// Check for the sheet index match, if requested
if (sheetRefIndex == -1 || thisSheetRefIndex == sheetRefIndex)
{
return new NameXPtg(thisSheetRefIndex, definedNameIndex);
}
}
}
return null;
}
public NameRecord GetNameRecord(int index)
{
return (NameRecord)_definedNames[index];
}
public void AddName(NameRecord name)
{
_definedNames.Add(name);
// TODO - this Is messy
// Not the most efficient way but the other way was causing too many bugs
int idx = FindFirstRecordLocBySid(ExternSheetRecord.sid);
if (idx == -1) idx = FindFirstRecordLocBySid(SupBookRecord.sid);
if (idx == -1) idx = FindFirstRecordLocBySid(CountryRecord.sid);
int countNames = _definedNames.Count;
_workbookRecordList.Add(idx + countNames, name);
}
/**
* Register an external name in this workbook
*
* @param name the name to register
* @return a NameXPtg describing this name
*/
public NameXPtg AddNameXPtg(String name)
{
int extBlockIndex = -1;
ExternalBookBlock extBlock = null;
// find ExternalBlock for Add-In functions and remember its index
for (int i = 0; i < _externalBookBlocks.Length; i++)
{
SupBookRecord ebr = _externalBookBlocks[i].GetExternalBookRecord();
if (ebr.IsAddInFunctions)
{
extBlock = _externalBookBlocks[i];
extBlockIndex = i;
break;
}
}
// An ExternalBlock for Add-In functions was not found. Create a new one.
if (extBlock == null)
{
extBlock = new ExternalBookBlock();
extBlockIndex = ExtendExternalBookBlocks(extBlock);
// add the created SupBookRecord before ExternSheetRecord
int idx = FindFirstRecordLocBySid(ExternSheetRecord.sid);
_workbookRecordList.Add(idx, extBlock.GetExternalBookRecord());
// register the SupBookRecord in the ExternSheetRecord
// -2 means that the scope of this name is Workbook and the reference applies to the entire workbook.
_externSheetRecord.AddRef(_externalBookBlocks.Length - 1, -2, -2);
}
// create a ExternalNameRecord that will describe this name
ExternalNameRecord extNameRecord = new ExternalNameRecord();
extNameRecord.Text = (name);
// The docs don't explain why Excel set the formula to #REF!
extNameRecord.SetParsedExpression(new Ptg[] { ErrPtg.REF_INVALID });
int nameIndex = extBlock.AddExternalName(extNameRecord);
int supLinkIndex = 0;
// find the posistion of the Add-In SupBookRecord in the workbook stream,
// the created ExternalNameRecord will be appended to it
for (IEnumerator iterator = _workbookRecordList.GetEnumerator(); iterator.MoveNext(); supLinkIndex++)
{
Record record = (Record)iterator.Current;
if (record is SupBookRecord)
{
if (((SupBookRecord)record).IsAddInFunctions) break;
}
}
int numberOfNames = extBlock.NumberOfNames;
// a new name is inserted in the end of the SupBookRecord, after the last name
_workbookRecordList.Add(supLinkIndex + numberOfNames, extNameRecord);
int fakeSheetIdx = -2; /* the scope is workbook*/
int ix = _externSheetRecord.GetRefIxForSheet(extBlockIndex, fakeSheetIdx, fakeSheetIdx);
return new NameXPtg(ix, nameIndex);
}
public void RemoveName(int namenum)
{
_definedNames.RemoveAt(namenum);
}
private static int GetSheetIndex(String[] sheetNames, String sheetName)
{
for (int i = 0; i < sheetNames.Length; i++)
{
if (sheetNames[i].Equals(sheetName))
{
return i;
}
}
throw new InvalidOperationException("External workbook does not contain sheet '" + sheetName + "'");
}
private int GetExternalWorkbookIndex(String workbookName)
{
for (int i = 0; i < _externalBookBlocks.Length; i++)
{
SupBookRecord ebr = _externalBookBlocks[i].GetExternalBookRecord();
if (!ebr.IsExternalReferences)
{
continue;
}
if (workbookName.Equals(ebr.URL))
{ // not sure if 'equals()' works when url has a directory
return i;
}
}
return -1;
}
public int LinkExternalWorkbook(String name, IWorkbook externalWorkbook)
{
int extBookIndex = GetExternalWorkbookIndex(name);
if (extBookIndex != -1)
{
// Already linked!
return extBookIndex;
}
// Create a new SupBookRecord
String[] sheetNames = new String[externalWorkbook.NumberOfSheets];
for (int sn = 0; sn < sheetNames.Length; sn++)
{
sheetNames[sn] = externalWorkbook.GetSheetName(sn);
}
//\000 is octal digit in java, but c# think it is a '\0' and two zero.
String url = "\0" + name;
ExternalBookBlock block = new ExternalBookBlock(url, sheetNames);
// Add it into the list + records
extBookIndex = ExtendExternalBookBlocks(block);
// add the created SupBookRecord before ExternSheetRecord
int idx = FindFirstRecordLocBySid(ExternSheetRecord.sid);
if (idx == -1)
{
idx = _workbookRecordList.Count;
}
_workbookRecordList.Add(idx, block.GetExternalBookRecord());
// Setup links for the sheets
for (int sn = 0; sn < sheetNames.Length; sn++)
{
_externSheetRecord.AddRef(extBookIndex, sn, sn);
}
// Report where it went
return extBookIndex;
}
public int GetExternalSheetIndex(String workbookName, String firstSheetName, String lastSheetName)
{
int externalBookIndex = GetExternalWorkbookIndex(workbookName);
if (externalBookIndex == -1)
{
throw new RuntimeException("No external workbook with name '" + workbookName + "'");
}
SupBookRecord ebrTarget = _externalBookBlocks[externalBookIndex].GetExternalBookRecord();
int firstSheetIndex = GetSheetIndex(ebrTarget.SheetNames, firstSheetName);
int lastSheetIndex = GetSheetIndex(ebrTarget.SheetNames, lastSheetName);
// Find or add the external sheet record definition for this
int result = _externSheetRecord.GetRefIxForSheet(externalBookIndex, firstSheetIndex, lastSheetIndex);
if (result < 0)
{
result = _externSheetRecord.AddRef(externalBookIndex, firstSheetIndex, lastSheetIndex);
}
return result;
}
public String[] GetExternalBookAndSheetName(int extRefIndex)
{
int ebIx = _externSheetRecord.GetExtbookIndexFromRefIndex(extRefIndex);
SupBookRecord ebr = _externalBookBlocks[ebIx].GetExternalBookRecord();
if (!ebr.IsExternalReferences)
{
return null;
}
// Sheet name only applies if not a global reference
int shIx1 = _externSheetRecord.GetFirstSheetIndexFromRefIndex(extRefIndex);
int shIx2 = _externSheetRecord.GetLastSheetIndexFromRefIndex(extRefIndex);
String firstSheetName = null;
String lastSheetName = null;
if (shIx1 >= 0)
{
firstSheetName = ebr.SheetNames[shIx1];
}
if (shIx2 >= 0)
{
lastSheetName = ebr.SheetNames[shIx2];
}
if (shIx1 == shIx2)
{
return new String[] {
ebr.URL,
firstSheetName
};
}
else
{
return new String[] {
ebr.URL,
firstSheetName,
lastSheetName
};
}
}
public int CheckExternSheet(int sheetIndex)
{
return CheckExternSheet(sheetIndex, sheetIndex);
}
public int CheckExternSheet(int firstSheetIndex, int lastSheetIndex)
{
int thisWbIndex = -1; // this is probably always zero
for (int i = 0; i < _externalBookBlocks.Length; i++)
{
SupBookRecord ebr = _externalBookBlocks[i].GetExternalBookRecord();
if (ebr.IsInternalReferences)
{
thisWbIndex = i;
break;
}
}
if (thisWbIndex < 0)
{
throw new InvalidOperationException("Could not find 'internal references' EXTERNALBOOK");
}
//Trying to find reference to this sheet
int j = _externSheetRecord.GetRefIxForSheet(thisWbIndex, firstSheetIndex, lastSheetIndex);
if (j >= 0)
{
return j;
}
//We haven't found reference to this sheet
return _externSheetRecord.AddRef(thisWbIndex, firstSheetIndex, lastSheetIndex);
}
/**
* copied from Workbook
*/
private int FindFirstRecordLocBySid(short sid)
{
int index = 0;
for (IEnumerator<Record> iterator = _workbookRecordList.GetEnumerator(); iterator.MoveNext(); )
{
Record record = iterator.Current;
if (record.Sid == sid)
{
return index;
}
index++;
}
return -1;
}
public String ResolveNameXText(int refIndex, int definedNameIndex, InternalWorkbook workbook)
{
int extBookIndex = _externSheetRecord.GetExtbookIndexFromRefIndex(refIndex);
int firstTabIndex = _externSheetRecord.GetFirstSheetIndexFromRefIndex(refIndex);
if (firstTabIndex == -1)
{
// The referenced sheet could not be found
throw new RuntimeException("Referenced sheet could not be found");
}
// Does it exist via the external book block?
ExternalBookBlock externalBook = _externalBookBlocks[extBookIndex];
if (externalBook._externalNameRecords.Length > definedNameIndex)
{
return _externalBookBlocks[extBookIndex].GetNameText(definedNameIndex);
}
else if (firstTabIndex == -2)
{
// Workbook scoped name, not actually external after all
NameRecord nr = GetNameRecord(definedNameIndex);
int sheetNumber = nr.SheetNumber;
StringBuilder text = new StringBuilder();
if (sheetNumber > 0)
{
String sheetName = workbook.GetSheetName(sheetNumber - 1);
SheetNameFormatter.AppendFormat(text, sheetName);
text.Append("!");
}
text.Append(nr.NameText);
return text.ToString();
}
else
{
throw new IndexOutOfRangeException(
"Ext Book Index relative but beyond the supported length, was " +
extBookIndex + " but maximum is " + _externalBookBlocks.Length
);
}
}
public int ResolveNameXIx(int refIndex, int definedNameIndex)
{
int extBookIndex = _externSheetRecord.GetExtbookIndexFromRefIndex(refIndex);
return _externalBookBlocks[extBookIndex].GetNameIx(definedNameIndex);
}
/**
* Changes an external referenced file to another file.
* A formular in Excel which refers a cell in another file is saved in two parts:
* The referenced file is stored in an reference table. the row/cell information is saved separate.
* This method invokation will only change the reference in the lookup-table itself.
* @param oldUrl The old URL to search for and which is to be replaced
* @param newUrl The URL replacement
* @return true if the oldUrl was found and replaced with newUrl. Otherwise false
*/
public bool ChangeExternalReference(String oldUrl, String newUrl)
{
foreach (ExternalBookBlock ex in _externalBookBlocks)
{
SupBookRecord externalRecord = ex.GetExternalBookRecord();
if (externalRecord.IsExternalReferences
&& externalRecord.URL.Equals(oldUrl))
{
externalRecord.URL = (newUrl);
return true;
}
}
return false;
}
}
}
| |
#region License, Terms and Author(s)
//
// ELMAH - Error Logging Modules and Handlers for ASP.NET
// Copyright (c) 2004-9 Atif Aziz. All rights reserved.
//
// Author(s):
//
// Atif Aziz, http://www.raboof.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
[assembly: Elmah.Scc("$Id: ErrorMailHtmlFormatter.cs 566 2009-05-11 10:37:10Z azizatif $")]
namespace Elmah
{
#region Imports
using System;
using TextWriter = System.IO.TextWriter;
using HttpUtility = System.Web.HttpUtility;
using NameValueCollection = System.Collections.Specialized.NameValueCollection;
using HtmlTextWriter = System.Web.UI.HtmlTextWriter;
using Html32TextWriter = System.Web.UI.Html32TextWriter;
using HtmlTextWriterTag = System.Web.UI.HtmlTextWriterTag;
using HtmlTextWriterAttribute = System.Web.UI.HtmlTextWriterAttribute;
#endregion
/// <summary>
/// Formats the HTML to display the details of a given error that is
/// suitable for sending as the body of an e-mail message.
/// </summary>
public class ErrorMailHtmlFormatter : ErrorTextFormatter
{
private HtmlTextWriter _writer;
private Error _error;
/// <summary>
/// Returns the text/html MIME type that is the format provided
/// by this <see cref="ErrorTextFormatter"/> implementation.
/// </summary>
public override string MimeType
{
get { return "text/html"; }
}
/// <summary>
/// Formats a complete HTML document describing the given
/// <see cref="Error"/> instance.
/// </summary>
public override void Format(TextWriter writer, Error error)
{
if (writer == null)
throw new ArgumentNullException("writer");
if (error == null)
throw new ArgumentNullException("error");
//
// Create a HTML writer on top of the given writer and
// write out the document. Note that the incoming
// writer and error parameters are promoted to members
// during formatting in order to avoid passing them
// as context to each downstream method responsible
// for rendering a part of the document. The important
// assumption here is that Format will never be called
// from more than one thread at the same time.
//
Html32TextWriter htmlWriter = new Html32TextWriter(writer);
htmlWriter.RenderBeginTag(HtmlTextWriterTag.Html);
_writer = htmlWriter;
_error = error;
try
{
RenderHead();
RenderBody();
}
finally
{
_writer = null;
_error = null;
}
htmlWriter.RenderEndTag(); // </html>
htmlWriter.WriteLine();
}
/// <summary>
/// Gets the <see cref="HtmlTextWriter"/> used for HTML formatting.
/// </summary>
/// <remarks>
/// This property is only available to downstream methods in the
/// context of the <see cref="Format"/> method call.
/// </remarks>
protected HtmlTextWriter Writer
{
get { return _writer; }
}
/// <summary>
/// Gets the <see cref="Error"/> object for which a HTML document
/// is being formatted.
/// </summary>
/// <remarks>
/// This property is only available to downstream methods in the
/// context of the <see cref="Format"/> method call.
/// </remarks>
protected Error Error
{
get { return _error; }
}
/// <summary>
/// Renders the <head> section of the HTML document.
/// </summary>
protected virtual void RenderHead()
{
HtmlTextWriter writer = this.Writer;
writer.RenderBeginTag(HtmlTextWriterTag.Head);
//
// Write the document title and style.
//
writer.RenderBeginTag(HtmlTextWriterTag.Title);
writer.Write("Error: ");
HttpUtility.HtmlEncode(this.Error.Message, writer);
writer.RenderEndTag(); // </title>
writer.WriteLine();
RenderStyle();
writer.RenderEndTag(); // </head>
writer.WriteLine();
}
/// <summary>
/// Renders the <body> section of the HTML document.
/// </summary>
protected virtual void RenderBody()
{
HtmlTextWriter writer = this.Writer;
writer.RenderBeginTag(HtmlTextWriterTag.Body);
RenderSummary();
if (this.Error.Detail.Length != 0)
{
RenderDetail();
}
RenderCollections();
RenderFooter();
writer.RenderEndTag(); // </body>
writer.WriteLine();
}
/// <summary>
/// Renders the footer content that appears at the end of the
/// HTML document body.
/// </summary>
protected virtual void RenderFooter()
{
HtmlTextWriter writer = this.Writer;
writer.RenderBeginTag(HtmlTextWriterTag.P);
PoweredBy poweredBy = new PoweredBy();
poweredBy.RenderControl(writer);
writer.RenderEndTag();
}
/// <summary>
/// Renders the <style> element along with in-line styles
/// used to format the body of the HTML document.
/// </summary>
protected virtual void RenderStyle()
{
HtmlTextWriter writer = this.Writer;
writer.RenderBeginTag(HtmlTextWriterTag.Style);
writer.WriteLine(@"
body { font-family: verdana, arial, helvetic; font-size: x-small; }
td, th, pre { font-size: x-small; }
#errorDetail { padding: 1em; background-color: #FFFFCC; }
#errorMessage { font-size: medium; font-style: italic; color: maroon; }
h1 { font-size: small; }");
writer.RenderEndTag(); // </style>
writer.WriteLine();
}
/// <summary>
/// Renders the details about the <see cref="Error" /> object in
/// body of the HTML document.
/// </summary>
protected virtual void RenderDetail()
{
HtmlTextWriter writer = this.Writer;
//
// Write the full text of the error.
//
writer.AddAttribute(HtmlTextWriterAttribute.Id, "errorDetail");
writer.RenderBeginTag(HtmlTextWriterTag.Pre);
writer.InnerWriter.Flush();
HttpUtility.HtmlEncode(this.Error.Detail, writer.InnerWriter);
writer.RenderEndTag(); // </pre>
writer.WriteLine();
}
/// <summary>
/// Renders a summary about the <see cref="Error"/> object in
/// body of the HTML document.
/// </summary>
protected virtual void RenderSummary()
{
HtmlTextWriter writer = this.Writer;
Error error = this.Error;
//
// Write the error type and message.
//
writer.AddAttribute(HtmlTextWriterAttribute.Id, "errorMessage");
writer.RenderBeginTag(HtmlTextWriterTag.P);
HttpUtility.HtmlEncode(error.Type, writer);
writer.Write(": ");
HttpUtility.HtmlEncode(error.Message, writer);
writer.RenderEndTag(); // </p>
writer.WriteLine();
//
// Write out the time, in UTC, at which the error was generated.
//
if (error.Time != DateTime.MinValue)
{
writer.RenderBeginTag(HtmlTextWriterTag.P);
writer.Write("Generated: ");
HttpUtility.HtmlEncode(error.Time.ToUniversalTime().ToString("r"), writer);
writer.RenderEndTag(); // </p>
writer.WriteLine();
}
}
/// <summary>
/// Renders the diagnostic collections of the <see cref="Error" /> object in
/// body of the HTML document.
/// </summary>
protected virtual void RenderCollections()
{
RenderCollection(this.Error.ServerVariables, "Server Variables");
}
/// <summary>
/// Renders a collection as a table in HTML document body.
/// </summary>
/// <remarks>
/// This method is called by <see cref="RenderCollections"/> to
/// format a diagnostic collection from <see cref="Error"/> object.
/// </remarks>
protected virtual void RenderCollection(NameValueCollection collection, string caption)
{
if (collection == null || collection.Count == 0)
{
return;
}
HtmlTextWriter writer = this.Writer;
writer.RenderBeginTag(HtmlTextWriterTag.H1);
HttpUtility.HtmlEncode(caption, writer);
writer.RenderEndTag(); // </h1>
writer.WriteLine();
//
// Write a table with each key in the left column
// and its value in the right column.
//
writer.AddAttribute(HtmlTextWriterAttribute.Cellpadding, "5");
writer.AddAttribute(HtmlTextWriterAttribute.Cellspacing, "0");
writer.AddAttribute(HtmlTextWriterAttribute.Border, "1");
writer.AddAttribute(HtmlTextWriterAttribute.Width, "100%");
writer.RenderBeginTag(HtmlTextWriterTag.Table);
//
// Write the column headings.
//
writer.AddAttribute(HtmlTextWriterAttribute.Valign, "top");
writer.RenderBeginTag(HtmlTextWriterTag.Tr);
writer.AddAttribute(HtmlTextWriterAttribute.Align, "left");
writer.RenderBeginTag(HtmlTextWriterTag.Th);
writer.Write("Name");
writer.RenderEndTag(); // </th>
writer.AddAttribute(HtmlTextWriterAttribute.Align, "left");
writer.RenderBeginTag(HtmlTextWriterTag.Th);
writer.Write("Value");
writer.RenderEndTag(); // </th>
writer.RenderEndTag(); // </tr>
//
// Write the main body of the table containing keys
// and values in a two-column layout.
//
foreach (string key in collection.Keys)
{
writer.AddAttribute(HtmlTextWriterAttribute.Valign, "top");
writer.RenderBeginTag(HtmlTextWriterTag.Tr);
writer.RenderBeginTag(HtmlTextWriterTag.Td);
HttpUtility.HtmlEncode(key, writer);
writer.RenderEndTag(); // </td>
writer.RenderBeginTag(HtmlTextWriterTag.Td);
string value = Mask.NullString(collection[key]);
if (value.Length != 0)
{
HttpUtility.HtmlEncode(value, writer);
}
else
{
writer.Write(" ");
}
writer.RenderEndTag(); // </td>
writer.RenderEndTag(); // </tr>
}
writer.RenderEndTag(); // </table>
writer.WriteLine();
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="GraphStageTimersSpec.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.Threading.Tasks;
using Akka.Actor;
using Akka.Streams.Dsl;
using Akka.Streams.Implementation.Fusing;
using Akka.Streams.Stage;
using Akka.Streams.TestKit;
using Akka.Streams.TestKit.Tests;
using Akka.TestKit;
using FluentAssertions;
using Xunit;
using Xunit.Abstractions;
// ReSharper disable InvokeAsExtensionMethod
namespace Akka.Streams.Tests.Dsl
{
public class GraphStageTimersSpec : AkkaSpec
{
private ActorMaterializer Materializer { get; }
public GraphStageTimersSpec(ITestOutputHelper helper) : base(helper)
{
var settings = ActorMaterializerSettings.Create(Sys);
Materializer = ActorMaterializer.Create(Sys, settings);
}
private SideChannel SetupIsolatedStage()
{
var channel = new SideChannel();
var stopPromise =
Source.Maybe<int>()
.Via(new TestStage(TestActor, channel, this))
.To(Sink.Ignore<int>())
.Run(Materializer);
channel.StopPromise = stopPromise;
AwaitCondition(()=>channel.IsReady);
return channel;
}
[Fact]
public void GraphStage_timer_support_must_receive_single_shot_timer()
{
var driver = SetupIsolatedStage();
Within(TimeSpan.FromSeconds(2), () =>
{
Within(TimeSpan.FromMilliseconds(500), TimeSpan.FromSeconds(1), () =>
{
driver.Tell(TestSingleTimer.Instance);
ExpectMsg(new Tick(1));
});
ExpectNoMsg(TimeSpan.FromSeconds(1));
});
driver.StopStage();
}
[Fact]
public void GraphStage_timer_support_must_resubmit_single_shot_timer()
{
var driver = SetupIsolatedStage();
Within(TimeSpan.FromSeconds(2.5), () =>
{
Within(TimeSpan.FromMilliseconds(500), TimeSpan.FromSeconds(1), () =>
{
driver.Tell(TestSingleTimerResubmit.Instance);
ExpectMsg(new Tick(1));
});
Within(TimeSpan.FromSeconds(1), () => ExpectMsg(new Tick(2)));
ExpectNoMsg(TimeSpan.FromSeconds(1));
});
driver.StopStage();
}
[Fact]
public void GraphStage_timer_support_must_correctly_cancel_a_named_timer()
{
var driver = SetupIsolatedStage();
driver.Tell(TestCancelTimer.Instance);
Within(TimeSpan.FromMilliseconds(500), () => ExpectMsg<TestCancelTimerAck>());
Within(TimeSpan.FromMilliseconds(300), TimeSpan.FromSeconds(1), () => ExpectMsg(new Tick(1)));
ExpectNoMsg(TimeSpan.FromSeconds(1));
driver.StopStage();
}
[Fact]
public void GraphStage_timer_support_must_receive_and_cancel_a_repeated_timer()
{
var driver = SetupIsolatedStage();
driver.Tell(TestRepeatedTimer.Instance);
var seq = ReceiveWhile(TimeSpan.FromSeconds(2), o => (Tick)o);
seq.Should().HaveCount(5);
ExpectNoMsg(TimeSpan.FromSeconds(1));
driver.StopStage();
}
[Fact]
public void GraphStage_timer_support_must_produce_scheduled_ticks_as_expected()
{
this.AssertAllStagesStopped(() =>
{
var upstream = this.CreatePublisherProbe<int>();
var downstream = this.CreateSubscriberProbe<int>();
Source.FromPublisher(upstream)
.Via(new TestStage2())
.RunWith(Sink.FromSubscriber(downstream), Materializer);
downstream.Request(5);
downstream.ExpectNext(1, 2, 3);
downstream.ExpectNoMsg(TimeSpan.FromSeconds(1));
upstream.SendComplete();
downstream.ExpectComplete();
}, Materializer);
}
[Fact]
public void GraphStage_timer_support_must_propagate_error_if_OnTimer_throws_an_Exception()
{
this.AssertAllStagesStopped(() =>
{
var exception = new TestException("Expected exception to the rule");
var upstream = this.CreatePublisherProbe<int>();
var downstream = this.CreateSubscriberProbe<int>();
Source.FromPublisher(upstream)
.Via(new ThrowStage(exception))
.RunWith(Sink.FromSubscriber(downstream), Materializer);
downstream.Request(1);
downstream.ExpectError().Should().Be(exception);
}, Materializer);
}
#region Test classes
private sealed class TestSingleTimer
{
public static readonly TestSingleTimer Instance = new TestSingleTimer();
private TestSingleTimer()
{
}
}
private sealed class TestSingleTimerResubmit
{
public static readonly TestSingleTimerResubmit Instance = new TestSingleTimerResubmit();
private TestSingleTimerResubmit()
{
}
}
private sealed class TestCancelTimer
{
public static readonly TestCancelTimer Instance = new TestCancelTimer();
private TestCancelTimer()
{
}
}
private sealed class TestCancelTimerAck
{
public static readonly TestCancelTimerAck Instance = new TestCancelTimerAck();
private TestCancelTimerAck()
{
}
}
private sealed class TestRepeatedTimer
{
public static readonly TestRepeatedTimer Instance = new TestRepeatedTimer();
private TestRepeatedTimer()
{
}
}
private sealed class Tick
{
public int N { get; }
public Tick(int n)
{
N = n;
}
public override bool Equals(object obj)
{
var t = obj as Tick;
return t != null && Equals(t);
}
private bool Equals(Tick other) => N == other.N;
public override int GetHashCode() => N;
}
private sealed class SideChannel
{
public volatile Action<object> AsyncCallback;
public volatile TaskCompletionSource<int> StopPromise;
public bool IsReady => AsyncCallback != null;
public void Tell(object message) => AsyncCallback(message);
public void StopStage() => StopPromise.TrySetResult(-1);
}
private sealed class TestStage : SimpleLinearGraphStage<int>
{
private sealed class Logic : TimerGraphStageLogic
{
private const string TestSingleTimerKey = "TestSingleTimer";
private const string TestSingleTimerResubmitKey = "TestSingleTimerResubmit";
private const string TestCancelTimerKey = "TestCancelTimer";
private const string TestRepeatedTimerKey = "TestRepeatedTimer";
private readonly TestStage _stage;
private int _tickCount = 1;
public Logic(TestStage stage) : base(stage.Shape)
{
_stage = stage;
SetHandler(stage.Inlet, onPush: () => Push(stage.Outlet, Grab(stage.Inlet)));
SetHandler(stage.Outlet, onPull: () => Pull(stage.Inlet));
}
public override void PreStart()
=> _stage._sideChannel.AsyncCallback = GetAsyncCallback<object>(OnTestEvent);
private void OnTestEvent(object message)
{
message.Match()
.With<TestSingleTimer>(() => ScheduleOnce(TestSingleTimerKey, Dilated(500)))
.With<TestSingleTimerResubmit>(() => ScheduleOnce(TestSingleTimerResubmitKey, Dilated(500)))
.With<TestCancelTimer>(() =>
{
ScheduleOnce(TestCancelTimerKey, Dilated(1));
// Likely in mailbox but we cannot guarantee
CancelTimer(TestCancelTimerKey);
_stage._probe.Tell(TestCancelTimerAck.Instance);
ScheduleOnce(TestCancelTimerKey, Dilated(500));
})
.With<TestRepeatedTimer>(() => ScheduleRepeatedly(TestRepeatedTimerKey, Dilated(100)));
}
private TimeSpan Dilated(int milliseconds)
=> _stage._testKit.Dilated(TimeSpan.FromMilliseconds(milliseconds));
protected internal override void OnTimer(object timerKey)
{
var tick = new Tick(_tickCount++);
_stage._probe.Tell(tick);
if (timerKey.Equals(TestSingleTimerResubmitKey) && tick.N == 1)
ScheduleOnce(TestSingleTimerResubmitKey, Dilated(500));
else if (timerKey.Equals(TestRepeatedTimerKey) && tick.N == 5)
CancelTimer(TestRepeatedTimerKey);
}
}
private readonly IActorRef _probe;
private readonly SideChannel _sideChannel;
private readonly TestKitBase _testKit;
public TestStage(IActorRef probe, SideChannel sideChannel, TestKitBase testKit)
{
_probe = probe;
_sideChannel = sideChannel;
_testKit = testKit;
}
protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this);
}
private sealed class TestStage2 : SimpleLinearGraphStage<int>
{
private sealed class Logic : TimerGraphStageLogic
{
private const string TimerKey = "tick";
private readonly TestStage2 _stage;
private int _tickCount;
public Logic(TestStage2 stage) : base(stage.Shape)
{
_stage = stage;
SetHandler(stage.Inlet, onPush: DoNothing,
onUpstreamFinish: CompleteStage,
onUpstreamFailure: FailStage);
SetHandler(stage.Outlet, onPull: DoNothing, onDownstreamFinish: CompleteStage);
}
public override void PreStart() => ScheduleRepeatedly(TimerKey, TimeSpan.FromMilliseconds(100));
protected internal override void OnTimer(object timerKey)
{
_tickCount++;
if(IsAvailable(_stage.Outlet))
Push(_stage.Outlet, _tickCount);
if(_tickCount == 3)
CancelTimer(TimerKey);
}
}
protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this);
}
private sealed class ThrowStage : SimpleLinearGraphStage<int>
{
private sealed class Logic : TimerGraphStageLogic
{
private readonly ThrowStage _stage;
public Logic(ThrowStage stage) : base(stage.Shape)
{
_stage = stage;
SetHandler(stage.Outlet, onPull: () => Pull(stage.Inlet));
SetHandler(stage.Inlet, onPush: DoNothing);
}
public override void PreStart() => ScheduleOnce("tick", TimeSpan.FromMilliseconds(100));
protected internal override void OnTimer(object timerKey)
{
throw _stage._exception;
}
}
private readonly Exception _exception;
public ThrowStage(Exception exception)
{
_exception = exception;
}
protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this);
}
#endregion
}
}
| |
namespace Northwind.Web.App.Tests
{
using System.Linq;
using Northwind.Web.App.Api;
using Northwind.Web.App.Models;
using NRepository.Core;
using NRepository.TestKit;
using NUnit.Framework;
using Northwind.Domain.Core.Entities;
using NRepository.Core.Query;
[TestFixture]
public class OrdersControllerTests
{
[Test]
public void GetVeryImportantCustomersShouldReturnCorrectData()
{
// Arrange
var events = new RecordedRepositoryEvents();
var repository = new InMemoryRepository(events);
var customerSales = Enumerable.Repeat(EntityGenerator.Create<AggregateCustomerSales>(), 20).ToList();
customerSales.ForEach(repository.Add);
// Act
var ordersController = new OrdersController(repository);
var results = ordersController.GetVeryImportantCustomers().Result;
// Assert
results.Count().ShouldEqual(10);
var allStrategies = events.QueryEvents.Single().GetQueryStrategies();
// check the strategies used in this call
allStrategies.Count().ShouldEqual(2);
allStrategies.First().GetType().ShouldEqual(typeof(DefaultSpecificationQueryStrategy<AggregateCustomerSales>));
allStrategies.Second().GetType().ShouldEqual(typeof(FindVeryImportantCustomersQueryStrategy));
}
[Test]
public void GetAllCustomersShouldReturnAllDataWhenDefaultValuesUsed()
{
// Arrange
var interceptors = new DefaultRepositoryInterceptors(new NorthwindQueryRepositoryInterceptor());
var repository = new InMemoryRepository(interceptors);
for (int i = 0; i < 15; i++)
{
repository.Add(EntityGenerator.Create<Customer>(
p => p.CompanyName = p.CompanyName + i,
p => p.CustomerID = i.ToString(),
p => p.Orders.First().OrderDetails.First().Quantity = (short)i,
p => p.Orders.First().OrderDetails.First().UnitPrice = 100.0M));
}
// Act
var ordersController = new OrdersController(repository);
var results = ordersController.GetAllCustomers().Result;
// Assert
results.Count().ShouldEqual(15);
for (int i = 0; i < 15; i++)
{
results.ElementAt(i).CustomerId.ShouldEqual(i.ToString());
results.ElementAt(i).CompanyName.ShouldEqual("CompanyName" + i);
results.ElementAt(i).CombinedOrderValue.ShouldEqual(100 * i);
}
}
[Test]
public void GetAllCustomersShouldReturnCorrectDataWhenTakeAndSkipSupplied()
{
// Arrange
var interceptors = new DefaultRepositoryInterceptors(new NorthwindQueryRepositoryInterceptor());
var repository = new InMemoryRepository(interceptors);
for (int i = 0; i < 15; i++)
{
repository.Add(EntityGenerator.Create<Customer>(
p => p.CompanyName = p.CompanyName + i,
p => p.CustomerID = i.ToString(),
p => p.Orders.First().OrderDetails.First().Quantity = (short)i,
p => p.Orders.First().OrderDetails.First().UnitPrice = 100.0M));
}
// Act
var ordersController = new OrdersController(repository);
var results = ordersController.GetAllCustomers(take: 2, skip: 2).Result;
// Assert
results.Count().ShouldEqual(2);
results.First().CustomerId.ShouldEqual("2");
results.Second().CustomerId.ShouldEqual("3");
}
[Test]
public void GetAllCustomersShouldReturnCorrectDataWhenOrderedByDesc()
{
// Arrange
var interceptors = new DefaultRepositoryInterceptors(new NorthwindQueryRepositoryInterceptor());
var repository = new InMemoryRepository(interceptors);
for (int i = 0; i < 15; i++)
{
repository.Add(EntityGenerator.Create<Customer>(
p => p.CompanyName = p.CompanyName + i,
p => p.CustomerID = i.ToString(),
p => p.Orders.First().OrderDetails.First().Quantity = (short)i,
p => p.Orders.First().OrderDetails.First().UnitPrice = 100.0M));
}
// Act
var ordersController = new OrdersController(repository);
var results = ordersController.GetAllCustomers(take: 1, skip: 0, ascending: false).Result;
// Assert
results.Single().CustomerId.ShouldEqual("14");
}
[Test]
public void GetAllCustomersShouldReturnCorrectDataWhenMinOrderSupplied()
{
// Arrange
var interceptors = new DefaultRepositoryInterceptors(new NorthwindQueryRepositoryInterceptor());
var repository = new InMemoryRepository(interceptors);
for (int i = 0; i < 15; i++)
{
repository.Add(EntityGenerator.Create<Customer>(
p => p.CompanyName = p.CompanyName + i,
p => p.CustomerID = i.ToString(),
p => p.Orders.First().OrderDetails.First().Quantity = (short)i,
p => p.Orders.First().OrderDetails.First().UnitPrice = 100.0M));
}
// Act
var ordersController = new OrdersController(repository);
// Assert
var results = ordersController.GetAllCustomers(minOrderValue: 100 * 10).Result;
results.Count().ShouldEqual(5);
}
[Test]
public void GetCustomerOrderHistoryShouldReturnCorrectData()
{
// Arrange
var events = new RecordedRepositoryEvents();
var repository = new InMemoryRepository(events);
// Act
var ordersController = new OrdersController(repository);
var result = ordersController.GetCustomerOrderHistory("NotUsed").Result;
result.Count().ShouldEqual(TestsEntityFrameworkRepositoryExtensions.CustomerOrderHistories.Count());
var allStrategies = events.QueryEvents.Single().GetQueryStrategies();
allStrategies.Count().ShouldEqual(3);
allStrategies.First().GetType().ShouldEqual(typeof(DefaultSpecificationQueryStrategy<CustomerOrderHistory>));
allStrategies.Second().GetType().ShouldEqual(typeof(CustomerOrderHistoryStoredProcQueryStrategy));
allStrategies.Third().GetType().ShouldEqual(typeof(ConditionalQueryStrategy));
}
[Test]
public void GetCustomerOrderHistoryShouldReturnCorrectDataWhenFilteredByProductName()
{
// Arrange
var repository = new InMemoryRepository();
// Act
var ordersController = new OrdersController(repository);
var result = ordersController.GetCustomerOrderHistory("NotUsed", "2").Result;
// Assert
result.Count().ShouldEqual(1);
result.First().ProductName.ShouldEqual("ProductName2");
}
// Awaiting new version NRepository.Core 2.5 (properties public on ConditionalQueryStrategy)
[TestCase(1, 2, "CompanyName", true, null)]
public void GetAllCustomersQueryShouldUseCorrectStrategies(int take, int skip, string orderBy, bool ascending, decimal? minOrderValue)
{
// Arrange
var events = new RecordedRepositoryEvents();
var repository = new InMemoryRepository(events);
// Act
var notUsed = new OrdersController(repository).GetAllCustomers(take, skip, orderBy, ascending, minOrderValue).Result;
// Assert
var allStrategies = events.QueryEvents.Single().GetQueryStrategies();
allStrategies.Count().ShouldEqual(4);
allStrategies.First().GetType().ShouldEqual(typeof(DefaultSpecificationQueryStrategy<AggregateCustomerSales>));
allStrategies.Second().GetType().ShouldEqual(typeof(ConditionalQueryStrategy));
allStrategies.Third().GetType().ShouldEqual(typeof(ConditionalQueryStrategy));
allStrategies.Fourth().GetType().ShouldEqual(typeof(ConditionalQueryStrategy));
}
}
}
| |
private const bool echoLog = true;
public void Main(string argument)
{
Command command = new Command();
if(string.IsNullOrWhiteSpace(argument))
{
if(echoLog)
{
Echo("Empty Argument");
}
}
else if(!Command.TryParse(argument, ref command))
{
if(echoLog)
{
Echo("Failed Parse:");
Echo(argument);
}
}
else
{
try
{
var result = Process(command);
if(echoLog)
{
Echo(result ? "Success" : "Failure");
}
}
catch(CommandException ex)
{
Echo(ex.Message);
}
catch(Exception ex)
{
// If this block is ever reached
// Notify the developer
throw ex;
}
}
}
delegate bool GroupFunction(IMyBlockGroup group);
delegate bool BlockFunction(IMyTerminalBlock block);
static readonly Dictionary<string, BlockFunction> blockFunctions = new Dictionary<string, BlockFunction>()
{
// Door Commands
{ MakeIndex("Door", "Open"), MakeBlockFunction((IMyDoor d) => d.OpenDoor()) },
{ MakeIndex("Door", "Close"), MakeBlockFunction((IMyDoor d) => d.CloseDoor()) },
{ MakeIndex("Door", "Toggle"), MakeBlockFunction((IMyDoor d) => d.ToggleDoor()) },
// Piston Commands
{ MakeIndex("Piston", "Extend"), MakeBlockFunction((IMyPistonBase p) => p.Extend()) },
{ MakeIndex("Piston", "Retract"), MakeBlockFunction((IMyPistonBase p) => p.Retract()) },
{ MakeIndex("Piston", "Reverse"), MakeBlockFunction((IMyPistonBase p) => p.Reverse()) },
// Functional Commands
{ MakeIndex("Functional", "Enable"), MakeBlockFunction((IMyFunctionalBlock f) => f.Enabled = true) },
{ MakeIndex("Functional", "Disable"), MakeBlockFunction((IMyFunctionalBlock f) => f.Enabled = false) },
// Remote Control Commands
{ MakeIndex("RemoteControl", "EnableAutoPilot"), MakeBlockFunction((IMyRemoteControl r) => r.SetAutoPilotEnabled(true)) },
{ MakeIndex("RemoteControl", "DisableAutoPilot"), MakeBlockFunction((IMyRemoteControl r) => r.SetAutoPilotEnabled(false)) },
// Antenna Commands
{ MakeIndex("Antenna", "EnableAlliedBroadcast"), MakeBlockFunction<IMyRadioAntenna>(a => a.IgnoreAlliedBroadcast = false) },
{ MakeIndex("Antenna", "DisableAlliedBroadcast"), MakeBlockFunction<IMyRadioAntenna>(a => a.IgnoreAlliedBroadcast = true) },
{ MakeIndex("Antenna", "EnableOtherBroadcast"), MakeBlockFunction<IMyRadioAntenna>(a => a.IgnoreOtherBroadcast = false) },
{ MakeIndex("Antenna", "DisableOtherBroadcast"), MakeBlockFunction<IMyRadioAntenna>(a => a.IgnoreOtherBroadcast = true) },
// Connector Commands
{ MakeIndex("Connector", "EnableThrowOut"), MakeBlockFunction<IMyShipConnector>(c => c.ThrowOut = true) },
{ MakeIndex("Connector", "DisableThrowOut"), MakeBlockFunction<IMyShipConnector>(c => c.ThrowOut = false) },
{ MakeIndex("Connector", "EnableCollectAll"), MakeBlockFunction<IMyShipConnector>(c => c.CollectAll = true) },
{ MakeIndex("Connector", "DisableCollectAll"), MakeBlockFunction<IMyShipConnector>(c => c.CollectAll = false) },
{ MakeIndex("Connector", "Connect"), MakeBlockFunction<IMyShipConnector>(c => c.Connect()) },
{ MakeIndex("Connector", "Disconnect"), MakeBlockFunction<IMyShipConnector>(c => c.Disconnect()) },
{ MakeIndex("Connector", "ToggleConnect"), MakeBlockFunction<IMyShipConnector>(c => c.ToggleConnect()) },
};
static readonly List<IMyDoor> doors = new List<IMyDoor>();
static readonly List<IMyPistonBase> pistons = new List<IMyPistonBase>();
static readonly List<IMyFunctionalBlock> functionalBlocks = new List<IMyFunctionalBlock>();
static readonly List<IMyRemoteControl> remoteControls = new List<IMyRemoteControl>();
static readonly List<IMyRadioAntenna> antennas = new List<IMyRadioAntenna>();
static readonly List<IMyShipConnector> connectors = new List<IMyShipConnector>();
static readonly Dictionary<string, GroupFunction> groupFunctions = new Dictionary<string, GroupFunction>()
{
// Door Commands
{ MakeIndex("Door", "Open"), MakeGroupFunction(doors, d => d.OpenDoor()) },
{ MakeIndex("Door", "Close"), MakeGroupFunction(doors, d => d.CloseDoor()) },
{ MakeIndex("Door", "Toggle"), MakeGroupFunction(doors, d => d.ToggleDoor()) },
// Piston Commands
{ MakeIndex("Piston", "Extend"), MakeGroupFunction(pistons, p => p.Extend()) },
{ MakeIndex("Piston", "Retract"), MakeGroupFunction(pistons, p => p.Retract()) },
{ MakeIndex("Piston", "Reverse"), MakeGroupFunction(pistons, p => p.Reverse()) },
// Functional Commands
{ MakeIndex("Functional", "Enable"), MakeGroupFunction(functionalBlocks, f => f.Enabled = true) },
{ MakeIndex("Functional", "Disable"), MakeGroupFunction(functionalBlocks, f => f.Enabled = false) },
// Remote Control Commands
{ MakeIndex("RemoteControl", "EnableAutoPilot"), MakeGroupFunction(remoteControls, r => r.SetAutoPilotEnabled(true)) },
{ MakeIndex("RemoteControl", "DisableAutoPilot"), MakeGroupFunction(remoteControls, r => r.SetAutoPilotEnabled(false)) },
// Antenna Commands
{ MakeIndex("Antenna", "EnableAlliedBroadcast"), MakeGroupFunction(antennas, a => a.IgnoreAlliedBroadcast = false) },
{ MakeIndex("Antenna", "DisableAlliedBroadcast"), MakeGroupFunction(antennas, a => a.IgnoreAlliedBroadcast = true) },
{ MakeIndex("Antenna", "EnableOtherBroadcast"), MakeGroupFunction(antennas, a => a.IgnoreOtherBroadcast = false) },
{ MakeIndex("Antenna", "DisableOtherBroadcast"), MakeGroupFunction(antennas, a => a.IgnoreOtherBroadcast = true) },
// Connector Commands
{ MakeIndex("Connector", "EnableThrowOut"), MakeGroupFunction(connectors, c => c.ThrowOut = true) },
{ MakeIndex("Connector", "DisableThrowOut"), MakeGroupFunction(connectors, c => c.ThrowOut = false) },
{ MakeIndex("Connector", "EnableCollectAll"), MakeGroupFunction(connectors, c => c.CollectAll = true) },
{ MakeIndex("Connector", "DisableCollectAll"), MakeGroupFunction(connectors, c => c.CollectAll = false) },
{ MakeIndex("Connector", "Connect"), MakeGroupFunction(connectors, c => c.Connect()) },
{ MakeIndex("Connector", "Disconnect"), MakeGroupFunction(connectors, c => c.Disconnect()) },
{ MakeIndex("Connector", "ToggleConnect"), MakeGroupFunction(connectors, c => c.ToggleConnect()) },
};
static string MakeIndex(string typeName, string actionName)
{
return string.Concat(typeName.ToLower(), "_", actionName.ToLower());
}
bool Process(Command command)
{
switch(command.Qualifier)
{
case Qualifier.Block:
return ProcessBlock(command.Name, command.Type, command.Action);
case Qualifier.Group:
return ProcessGroup(command.Name, command.Type, command.Action);
default:
return false;
}
}
bool ProcessBlock(string name, string type, string action)
{
var block = GridTerminalSystem.GetBlockWithName(name);
if(block == null)
throw new CommandException("Block not found:" + name);
BlockFunction function;
var index = MakeIndex(type, action);
if(blockFunctions.TryGetValue(index, out function))
return function(block);
throw new CommandException("Could not find action \"" + action + "\" for block type " + type);
}
bool ProcessGroup(string name, string type, string action)
{
var group = GridTerminalSystem.GetBlockGroupWithName(name);
if(group == null)
throw new CommandException("Group not found:" + name);
GroupFunction function;
var index = MakeIndex(type, action);
if(groupFunctions.TryGetValue(index, out function))
{
return function(group);
}
throw new CommandException("Could not find action \"" + action + "\" for block type " + type);
}
static BlockFunction MakeBlockFunction<T>(Action<T> action)
{
return (IMyTerminalBlock block) =>
{
if(!(block is T))
return false;
action((T)block);
return true;
};
}
static GroupFunction MakeGroupFunction<T>(List<T> list, Action<T> action) where T : class
{
return (IMyBlockGroup group) =>
{
list.Clear();
group.GetBlocksOfType<T>(list);
if(list.Count == 0)
return false;
foreach(var item in list)
action(item);
list.Clear();
return true;
};
}
public class CommandException : Exception
{
public CommandException(string message) : base(message) {}
}
public enum Qualifier
{
Block,
Group,
}
public struct Command
{
private string name;
private string type;
private string action;
private Qualifier qualifier;
public string Name { get { return this.name; } }
public string Type { get { return this.type; } }
public string Action { get { return this.action; } }
public Qualifier Qualifier { get { return this.qualifier; } }
public override string ToString()
{
return string.Format("{0} {1} {2} \"{3}\"", Action, Type, Qualifier, Name);
}
public static bool TryParse(string input, ref Command command)
{
Command result = new Command();
Parser parser = new Parser(input);
// Read Action
result.action = parser.ReadIdentifier();
if(result.action == null)
return false;
parser.ConsumeWhitespace();
// Read Type
result.type = parser.ReadIdentifier();
if(result.type == null)
return false;
parser.ConsumeWhitespace();
// Read Qualifier
var qualifier = parser.ReadIdentifier();
if(qualifier == null)
return false;
if(!Enum.TryParse(qualifier, true, out result.qualifier))
return false;
parser.ConsumeWhitespace();
// Read Name
result.name = parser.ReadStringOrIdentifier();
if(result.name == null)
return false;
parser.ConsumeWhitespace();
command = result;
return true;
}
}
public class StringReader
{
private readonly string source;
private int index;
public StringReader(string source)
{
if(source == null)
throw new ArgumentNullException("source");
this.source = source;
}
public int Peek()
{
return
(this.index >= 0 && this.index < this.source.Length) ?
(int)this.source[index] :
-1;
}
public char Read()
{
if(this.index < 0 || this.index >= this.source.Length)
throw new InvalidOperationException("Attempt to read past end of string");
char result = this.source[index];
++this.index;
return result;
}
public int Read(char[] buffer, int index, int count)
{
int bytesRead = 0;
for(int j = index; j < (index + count) && this.index < this.source.Length; ++j)
{
char c = this.source[this.index];
buffer[j] = c;
++this.index;
++bytesRead;
}
return bytesRead;
}
public string ReadLine()
{
int end = -1;
int start = this.index;
while(this.index < this.source.Length)
{
char c = this.source[this.index];
if(c == '\r')
{
end = this.index;
++this.index;
c = this.source[this.index];
if(c == '\n')
++this.index;
return this.source.Substring(start, end - start);
}
else if(c == '\n')
{
end = this.index;
++this.index;
return this.source.Substring(start, end - start);
}
}
return null;
}
public string ReadToEnd()
{
return (this.index > 0) ? this.source.Substring(index) : this.source;
}
}
public class Parser
{
readonly StringReader reader;
readonly StringBuilder builder = new StringBuilder();
readonly Dictionary<char, char> escapeChars = new Dictionary<char, char>()
{
{ '"', '"' }
};
public Parser(string source)
{
if(source == null)
throw new ArgumentNullException("source");
this.reader = new StringReader(source);
}
public Parser(string source, Dictionary<char, char> escapeChars)
{
if(source == null)
throw new ArgumentNullException("source");
this.reader = new StringReader(source);
this.escapeChars = new Dictionary<char, char>(escapeChars);
}
public string ReadIdentifier()
{
builder.Clear();
for(int i = reader.Peek(); i != -1; i = reader.Peek())
{
char c = (char)i;
if(!char.IsLetter(c))
break;
builder.Append(c);
reader.Read();
}
return builder.ToString();
}
public string ReadString()
{
builder.Clear();
bool escapeMode = false;
if(reader.Peek() != '"')
return null;
reader.Read();
for(int i = reader.Peek(); i != -1; i = reader.Peek())
{
char c = (char)i;
if(escapeMode)
{
char escapeChar = '\0';
if(!escapeChars.TryGetValue(c, out escapeChar))
return null;
c = escapeChar;
escapeMode = false;
}
else
{
if(c == '\\')
{
escapeMode = true;
reader.Read();
continue;
}
else if(c == '"')
return builder.ToString();
else if(reader.Peek() == -1)
return null;
}
builder.Append(c);
reader.Read();
}
return builder.ToString();
}
public string ReadStringOrIdentifier()
{
builder.Clear();
bool quoteMode = false;
bool escapeMode = false;
for(int i = reader.Peek(); i != -1; i = reader.Peek())
{
char c = (char)i;
if(escapeMode)
{
char escapeChar = '\0';
if(!escapeChars.TryGetValue(c, out escapeChar))
return null;
c = escapeChar;
escapeMode = false;
}
else if(quoteMode)
{
if(c == '\\')
{
escapeMode = true;
reader.Read();
continue;
}
else if(c == '"')
break;
else if(reader.Peek() == -1)
return null;
}
else
{
if(c == '"')
{
quoteMode = true;
reader.Read();
continue;
}
else if(!char.IsLetter(c))
break;
}
builder.Append(c);
reader.Read();
}
return builder.ToString();
}
public void ConsumeWhitespace()
{
for(int i = reader.Peek(); i != -1; i = reader.Peek())
{
char c = (char)i;
if(!char.IsWhiteSpace(c))
return;
reader.Read();
}
}
public void ReadWhitespace()
{
for(int i = reader.Peek(); i != -1; i = reader.Peek())
{
char c = (char)i;
if(!char.IsWhiteSpace(c))
return;
builder.Append(c);
reader.Read();
}
}
}
| |
// ********************************************************************************************************
// Product Name: MapWindow.dll Alpha
// Description: The basic module for MapWindow version 6.0
// ********************************************************************************************************
// The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License");
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
// http://www.mozilla.org/MPL/
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOlhsT WARRANTY OF
// ANY KIND, either expressed or implied. See the License for the specific language governing rights and
// limitations under the License.
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 4/3/2008 3:29:47 PM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using GeoAPI.Geometries;
namespace DotSpatial.NTSExtension
{
/// <summary>
/// A float based 3 dimensional vector class, implementing all interesting features of vectors.
/// </summary>
public struct FloatVector3
{
#region Fields
/// <summary>
/// X
/// </summary>
public float X;
/// <summary>
/// Y
/// </summary>
public float Y;
/// <summary>
/// Z
/// </summary>
public float Z;
#endregion
#region Constructors
/// <summary>
/// Copies the X, Y and Z values from the CoordinateF without doing a conversion.
/// </summary>
/// <param name="coord">X, Y Z</param>
public FloatVector3(CoordinateF coord)
{
X = coord.X;
Y = coord.Y;
Z = coord.Z;
}
/// <summary>
/// Creates a new FloatVector3 with the specified values
/// </summary>
/// <param name="xValue">X</param>
/// <param name="yValue">Y</param>
/// <param name="zValue">Z</param>
public FloatVector3(float xValue, float yValue, float zValue)
{
X = xValue;
Y = yValue;
Z = zValue;
}
/// <summary>
/// Uses the X, Y and Z values from the coordinate to create a new FloatVector3
/// </summary>
/// <param name="coord">The coordinate to obtain X, Y and Z values from</param>
public FloatVector3(Coordinate coord)
{
X = Convert.ToSingle(coord.X);
Y = Convert.ToSingle(coord.Y);
Z = Convert.ToSingle(coord.Z);
}
#endregion
#region Properties
/// <summary>
/// Gets the length of the vector
/// </summary>
public float Length
{
get { return Convert.ToSingle(Math.Sqrt(X * X + Y * Y + Z * Z)); }
}
/// <summary>
/// Gets the square of length of this vector
/// </summary>
public float LengthSq
{
get { return Convert.ToSingle(X * X + Y * Y + Z * Z); }
}
#endregion
#region Operators
/// <summary>
/// Adds the vectors lhs and V using vector addition, which adds the corresponding components
/// </summary>
/// <param name="lhs">One vector to be added</param>
/// <param name="rhs">A second vector to be added</param>
/// <returns>The sum of the vectors</returns>
public static FloatVector3 operator +(FloatVector3 lhs, FloatVector3 rhs)
{
FloatVector3 result;
result.X = lhs.X + rhs.X;
result.Y = lhs.Y + rhs.Y;
result.Z = lhs.Z + rhs.Z;
return result;
}
/// <summary>
/// Divides the components of vector lhs by the respective components
/// ov vector V and returns the resulting vector.
/// </summary>
/// <param name="lhs">FloatVector3 Dividend (Numbers to be divided)</param>
/// <param name="rhs">FloatVector3 Divisor (Numbers to divide by)</param>
/// <returns>A FloatVector3 quotient of lhs and V</returns>
/// <remarks>To prevent divide by 0, if a 0 is in V, it will return 0 in the result</remarks>
public static FloatVector3 operator /(FloatVector3 lhs, FloatVector3 rhs)
{
FloatVector3 result = new FloatVector3();
if (rhs.X > 0) result.X = lhs.X / rhs.X;
if (rhs.Y > 0) result.Y = lhs.Y / rhs.Y;
if (rhs.Z > 0) result.Z = lhs.Z / rhs.Z;
return result;
}
/// <summary>
/// Multiplies each component of vector lhs by the Scalar value
/// </summary>
/// <param name="lhs">A vector representing the vector to be multiplied</param>
/// <param name="scalar">Double, the scalar value to mulitiply the vector components by</param>
/// <returns>A FloatVector3 representing the vector product of vector lhs and the Scalar</returns>
public static FloatVector3 operator /(FloatVector3 lhs, float scalar)
{
FloatVector3 result;
if (scalar == 0) throw new ArgumentException("Divisor cannot be 0.");
result.X = lhs.X / scalar;
result.Y = lhs.Y / scalar;
result.Z = lhs.Z / scalar;
return result;
}
/// <summary>
/// Tests two float vectors for equality.
/// </summary>
/// <param name="lhs">The left hand side FloatVector3 to test.</param>
/// <param name="rhs">The right hand side FloatVector3 to test.</param>
/// <returns>Returns true if X, Y and Z are all equal.</returns>
public static bool operator ==(FloatVector3 lhs, FloatVector3 rhs)
{
if (lhs.X == rhs.X && lhs.Y == rhs.Y && lhs.Z == rhs.Z) return true;
return false;
}
/// <summary>
/// Returns the Cross Product of two vectors lhs and rhs
/// </summary>
/// <param name="lhs">Vector, the first input vector</param>
/// <param name="rhs">Vector, the second input vector</param>
/// <returns>A FloatVector3 containing the cross product of lhs and V</returns>
public static FloatVector3 operator ^(FloatVector3 lhs, FloatVector3 rhs)
{
FloatVector3 result = new FloatVector3();
result.X = (lhs.Y * rhs.Z - lhs.Z * rhs.Y);
result.Y = (lhs.Z * rhs.X - lhs.X * rhs.Z);
result.Z = (lhs.X * rhs.Y - lhs.Y * rhs.X);
return result;
}
/// <summary>
/// Tests two float vectors for inequality.
/// </summary>
/// <param name="lhs">The left hand side FloatVector3 to test.</param>
/// <param name="rhs">The right hand side FloatVector3 to test.</param>
/// <returns>Returns true if any of X, Y and Z are unequal.</returns>
public static bool operator !=(FloatVector3 lhs, FloatVector3 rhs)
{
if (lhs.X == rhs.X && lhs.Y == rhs.Y && lhs.Z == rhs.Z) return false;
return true;
}
/// <summary>
/// Returns the Inner Product also known as the dot product of two vectors, lhs and V
/// </summary>
/// <param name="lhs">The input vector</param>
/// <param name="rhs">The vector to take the inner product against lhs</param>
/// <returns>a Double containing the dot product of lhs and V</returns>
public static float operator *(FloatVector3 lhs, FloatVector3 rhs)
{
return (lhs.X * rhs.X) + (lhs.Y * rhs.Y) + (lhs.Z * rhs.Z);
}
/// <summary>
/// Multiplies the vectors lhs and V using vector multiplication,
/// which adds the corresponding components
/// </summary>
/// <param name="scalar">A scalar to multpy to the vector</param>
/// <param name="rhs">A vector to be multiplied</param>
/// <returns>The scalar product for the vectors</returns>
public static FloatVector3 operator *(float scalar, FloatVector3 rhs)
{
FloatVector3 result;
result.X = scalar * rhs.X;
result.Y = scalar * rhs.Y;
result.Z = scalar * rhs.Z;
return result;
}
/// <summary>
/// Multiplies each component of vector lhs by the Scalar value
/// </summary>
/// <param name="lhs">A vector representing the vector to be multiplied</param>
/// <param name="scalar">Double, the scalar value to mulitiply the vector components by</param>
/// <returns>A FloatVector3 representing the vector product of vector lhs and the Scalar</returns>
public static FloatVector3 operator *(FloatVector3 lhs, float scalar)
{
FloatVector3 result;
result.X = lhs.X * scalar;
result.Y = lhs.Y * scalar;
result.Z = lhs.Z * scalar;
return result;
}
/// <summary>
/// Subtracts FloatVector3 V from FloatVector3 lhs
/// </summary>
/// <param name="lhs">A FloatVector3 to subtract from</param>
/// <param name="rhs">A FloatVector3 to subtract</param>
/// <returns>The FloatVector3 difference lhs - V</returns>
public static FloatVector3 operator -(FloatVector3 lhs, FloatVector3 rhs)
{
FloatVector3 result;
result.X = lhs.X - rhs.X;
result.Y = lhs.Y - rhs.Y;
result.Z = lhs.Z - rhs.Z;
return result;
}
#endregion
#region Methods
/// <summary>
/// Adds all the scalar members of the the two vectors
/// </summary>
/// <param name="lhs">Left hand side</param>
/// <param name="rhs">Right hand side</param>
/// <returns></returns>
public static FloatVector3 Add(FloatVector3 lhs, FloatVector3 rhs)
{
return new FloatVector3(lhs.X + rhs.X, lhs.Y + rhs.Y, lhs.Z + rhs.Z);
}
/// <summary>
/// Adds the specified v
/// </summary>
/// <param name="vector">A FloatVector3 to add to this vector</param>
public void Add(FloatVector3 vector)
{
X += vector.X;
Y += vector.Y;
Z += vector.Z;
}
/// <summary>
/// Returns the Cross Product of two vectors lhs and V
/// </summary>
/// <param name="lhs">Vector, the first input vector</param>
/// <param name="rhs">Vector, the second input vector</param>
/// <returns>A FloatVector3 containing the cross product of lhs and V</returns>
public static FloatVector3 CrossProduct(FloatVector3 lhs, FloatVector3 rhs)
{
FloatVector3 result = new FloatVector3();
result.X = (lhs.Y * rhs.Z - lhs.Z * rhs.Y);
result.Y = (lhs.Z * rhs.X - lhs.X * rhs.Z);
result.Z = (lhs.X * rhs.Y - lhs.Y * rhs.X);
return result;
}
/// <summary>
/// Multiplies all the scalar members of the the two vectors
/// </summary>
/// <param name="lhs">Left hand side</param>
/// <param name="rhs">Right hand side</param>
/// <returns></returns>
public static float Dot(FloatVector3 lhs, FloatVector3 rhs)
{
return lhs.X * rhs.X + lhs.Y * rhs.Y + lhs.Z * rhs.Z;
}
/// <summary>
/// tests to see if the specified object has the same X, Y and Z values
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public override bool Equals(object obj)
{
if (obj is FloatVector3)
{
FloatVector3 fv = (FloatVector3)obj;
if (fv.X == X && fv.Y == Y && fv.Z == Z) return true;
}
return false;
}
/// <summary>
/// Not sure what I should be doing here since Int can't really contain this much info very well
/// </summary>
/// <returns></returns>
public override int GetHashCode()
{
return base.GetHashCode();
}
/// <summary>
/// Multiplies the source vector by a scalar.
/// </summary>
/// <param name="source"></param>
/// <param name="scalar"></param>
/// <returns></returns>
public static FloatVector3 Multiply(FloatVector3 source, float scalar)
{
return new FloatVector3(source.X * scalar, source.Y * scalar, source.Z * scalar);
}
/// <summary>
/// Multiplies this vector by a scalar value.
/// </summary>
/// <param name="scalar">The scalar to multiply by</param>
public void Multiply(float scalar)
{
X *= scalar;
Y *= scalar;
Z *= scalar;
}
/// <summary>
/// Normalizes the vectors
/// </summary>
public void Normalize()
{
float length = Length;
X = X / length;
Y = Y / length;
Z = Z / length;
}
/// <summary>
/// Subtracts all the scalar members of the the two vectors
/// </summary>
/// <param name="lhs">Left hand side</param>
/// <param name="rhs">Right hand side</param>
/// <returns></returns>
public static FloatVector3 Subtract(FloatVector3 lhs, FloatVector3 rhs)
{
return new FloatVector3(lhs.X - rhs.X, lhs.Y - rhs.Y, lhs.Z - rhs.Z);
}
/// <summary>
/// Subtracts the specified value
/// </summary>
/// <param name="vector">A FloatVector3</param>
public void Subtract(FloatVector3 vector)
{
X -= vector.X;
Y -= vector.Y;
Z -= vector.Z;
}
#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 Json.Net.Serialization;
#if !(PORTABLE40 || NET20 || NET35)
using System;
using System.Linq.Expressions;
using System.Reflection;
namespace Json.Net.Utilities
{
internal class ExpressionReflectionDelegateFactory : ReflectionDelegateFactory
{
private static readonly ExpressionReflectionDelegateFactory _instance = new ExpressionReflectionDelegateFactory();
internal static ReflectionDelegateFactory Instance
{
get { return _instance; }
}
public override ObjectConstructor<object> CreateParametrizedConstructor(MethodBase method)
{
ValidationUtils.ArgumentNotNull(method, "method");
Type type = typeof(object);
ParameterExpression argsParameterExpression = Expression.Parameter(typeof(object[]), "args");
Expression callExpression = BuildMethodCall(method, type, null, argsParameterExpression);
LambdaExpression lambdaExpression = Expression.Lambda(typeof(ObjectConstructor<object>), callExpression, argsParameterExpression);
ObjectConstructor<object> compiled = (ObjectConstructor<object>)lambdaExpression.Compile();
return compiled;
}
public override MethodCall<T, object> CreateMethodCall<T>(MethodBase method)
{
ValidationUtils.ArgumentNotNull(method, "method");
Type type = typeof(object);
ParameterExpression targetParameterExpression = Expression.Parameter(type, "target");
ParameterExpression argsParameterExpression = Expression.Parameter(typeof(object[]), "args");
Expression callExpression = BuildMethodCall(method, type, targetParameterExpression, argsParameterExpression);
LambdaExpression lambdaExpression = Expression.Lambda(typeof(MethodCall<T, object>), callExpression, targetParameterExpression, argsParameterExpression);
MethodCall<T, object> compiled = (MethodCall<T, object>)lambdaExpression.Compile();
return compiled;
}
private Expression BuildMethodCall(MethodBase method, Type type, ParameterExpression targetParameterExpression, ParameterExpression argsParameterExpression)
{
ParameterInfo[] parametersInfo = method.GetParameters();
Expression[] argsExpression = new Expression[parametersInfo.Length];
for (int i = 0; i < parametersInfo.Length; i++)
{
Type parameterType = parametersInfo[i].ParameterType;
Expression indexExpression = Expression.Constant(i);
Expression paramAccessorExpression = Expression.ArrayIndex(argsParameterExpression, indexExpression);
Expression argExpression;
if (parameterType.IsValueType())
{
BinaryExpression ensureValueTypeNotNull = Expression.Coalesce(paramAccessorExpression, Expression.New(parameterType));
argExpression = EnsureCastExpression(ensureValueTypeNotNull, parameterType);
}
else
{
argExpression = EnsureCastExpression(paramAccessorExpression, parameterType);
}
argsExpression[i] = argExpression;
}
Expression callExpression;
if (method.IsConstructor)
{
callExpression = Expression.New((ConstructorInfo) method, argsExpression);
}
else if (method.IsStatic)
{
callExpression = Expression.Call((MethodInfo) method, argsExpression);
}
else
{
Expression readParameter = EnsureCastExpression(targetParameterExpression, method.DeclaringType);
callExpression = Expression.Call(readParameter, (MethodInfo) method, argsExpression);
}
if (method is MethodInfo)
{
MethodInfo m = (MethodInfo) method;
if (m.ReturnType != typeof (void))
callExpression = EnsureCastExpression(callExpression, type);
else
callExpression = Expression.Block(callExpression, Expression.Constant(null));
}
else
{
callExpression = EnsureCastExpression(callExpression, type);
}
return callExpression;
}
public override Func<T> CreateDefaultConstructor<T>(Type type)
{
ValidationUtils.ArgumentNotNull(type, "type");
// avoid error from expressions compiler because of abstract class
if (type.IsAbstract())
return () => (T)Activator.CreateInstance(type);
try
{
Type resultType = typeof(T);
Expression expression = Expression.New(type);
expression = EnsureCastExpression(expression, resultType);
LambdaExpression lambdaExpression = Expression.Lambda(typeof(Func<T>), expression);
Func<T> compiled = (Func<T>)lambdaExpression.Compile();
return compiled;
}
catch
{
// an error can be thrown if constructor is not valid on Win8
// will have INVOCATION_FLAGS_NON_W8P_FX_API invocation flag
return () => (T)Activator.CreateInstance(type);
}
}
public override Func<T, object> CreateGet<T>(PropertyInfo propertyInfo)
{
ValidationUtils.ArgumentNotNull(propertyInfo, "propertyInfo");
Type instanceType = typeof(T);
Type resultType = typeof(object);
ParameterExpression parameterExpression = Expression.Parameter(instanceType, "instance");
Expression resultExpression;
MethodInfo getMethod = propertyInfo.GetGetMethod(true);
if (getMethod.IsStatic)
{
resultExpression = Expression.MakeMemberAccess(null, propertyInfo);
}
else
{
Expression readParameter = EnsureCastExpression(parameterExpression, propertyInfo.DeclaringType);
resultExpression = Expression.MakeMemberAccess(readParameter, propertyInfo);
}
resultExpression = EnsureCastExpression(resultExpression, resultType);
LambdaExpression lambdaExpression = Expression.Lambda(typeof(Func<T, object>), resultExpression, parameterExpression);
Func<T, object> compiled = (Func<T, object>)lambdaExpression.Compile();
return compiled;
}
public override Func<T, object> CreateGet<T>(FieldInfo fieldInfo)
{
ValidationUtils.ArgumentNotNull(fieldInfo, "fieldInfo");
ParameterExpression sourceParameter = Expression.Parameter(typeof(T), "source");
Expression fieldExpression;
if (fieldInfo.IsStatic)
{
fieldExpression = Expression.Field(null, fieldInfo);
}
else
{
Expression sourceExpression = EnsureCastExpression(sourceParameter, fieldInfo.DeclaringType);
fieldExpression = Expression.Field(sourceExpression, fieldInfo);
}
fieldExpression = EnsureCastExpression(fieldExpression, typeof(object));
Func<T, object> compiled = Expression.Lambda<Func<T, object>>(fieldExpression, sourceParameter).Compile();
return compiled;
}
public override Action<T, object> CreateSet<T>(FieldInfo fieldInfo)
{
ValidationUtils.ArgumentNotNull(fieldInfo, "fieldInfo");
// use reflection for structs
// expression doesn't correctly set value
if (fieldInfo.DeclaringType.IsValueType() || fieldInfo.IsInitOnly)
return LateBoundReflectionDelegateFactory.Instance.CreateSet<T>(fieldInfo);
ParameterExpression sourceParameterExpression = Expression.Parameter(typeof(T), "source");
ParameterExpression valueParameterExpression = Expression.Parameter(typeof(object), "value");
Expression fieldExpression;
if (fieldInfo.IsStatic)
{
fieldExpression = Expression.Field(null, fieldInfo);
}
else
{
Expression sourceExpression = EnsureCastExpression(sourceParameterExpression, fieldInfo.DeclaringType);
fieldExpression = Expression.Field(sourceExpression, fieldInfo);
}
Expression valueExpression = EnsureCastExpression(valueParameterExpression, fieldExpression.Type);
BinaryExpression assignExpression = Expression.Assign(fieldExpression, valueExpression);
LambdaExpression lambdaExpression = Expression.Lambda(typeof(Action<T, object>), assignExpression, sourceParameterExpression, valueParameterExpression);
Action<T, object> compiled = (Action<T, object>)lambdaExpression.Compile();
return compiled;
}
public override Action<T, object> CreateSet<T>(PropertyInfo propertyInfo)
{
ValidationUtils.ArgumentNotNull(propertyInfo, "propertyInfo");
// use reflection for structs
// expression doesn't correctly set value
if (propertyInfo.DeclaringType.IsValueType())
return LateBoundReflectionDelegateFactory.Instance.CreateSet<T>(propertyInfo);
Type instanceType = typeof(T);
Type valueType = typeof(object);
ParameterExpression instanceParameter = Expression.Parameter(instanceType, "instance");
ParameterExpression valueParameter = Expression.Parameter(valueType, "value");
Expression readValueParameter = EnsureCastExpression(valueParameter, propertyInfo.PropertyType);
MethodInfo setMethod = propertyInfo.GetSetMethod(true);
Expression setExpression;
if (setMethod.IsStatic)
{
setExpression = Expression.Call(setMethod, readValueParameter);
}
else
{
Expression readInstanceParameter = EnsureCastExpression(instanceParameter, propertyInfo.DeclaringType);
setExpression = Expression.Call(readInstanceParameter, setMethod, readValueParameter);
}
LambdaExpression lambdaExpression = Expression.Lambda(typeof(Action<T, object>), setExpression, instanceParameter, valueParameter);
Action<T, object> compiled = (Action<T, object>)lambdaExpression.Compile();
return compiled;
}
private Expression EnsureCastExpression(Expression expression, Type targetType)
{
Type expressionType = expression.Type;
// check if a cast or conversion is required
if (expressionType == targetType || (!expressionType.IsValueType() && targetType.IsAssignableFrom(expressionType)))
return expression;
return Expression.Convert(expression, targetType);
}
}
}
#endif
| |
//#define DEBUG
// Embedded HTTP server, partial 1.1 support with keep-alive and session management
// REQUIRES: Sockets.dll (or Sockets.cs)
// v1.0
// HttpServer: Main class that implements a HTTP server on top of Sockets server.
// Includes session management via cookies, keep-alive, UTF8 transfer of text
// and simple query string parsing (via GET or POST).
// HttpRequest: Represents the request made by the user, with header fields,
// query string and cookies pre-parsed. Typical server code will read the
// properties of this request to determine what to do.
// HttpResponse: The response which is to be sent back to the user. A simple
// server will set the Content property, but you can send binary information
// via RawContent, and change the mime type or response code.
// Session: A container into which you may put state information that will be
// available in future requests from the same user.
// IHttpHandler: You must implement this interface in order to process
// requests.
// SubstitutingFileHandler: An implementation of IHttpHandler that reads files
// from disk and allows substitutions of <%pseudotags> within text documents.
// (C) Richard Smith 2008
// bobjanova@gmail.com
// If downloaded from CodeProject, this file is subject to the CodeProject Open Licence 1.0.
// If downloaded from elsewhere, you may freely distribute the source code, as long as this
// header is not removed or modified. You may not charge for the source code or any compiled
// library that includes this class; however you may link to it from commercial software. Please
// leave a credit to the original download location in your documentation or About box.
// Simple HTTP server
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
namespace RedCorona.Net {
public class HttpServer {
Server s;
Hashtable hostmap = new Hashtable(); // Map<string, string>: Host => Home folder
ArrayList handlers = new ArrayList(); // List<IHttpHandler>
Hashtable sessions = new Hashtable(); // Map<string,Session>
int sessionTimeout = 600;
public Hashtable Hostmap { get { return hostmap; } }
public Server Server { get { return s ; } }
public ArrayList Handlers { get { return handlers; } }
public int SessionTimeout {
get { return sessionTimeout; }
set { sessionTimeout = value; CleanUpSessions(); }
}
public HttpServer(Server s){
this.s = s;
s.Connect += new ClientEvent(ClientConnect);
handlers.Add(new FallbackHandler());
}
bool ClientConnect(Server s, ClientInfo ci){
ci.Delimiter = "\r\n\r\n";
ci.Data = new ClientData(ci);
ci.OnRead += new ConnectionRead(ClientRead);
ci.OnReadBytes += new ConnectionReadBytes(ClientReadBytes);
return true;
}
void ClientRead(ClientInfo ci, string text){
// Read header, if in right state
ClientData data = (ClientData)ci.Data;
if(data.state != ClientState.Header) return; // already done; must be some text in content, which will be handled elsewhere
text = text.Substring(data.headerskip);
Console.WriteLine("Read header: "+text+" (skipping first "+data.headerskip+")");
data.headerskip = 0;
string[] lines = text.Replace("\r\n", "\n").Split('\n');
data.req.HeaderText = text;
// First line: METHOD /path/url HTTP/version
string[] firstline = lines[0].Split(' ');
if(firstline.Length != 3){ SendResponse(ci, data.req, new HttpResponse(400, "Incorrect first header line "+lines[0]), true); return; }
if(firstline[2].Substring(0, 4) != "HTTP"){ SendResponse(ci, data.req, new HttpResponse(400, "Unknown protocol "+firstline[2]), true); return; }
data.req.Method = firstline[0];
data.req.Url = firstline[1];
data.req.HttpVersion = firstline[2].Substring(5);
int p;
for(int i = 1; i < lines.Length; i++){
p = lines[i].IndexOf(':');
if(p > 0) data.req.Header[lines[i].Substring(0, p)] = lines[i].Substring(p+2);
else Console.WriteLine("Warning, incorrect header line "+lines[i]);
}
// If ? in URL, split out query information
p = firstline[1].IndexOf('?');
if(p > 0){
data.req.Page = data.req.Url.Substring(0, p);
data.req.QueryString = data.req.Url.Substring(p+1);
} else {
data.req.Page = data.req.Url;
data.req.QueryString = "";
}
if(data.req.Page.IndexOf("..") >= 0) { SendResponse(ci, data.req, new HttpResponse(400, "Invalid path"), true); return; }
if(!data.req.Header.TryGetValue("Host", out data.req.Host)){ SendResponse(ci, data.req, new HttpResponse(400, "No Host specified"), true); return; }
string cookieHeader;
if(data.req.Header.TryGetValue("Cookie", out cookieHeader)){
string[] cookies = cookieHeader.Split(';');
foreach(string cookie in cookies){
p = cookie.IndexOf('=');
if(p > 0){
data.req.Cookies[cookie.Substring(0, p).Trim()] = cookie.Substring(p+1);
} else {
data.req.Cookies[cookie.Trim()] = "";
}
}
}
string contentLengthString;
if(data.req.Header.TryGetValue("Content-Length", out contentLengthString))
data.req.ContentLength = Int32.Parse(contentLengthString);
else data.req.ContentLength = 0;
//if(data.req.ContentLength > 0){
data.state = ClientState.PreContent;
data.skip = text.Length + 4;
//} else DoProcess(ci);
//ClientReadBytes(ci, new byte[0], 0); // For content length 0 body
}
public string GetFilename(HttpRequest req){
string folder = (string)hostmap[req.Host];
if(folder == null) folder = "webhome";
if(req.Page == "/") return folder + "/index.html";
else return folder + req.Page;
}
void DoProcess(ClientInfo ci){
ClientData data = (ClientData)ci.Data;
string sessid;
if(data.req.Cookies.TryGetValue("_sessid", out sessid))
data.req.Session = (Session)sessions[sessid];
bool closed = Process(ci, data.req);
data.state = closed ? ClientState.Closed : ClientState.Header;
data.read = 0;
HttpRequest oldreq = data.req;
data.req = new HttpRequest(); // Once processed, the connection will be used for a new request
data.req.Session = oldreq.Session; // ... but session is persisted
data.req.From = ((IPEndPoint)ci.Socket.RemoteEndPoint).Address;
}
void ClientReadBytes(ClientInfo ci, byte[] bytes, int len){
CleanUpSessions();
int ofs = 0;
ClientData data = (ClientData)ci.Data;
Console.WriteLine("Reading "+len+" bytes of content, in state "+data.state+", skipping "+data.skip+", read "+data.read);
switch(data.state){
case ClientState.Content: break;
case ClientState.PreContent:
data.state = ClientState.Content;
if((data.skip - data.read) > len) { data.skip -= len; return; }
ofs = data.skip - data.read; data.skip = 0;
break;
//case ClientState.Header: data.read += len - data.headerskip; return;
default: data.read += len; return;
}
data.req.Content += Encoding.Default.GetString(bytes, ofs, len-ofs);
data.req.BytesRead += len - ofs;
data.headerskip += len - ofs;
#if DEBUG
Console.WriteLine("Reading "+(len-ofs)+" bytes of content. Got "+data.req.BytesRead+" of "+data.req.ContentLength);
#endif
if(data.req.BytesRead >= data.req.ContentLength){
if(data.req.Method == "POST"){
if(data.req.QueryString == "")data.req.QueryString = data.req.Content;
else data.req.QueryString += "&" + data.req.Content;
}
ParseQuery(data.req);
DoProcess(ci);
}
}
void ParseQuery(HttpRequest req){
if(req.QueryString == "") return;
string[] sections = req.QueryString.Split('&');
for(int i = 0; i < sections.Length; i++){
int p = sections[i].IndexOf('=');
if(p < 0) req.Query[sections[i]] = "";
else req.Query[sections[i].Substring(0, p)] = URLDecode(sections[i].Substring(p+1));
}
}
public static string URLDecode(string input){
StringBuilder output = new StringBuilder();
int p;
while((p = input.IndexOf('%')) >= 0){
output.Append(input.Substring(0, p));
string hexNumber = input.Substring(p + 1, 2);
input = input.Substring(p + 3);
output.Append((char)int.Parse(hexNumber, System.Globalization.NumberStyles.HexNumber));
}
return output.Append(input).ToString();
}
protected virtual bool Process(ClientInfo ci, HttpRequest req){
HttpResponse resp = new HttpResponse();
resp.Url = req.Url;
for(int i = handlers.Count - 1; i >= 0; i--){
IHttpHandler handler = (IHttpHandler)handlers[i];
if(handler.Process(this, req, resp)){
SendResponse(ci, req, resp, resp.ReturnCode != 200);
return resp.ReturnCode != 200;
}
}
return true;
}
enum ClientState { Closed, Header, PreContent, Content };
class ClientData {
internal HttpRequest req = new HttpRequest();
internal ClientState state = ClientState.Header;
internal int skip, read, headerskip;
internal ClientData(ClientInfo ci){
req.From = ((IPEndPoint)ci.Socket.RemoteEndPoint).Address;
}
}
public Session RequestSession(HttpRequest req){
if(req.Session != null){
if(sessions[req.Session.ID] == req.Session) return req.Session;
}
req.Session = new Session(req.From);
sessions[req.Session.ID] = req.Session;
return req.Session;
}
void CleanUpSessions(){
ICollection keys = sessions.Keys;
ArrayList toRemove = new ArrayList();
foreach(string k in keys){
Session s = (Session)sessions[k];
int time = (int)((DateTime.Now - s.LastTouched).TotalSeconds);
if(time > sessionTimeout){
toRemove.Add(k);
Console.WriteLine("Removed session "+k);
}
}
foreach(object k in toRemove) sessions.Remove(k);
}
// Response stuff
static Hashtable Responses = new Hashtable();
static HttpServer(){
Responses[200] = "OK";
Responses[302] = "Found";
Responses[303] = "See Other";
Responses[400] = "Bad Request";
Responses[404] = "Not Found";
Responses[500] = "Misc Server Error";
Responses[502] = "Server Busy";
}
void SendResponse(ClientInfo ci, HttpRequest req, HttpResponse resp, bool close){
#if DEBUG
Console.WriteLine("Response: "+resp.ReturnCode + Responses[resp.ReturnCode]);
#endif
ByteBuilder bb = new ByteBuilder();
bb.Add(Encoding.UTF8.GetBytes("HTTP/1.1 " + resp.ReturnCode + " " + Responses[resp.ReturnCode] +
"\r\nDate: "+DateTime.Now.ToString("R")+
"\r\nServer: RedCoronaEmbedded/1.0"+
"\r\nConnection: "+(close ? "close" : "Keep-Alive")));
bb.Add(Encoding.UTF8.GetBytes("\r\nContent-Encoding: " + (resp.Encoding == null ? "utf-8" : resp.Encoding)));
if (resp.RawContent == null)
bb.Add(Encoding.UTF8.GetBytes("\r\nContent-Length: " + resp.Content.Length));
else
bb.Add(Encoding.UTF8.GetBytes("\r\nContent-Length: " + resp.RawContent.Length));
if(resp.ContentType != null)
bb.Add(Encoding.UTF8.GetBytes("\r\nContent-Type: "+resp.ContentType));
if(req.Session != null) bb.Add(Encoding.UTF8.GetBytes("\r\nSet-Cookie: _sessid="+req.Session.ID+"; path=/"));
foreach(KeyValuePair<string, string> de in resp.Header) bb.Add(Encoding.UTF8.GetBytes("\r\n" + de.Key + ": " + de.Value));
bb.Add(Encoding.UTF8.GetBytes("\r\n\r\n")); // End of header
if(resp.RawContent != null) bb.Add(resp.RawContent);
else bb.Add(Encoding.UTF8.GetBytes(resp.Content));
ci.Send(bb.Read(0, bb.Length));
#if DEBUG
Console.WriteLine("** SENDING\n"+resp.Content);
#endif
if(close) ci.Close();
}
class FallbackHandler : IHttpHandler {
public bool Process(HttpServer server, HttpRequest req, HttpResponse resp){
#if DEBUG
Console.WriteLine("Processing "+req);
#endif
server.RequestSession(req);
StringBuilder sb = new StringBuilder();
sb.Append("<h3>Session</h3>");
sb.Append("<p>ID: "+req.Session.ID+"<br>User: "+req.Session.User);
sb.Append("<h3>Header</h3>");
sb.Append("Method: "+req.Method+"; URL: '"+req.Url+"'; HTTP version "+req.HttpVersion+"<p>");
foreach(KeyValuePair<string, string> ide in req.Header) sb.Append(" "+ide.Key +": "+ide.Value+"<br>");
sb.Append("<h3>Cookies</h3>");
foreach(KeyValuePair<string, string> ide in req.Cookies) sb.Append(" "+ide.Key +": "+ide.Value+"<br>");
sb.Append("<h3>Query</h3>");
foreach(KeyValuePair<string, string> ide in req.Query) sb.Append(" "+ide.Key +": "+ide.Value+"<br>");
sb.Append("<h3>Content</h3>");
sb.Append(req.Content);
resp.Content = sb.ToString();
return true;
}
}
}
public class HttpRequest {
public bool GotHeader = false;
public string Method, Url, Page, HttpVersion, Host, Content, HeaderText, QueryString;
public IPAddress From;
//public byte[] RawContent;
public Dictionary<string, string> Query = new Dictionary<string, string>(), Header = new Dictionary<string, string>(), Cookies = new Dictionary<string, string>();
public int ContentLength, BytesRead;
public Session Session;
}
public class HttpResponse {
public int ReturnCode = 200;
public Dictionary<string, string> Header = new Dictionary<string, string>();
public string Url, Content, ContentType = "text/html";
public byte[] RawContent = null;
public string Encoding = null;
public HttpResponse(){}
public HttpResponse(int code, string content){ ReturnCode = code; Content = content; }
public void MakeRedirect(string newurl){
ReturnCode = 303;
Header["Location"] = newurl;
Content = "This document is requesting a redirection to <a href="+newurl+">"+newurl+"</a>";
}
}
public interface IHttpHandler {
bool Process(HttpServer server, HttpRequest request, HttpResponse response);
}
public class Session {
string id;
IPAddress user;
DateTime lasttouched;
Hashtable data = new Hashtable();
public string ID { get { return id; } }
public DateTime LastTouched { get { return lasttouched; } }
public IPAddress User { get { return user; } }
public object this[object key]{
get { return data[key]; }
set { data[key] = value; Touch(); }
}
public Session(IPAddress user){
this.user = user;
this.id = Guid.NewGuid().ToString();
Touch();
}
public void Touch(){ lasttouched = DateTime.Now; }
}
public class SubstitutingFileReader : IHttpHandler {
// Reads a file, and substitutes <%x>
HttpRequest req;
bool substitute = true;
public bool Substitute { get { return substitute; } set { substitute = value; } }
public static Hashtable MimeTypes;
static SubstitutingFileReader(){
MimeTypes = new Hashtable();
MimeTypes[".html"] = "text/html";
MimeTypes[".htm"] = "text/html";
MimeTypes[".css"] = "text/css";
MimeTypes[".js"] = "application/x-javascript";
MimeTypes[".png"] = "image/png";
MimeTypes[".gif"] = "image/gif";
MimeTypes[".jpg"] = "image/jpeg";
MimeTypes[".jpeg"] = "image/jpeg";
}
public virtual bool Process(HttpServer server, HttpRequest request, HttpResponse response){
string fn = server.GetFilename(request);
if(!File.Exists(fn)){
response.ReturnCode = 404;
response.Content = "File not found.";
return true;
}
string ext = Path.GetExtension(fn);
string mime = (string)MimeTypes[ext];
if(mime == null) mime = "application/octet-stream";
response.ContentType = mime;
try {
if(mime.Substring(0, 5) == "text/") {
// Mime type 'text' is substituted
StreamReader sr = new StreamReader(fn);
response.Content = sr.ReadToEnd();
sr.Close();
if(substitute){
// Do substitutions
Regex regex = new Regex(@"\<\%(?<tag>[^>]+)\>");
lock(this){
req = request;
response.Content = regex.Replace(response.Content, new MatchEvaluator(RegexMatch));
}
}
} else {
FileStream fs = File.Open(fn, FileMode.Open);
byte[] buf = new byte[fs.Length];
fs.Read(buf, 0, buf.Length);
fs.Close();
response.RawContent = buf;
}
} catch(Exception e) {
response.ReturnCode = 500;
response.Content = "Error reading file: "+e;
return true;
}
return true;
}
public virtual string GetValue(HttpRequest req, string tag){
return "<span class=error>Unknown substitution: "+tag+"</span>";
}
string RegexMatch(Match m){
try {
return GetValue(req, m.Groups["tag"].Value);
} catch(Exception) {
return "<span class=error>Error substituting "+m.Groups["tag"].Value+"</span>";
}
}
}
}
| |
/***************************************************************************\
*
* File: XmlWrappingReader.cs
*
* Purpose:
*
* History:
* 5/11/05: fmunoz "Borrowed from Whidbey Beta2 Sources
*
* Copyright (C) 2005 by Microsoft Corporation. All rights reserved.
*
\***************************************************************************/
//------------------------------------------------------------------------------
// <copyright file="XmlWrappingReader.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
//------------------------------------------------------------------------------
using System;
using System.Xml;
using System.Xml.Schema;
using System.Diagnostics;
using System.Collections.Generic;
using System.Security.Policy;
#if PBTCOMPILER
namespace MS.Internal.Markup
#elif SYSTEM_XAML
namespace System.Xaml
#else
namespace System.Windows.Markup
#endif
{
internal class XmlWrappingReader : XmlReader, IXmlLineInfo, IXmlNamespaceResolver {
//
// Fields
//
protected XmlReader _reader;
protected IXmlLineInfo _readerAsIXmlLineInfo;
protected IXmlNamespaceResolver _readerAsResolver;
//
// Constructor
//
internal XmlWrappingReader( XmlReader baseReader ) {
Debug.Assert( baseReader != null );
Reader = baseReader;
}
//
// XmlReader implementation
//
public override XmlReaderSettings Settings { get { return _reader.Settings; } }
public override XmlNodeType NodeType { get { return _reader.NodeType; } }
public override string Name { get { return _reader.Name; } }
public override string LocalName { get { return _reader.LocalName; } }
public override string NamespaceURI { get { return _reader.NamespaceURI; } }
public override string Prefix { get { return _reader.Prefix; } }
public override bool HasValue { get { return _reader.HasValue; } }
public override string Value { get { return _reader.Value; } }
public override int Depth { get { return _reader.Depth; } }
public override string BaseURI { get { return _reader.BaseURI; } }
public override bool IsEmptyElement { get { return _reader.IsEmptyElement; } }
public override bool IsDefault { get { return _reader.IsDefault; } }
public override char QuoteChar { get { return _reader.QuoteChar; } }
public override XmlSpace XmlSpace { get { return _reader.XmlSpace; } }
public override string XmlLang { get { return _reader.XmlLang; } }
public override IXmlSchemaInfo SchemaInfo { get { return _reader.SchemaInfo; } }
public override System.Type ValueType { get { return _reader.ValueType; } }
public override int AttributeCount { get { return _reader.AttributeCount; } }
public override string this [ int i ] { get { return _reader[i]; } }
public override string this [ string name ] { get { return _reader[ name ];}}
public override string this [ string name, string namespaceURI ] { get { return _reader[ name, namespaceURI ]; } }
public override bool CanResolveEntity { get { return _reader.CanResolveEntity; } }
public override bool EOF { get { return _reader.EOF; } }
public override ReadState ReadState { get { return _reader.ReadState; } }
public override bool HasAttributes { get { return _reader.HasAttributes; } }
public override XmlNameTable NameTable { get { return _reader.NameTable; } }
public override string GetAttribute( string name ) {
return _reader.GetAttribute( name );
}
public override string GetAttribute( string name, string namespaceURI ) {
return _reader.GetAttribute( name, namespaceURI );
}
public override string GetAttribute( int i ) {
return _reader.GetAttribute( i );
}
public override bool MoveToAttribute( string name ) {
return _reader.MoveToAttribute( name );
}
public override bool MoveToAttribute( string name, string ns ) {
return _reader.MoveToAttribute( name, ns );
}
public override void MoveToAttribute( int i ) {
_reader.MoveToAttribute( i );
}
public override bool MoveToFirstAttribute() {
return _reader.MoveToFirstAttribute();
}
public override bool MoveToNextAttribute() {
return _reader.MoveToNextAttribute();
}
public override bool MoveToElement() {
return _reader.MoveToElement();
}
public override bool Read() {
return _reader.Read();
}
public override void Close() {
_reader.Close();
}
public override void Skip() {
_reader.Skip();
}
public override string LookupNamespace( string prefix ) {
return _reader.LookupNamespace( prefix );
}
string IXmlNamespaceResolver.LookupPrefix( string namespaceName ) {
return (_readerAsResolver == null) ? null : _readerAsResolver.LookupPrefix( namespaceName );
}
IDictionary<string,string> IXmlNamespaceResolver.GetNamespacesInScope ( XmlNamespaceScope scope ) {
return (_readerAsResolver == null) ? null : _readerAsResolver.GetNamespacesInScope( scope );
}
public override void ResolveEntity() {
_reader.ResolveEntity();
}
public override bool ReadAttributeValue() {
return _reader.ReadAttributeValue();
}
//
// IDisposable interface
//
protected override void Dispose(bool disposing) {
try
{
if(disposing)
{
((IDisposable)_reader).Dispose();
}
}
finally
{
base.Dispose(disposing);
}
}
//
// IXmlLineInfo members
//
public virtual bool HasLineInfo() {
return ( _readerAsIXmlLineInfo == null ) ? false : _readerAsIXmlLineInfo.HasLineInfo();
}
public virtual int LineNumber {
get {
return ( _readerAsIXmlLineInfo == null ) ? 0 : _readerAsIXmlLineInfo.LineNumber;
}
}
public virtual int LinePosition {
get {
return ( _readerAsIXmlLineInfo == null ) ? 0 : _readerAsIXmlLineInfo.LinePosition;
}
}
//
// Protected methods
//
protected XmlReader Reader {
get {
return _reader;
}
set {
_reader = value;
_readerAsIXmlLineInfo = value as IXmlLineInfo;
_readerAsResolver = value as IXmlNamespaceResolver;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using UnityEngine.Assertions;
namespace UnityEngine.Rendering.PostProcessing
{
using SceneManagement;
using UnityObject = UnityEngine.Object;
public static class RuntimeUtilities
{
#region Textures
static Texture2D m_WhiteTexture;
public static Texture2D whiteTexture
{
get
{
if (m_WhiteTexture == null)
{
m_WhiteTexture = new Texture2D(1, 1, TextureFormat.ARGB32, false);
m_WhiteTexture.SetPixel(0, 0, Color.white);
m_WhiteTexture.Apply();
}
return m_WhiteTexture;
}
}
static Texture2D m_BlackTexture;
public static Texture2D blackTexture
{
get
{
if (m_BlackTexture == null)
{
m_BlackTexture = new Texture2D(1, 1, TextureFormat.ARGB32, false);
m_BlackTexture.SetPixel(0, 0, Color.black);
m_BlackTexture.Apply();
}
return m_BlackTexture;
}
}
static Texture2D m_TransparentTexture;
public static Texture2D transparentTexture
{
get
{
if (m_TransparentTexture == null)
{
m_TransparentTexture = new Texture2D(1, 1, TextureFormat.ARGB32, false);
m_TransparentTexture.SetPixel(0, 0, Color.clear);
m_TransparentTexture.Apply();
}
return m_TransparentTexture;
}
}
#endregion
#region Rendering
static Mesh s_FullscreenTriangle;
public static Mesh fullscreenTriangle
{
get
{
if (s_FullscreenTriangle != null)
return s_FullscreenTriangle;
s_FullscreenTriangle = new Mesh { name = "Fullscreen Triangle" };
// Because we have to support older platforms (GLES2/3, DX9 etc) we can't do all of
// this directly in the vertex shader using vertex ids :(
s_FullscreenTriangle.SetVertices(new List<Vector3>
{
new Vector3(-1f, -1f, 0f),
new Vector3(-1f, 3f, 0f),
new Vector3( 3f, -1f, 0f)
});
s_FullscreenTriangle.SetIndices(new [] { 0, 1, 2 }, MeshTopology.Triangles, 0, false);
s_FullscreenTriangle.UploadMeshData(false);
return s_FullscreenTriangle;
}
}
static Material s_CopyMaterial;
public static Material copyMaterial
{
get
{
if (s_CopyMaterial != null)
return s_CopyMaterial;
var shader = Shader.Find("Hidden/PostProcessing/Copy");
s_CopyMaterial = new Material(shader)
{
name = "PostProcess - Copy",
hideFlags = HideFlags.HideAndDontSave
};
return s_CopyMaterial;
}
}
// Use a custom blit method to draw a fullscreen triangle instead of a fullscreen quad
// https://michaldrobot.com/2014/04/01/gcn-execution-patterns-in-full-screen-passes/
public static void BlitFullscreenTriangle(this CommandBuffer cmd, RenderTargetIdentifier source, RenderTargetIdentifier destination, bool clear = false)
{
cmd.SetGlobalTexture(ShaderIDs.MainTex, source);
cmd.SetRenderTarget(destination);
if (clear)
cmd.ClearRenderTarget(true, true, Color.clear);
cmd.DrawMesh(fullscreenTriangle, Matrix4x4.identity, copyMaterial, 0, 0);
}
public static void BlitFullscreenTriangle(this CommandBuffer cmd, RenderTargetIdentifier source, RenderTargetIdentifier destination, PropertySheet propertySheet, int pass, bool clear = false)
{
cmd.SetGlobalTexture(ShaderIDs.MainTex, source);
cmd.SetRenderTarget(destination);
if (clear)
cmd.ClearRenderTarget(true, true, Color.clear);
cmd.DrawMesh(fullscreenTriangle, Matrix4x4.identity, propertySheet.material, 0, pass, propertySheet.properties);
}
public static void BlitFullscreenTriangle(this CommandBuffer cmd, RenderTargetIdentifier source, RenderTargetIdentifier destination, RenderTargetIdentifier depth, PropertySheet propertySheet, int pass, bool clear = false)
{
cmd.SetGlobalTexture(ShaderIDs.MainTex, source);
cmd.SetRenderTarget(destination, depth);
if (clear)
cmd.ClearRenderTarget(true, true, Color.clear);
cmd.DrawMesh(fullscreenTriangle, Matrix4x4.identity, propertySheet.material, 0, pass, propertySheet.properties);
}
public static void BlitFullscreenTriangle(this CommandBuffer cmd, RenderTargetIdentifier source, RenderTargetIdentifier[] destinations, RenderTargetIdentifier depth, PropertySheet propertySheet, int pass, bool clear = false)
{
cmd.SetGlobalTexture(ShaderIDs.MainTex, source);
cmd.SetRenderTarget(destinations, depth);
if (clear)
cmd.ClearRenderTarget(true, true, Color.clear);
cmd.DrawMesh(fullscreenTriangle, Matrix4x4.identity, propertySheet.material, 0, pass, propertySheet.properties);
}
public static void BlitFullscreenTriangle(Texture source, RenderTexture destination, Material material, int pass)
{
var oldRt = RenderTexture.active;
material.SetPass(pass);
if (source != null)
material.SetTexture(ShaderIDs.MainTex, source);
Graphics.SetRenderTarget(destination);
Graphics.DrawMeshNow(fullscreenTriangle, Matrix4x4.identity);
RenderTexture.active = oldRt;
}
// Fast basic copy texture if available, falls back to blit copy if not
// Assumes that both textures have the exact same type and format
public static void CopyTexture(CommandBuffer cmd, RenderTargetIdentifier source, RenderTargetIdentifier destination)
{
if (SystemInfo.copyTextureSupport > CopyTextureSupport.None)
cmd.CopyTexture(source, destination);
else
cmd.BlitFullscreenTriangle(source, destination);
}
#endregion
#region Unity specifics
public static bool scriptableRenderPipelineActive
{
get { return GraphicsSettings.renderPipelineAsset != null; } // 5.6+ only
}
public static bool isSinglePassStereoEnabled
{
get
{
#if UNITY_EDITOR
return UnityEditor.PlayerSettings.virtualRealitySupported
&& UnityEditor.PlayerSettings.stereoRenderingPath == UnityEditor.StereoRenderingPath.SinglePass;
#else
return false; // TODO: Check for SPSR support at runtime
#endif
}
}
public static bool isVREnabled
{
get
{
#if UNITY_EDITOR
return UnityEditor.PlayerSettings.virtualRealitySupported;
#elif UNITY_2017_2_OR_NEWER
return UnityEngine.XR.XRSettings.enabled;
#elif UNITY_5_6_OR_NEWER
return UnityEngine.VR.VRSettings.enabled;
#endif
}
}
public static void Destroy(UnityObject obj)
{
if (obj != null)
{
#if UNITY_EDITOR
if (Application.isPlaying)
UnityObject.Destroy(obj);
else
UnityObject.DestroyImmediate(obj);
#else
UnityObject.Destroy(obj);
#endif
}
}
public static bool isLinearColorSpace
{
get { return QualitySettings.activeColorSpace == ColorSpace.Linear; }
}
public static void DestroyProfile(PostProcessProfile profile, bool destroyEffects)
{
if (destroyEffects)
{
foreach (var effect in profile.settings)
Destroy(effect);
}
Destroy(profile);
}
public static void DestroyVolume(PostProcessVolume volume, bool destroySharedProfile)
{
if (destroySharedProfile)
DestroyProfile(volume.sharedProfile, true);
Destroy(volume);
}
// Returns ALL scene objects in the hierarchy, included inactive objects
// Beware, this method will be slow for big scenes
public static IEnumerable<T> GetAllSceneObjects<T>()
where T : Component
{
var queue = new Queue<Transform>();
var roots = SceneManager.GetActiveScene().GetRootGameObjects();
foreach (var root in roots)
{
queue.Enqueue(root.transform);
var comp = root.GetComponent<T>();
if (comp != null)
yield return comp;
}
while (queue.Count > 0)
{
foreach (Transform child in queue.Dequeue())
{
queue.Enqueue(child);
var comp = child.GetComponent<T>();
if (comp != null)
yield return comp;
}
}
}
#endregion
#region Maths
public static float Exp2(float x)
{
return Mathf.Exp(x * 0.69314718055994530941723212145818f);
}
#endregion
#region Reflection
// Quick extension method to get the first attribute of type T on a given Type
public static T GetAttribute<T>(this Type type) where T : Attribute
{
Assert.IsTrue(type.IsDefined(typeof(T), false), "Attribute not found");
return (T)type.GetCustomAttributes(typeof(T), false)[0];
}
// Returns all attributes set on a specific member
// Note: doesn't include inherited attributes, only explicit ones
public static Attribute[] GetMemberAttributes<TType, TValue>(Expression<Func<TType, TValue>> expr)
{
Expression body = expr;
if (body is LambdaExpression)
body = ((LambdaExpression)body).Body;
switch (body.NodeType)
{
case ExpressionType.MemberAccess:
var fi = (FieldInfo)((MemberExpression)body).Member;
return fi.GetCustomAttributes(false).Cast<Attribute>().ToArray();
default:
throw new InvalidOperationException();
}
}
// Returns a string path from an expression - mostly used to retrieve serialized properties
// without hardcoding the field path. Safer, and allows for proper refactoring.
public static string GetFieldPath<TType, TValue>(Expression<Func<TType, TValue>> expr)
{
MemberExpression me;
switch (expr.Body.NodeType)
{
case ExpressionType.MemberAccess:
me = expr.Body as MemberExpression;
break;
default:
throw new InvalidOperationException();
}
var members = new List<string>();
while (me != null)
{
members.Add(me.Member.Name);
me = me.Expression as MemberExpression;
}
var sb = new StringBuilder();
for (int i = members.Count - 1; i >= 0; i--)
{
sb.Append(members[i]);
if (i > 0) sb.Append('.');
}
return sb.ToString();
}
public static object GetParentObject(string path, object obj)
{
var fields = path.Split('.');
if (fields.Length == 1)
return obj;
var info = obj.GetType().GetField(fields[0], BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
obj = info.GetValue(obj);
return GetParentObject(string.Join(".", fields, 1, fields.Length - 1), obj);
}
#endregion
}
}
| |
using System;
using System.Globalization;
using System.Collections.Generic;
using Sasoma.Utils;
using Sasoma.Microdata.Interfaces;
using Sasoma.Languages.Core;
using Sasoma.Microdata.Properties;
namespace Sasoma.Microdata.Types
{
/// <summary>
/// A tourist information center.
/// </summary>
public class TouristInformationCenter_Core : TypeCore, ILocalBusiness
{
public TouristInformationCenter_Core()
{
this._TypeId = 269;
this._Id = "TouristInformationCenter";
this._Schema_Org_Url = "http://schema.org/TouristInformationCenter";
string label = "";
GetLabel(out label, "TouristInformationCenter", typeof(TouristInformationCenter_Core));
this._Label = label;
this._Ancestors = new int[]{266,193,155};
this._SubTypes = new int[0];
this._SuperTypes = new int[]{155};
this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,47,75,77,94,95,130,137,36,60,152,156,167};
}
/// <summary>
/// Physical address of the item.
/// </summary>
private Address_Core address;
public Address_Core Address
{
get
{
return address;
}
set
{
address = value;
SetPropertyInstance(address);
}
}
/// <summary>
/// The overall rating, based on a collection of reviews or ratings, of the item.
/// </summary>
private Properties.AggregateRating_Core aggregateRating;
public Properties.AggregateRating_Core AggregateRating
{
get
{
return aggregateRating;
}
set
{
aggregateRating = value;
SetPropertyInstance(aggregateRating);
}
}
/// <summary>
/// The larger organization that this local business is a branch of, if any.
/// </summary>
private BranchOf_Core branchOf;
public BranchOf_Core BranchOf
{
get
{
return branchOf;
}
set
{
branchOf = value;
SetPropertyInstance(branchOf);
}
}
/// <summary>
/// A contact point for a person or organization.
/// </summary>
private ContactPoints_Core contactPoints;
public ContactPoints_Core ContactPoints
{
get
{
return contactPoints;
}
set
{
contactPoints = value;
SetPropertyInstance(contactPoints);
}
}
/// <summary>
/// The basic containment relation between places.
/// </summary>
private ContainedIn_Core containedIn;
public ContainedIn_Core ContainedIn
{
get
{
return containedIn;
}
set
{
containedIn = value;
SetPropertyInstance(containedIn);
}
}
/// <summary>
/// The currency accepted (in <a href=\http://en.wikipedia.org/wiki/ISO_4217\ target=\new\>ISO 4217 currency format</a>).
/// </summary>
private CurrenciesAccepted_Core currenciesAccepted;
public CurrenciesAccepted_Core CurrenciesAccepted
{
get
{
return currenciesAccepted;
}
set
{
currenciesAccepted = value;
SetPropertyInstance(currenciesAccepted);
}
}
/// <summary>
/// A short description of the item.
/// </summary>
private Description_Core description;
public Description_Core Description
{
get
{
return description;
}
set
{
description = value;
SetPropertyInstance(description);
}
}
/// <summary>
/// Email address.
/// </summary>
private Email_Core email;
public Email_Core Email
{
get
{
return email;
}
set
{
email = value;
SetPropertyInstance(email);
}
}
/// <summary>
/// People working for this organization.
/// </summary>
private Employees_Core employees;
public Employees_Core Employees
{
get
{
return employees;
}
set
{
employees = value;
SetPropertyInstance(employees);
}
}
/// <summary>
/// Upcoming or past events associated with this place or organization.
/// </summary>
private Events_Core events;
public Events_Core Events
{
get
{
return events;
}
set
{
events = value;
SetPropertyInstance(events);
}
}
/// <summary>
/// The fax number.
/// </summary>
private FaxNumber_Core faxNumber;
public FaxNumber_Core FaxNumber
{
get
{
return faxNumber;
}
set
{
faxNumber = value;
SetPropertyInstance(faxNumber);
}
}
/// <summary>
/// A person who founded this organization.
/// </summary>
private Founders_Core founders;
public Founders_Core Founders
{
get
{
return founders;
}
set
{
founders = value;
SetPropertyInstance(founders);
}
}
/// <summary>
/// The date that this organization was founded.
/// </summary>
private FoundingDate_Core foundingDate;
public FoundingDate_Core FoundingDate
{
get
{
return foundingDate;
}
set
{
foundingDate = value;
SetPropertyInstance(foundingDate);
}
}
/// <summary>
/// The geo coordinates of the place.
/// </summary>
private Geo_Core geo;
public Geo_Core Geo
{
get
{
return geo;
}
set
{
geo = value;
SetPropertyInstance(geo);
}
}
/// <summary>
/// URL of an image of the item.
/// </summary>
private Image_Core image;
public Image_Core Image
{
get
{
return image;
}
set
{
image = value;
SetPropertyInstance(image);
}
}
/// <summary>
/// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>.
/// </summary>
private InteractionCount_Core interactionCount;
public InteractionCount_Core InteractionCount
{
get
{
return interactionCount;
}
set
{
interactionCount = value;
SetPropertyInstance(interactionCount);
}
}
/// <summary>
/// The location of the event or organization.
/// </summary>
private Location_Core location;
public Location_Core Location
{
get
{
return location;
}
set
{
location = value;
SetPropertyInstance(location);
}
}
/// <summary>
/// A URL to a map of the place.
/// </summary>
private Maps_Core maps;
public Maps_Core Maps
{
get
{
return maps;
}
set
{
maps = value;
SetPropertyInstance(maps);
}
}
/// <summary>
/// A member of this organization.
/// </summary>
private Members_Core members;
public Members_Core Members
{
get
{
return members;
}
set
{
members = value;
SetPropertyInstance(members);
}
}
/// <summary>
/// The name of the item.
/// </summary>
private Name_Core name;
public Name_Core Name
{
get
{
return name;
}
set
{
name = value;
SetPropertyInstance(name);
}
}
/// <summary>
/// The opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'.<br/>- Days are specified using the following two-letter combinations: <code>Mo</code>, <code>Tu</code>, <code>We</code>, <code>Th</code>, <code>Fr</code>, <code>Sa</code>, <code>Su</code>.<br/>- Times are specified using 24:00 time. For example, 3pm is specified as <code>15:00</code>. <br/>- Here is an example: <code><time itemprop=\openingHours\ datetime=\Tu,Th 16:00-20:00\>Tuesdays and Thursdays 4-8pm</time></code>. <br/>- If a business is open 7 days a week, then it can be specified as <code><time itemprop=\openingHours\ datetime=\Mo-Su\>Monday through Sunday, all day</time></code>.
/// </summary>
private OpeningHours_Core openingHours;
public OpeningHours_Core OpeningHours
{
get
{
return openingHours;
}
set
{
openingHours = value;
SetPropertyInstance(openingHours);
}
}
/// <summary>
/// Cash, credit card, etc.
/// </summary>
private PaymentAccepted_Core paymentAccepted;
public PaymentAccepted_Core PaymentAccepted
{
get
{
return paymentAccepted;
}
set
{
paymentAccepted = value;
SetPropertyInstance(paymentAccepted);
}
}
/// <summary>
/// Photographs of this place.
/// </summary>
private Photos_Core photos;
public Photos_Core Photos
{
get
{
return photos;
}
set
{
photos = value;
SetPropertyInstance(photos);
}
}
/// <summary>
/// The price range of the business, for example <code>$$$</code>.
/// </summary>
private PriceRange_Core priceRange;
public PriceRange_Core PriceRange
{
get
{
return priceRange;
}
set
{
priceRange = value;
SetPropertyInstance(priceRange);
}
}
/// <summary>
/// Review of the item.
/// </summary>
private Reviews_Core reviews;
public Reviews_Core Reviews
{
get
{
return reviews;
}
set
{
reviews = value;
SetPropertyInstance(reviews);
}
}
/// <summary>
/// The telephone number.
/// </summary>
private Telephone_Core telephone;
public Telephone_Core Telephone
{
get
{
return telephone;
}
set
{
telephone = value;
SetPropertyInstance(telephone);
}
}
/// <summary>
/// URL of the item.
/// </summary>
private Properties.URL_Core uRL;
public Properties.URL_Core URL
{
get
{
return uRL;
}
set
{
uRL = value;
SetPropertyInstance(uRL);
}
}
}
}
| |
/*
* Copyright 2012-2016 The Pkcs11Interop 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.
*/
/*
* Written for the Pkcs11Interop project by:
* Jaroslav IMRICH <jimrich@jimrich.sk>
*/
using System;
using System.IO;
using Net.Pkcs11Interop.Common;
using Net.Pkcs11Interop.LowLevelAPI41;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Net.Pkcs11Interop.Tests.LowLevelAPI41
{
/// <summary>
/// C_SignInit, C_Sign, C_SignUpdate, C_SignFinal, C_VerifyInit, C_Verify, C_VerifyUpdate and C_VerifyFinal tests.
/// </summary>
[TestClass]
public class _21_SignAndVerifyTest
{
/// <summary>
/// C_SignInit, C_Sign, C_VerifyInit and C_Verify test with CKM_RSA_PKCS mechanism.
/// </summary>
[TestMethod]
public void _01_SignAndVerifySinglePartTest()
{
if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 1)
Assert.Inconclusive("Test cannot be executed on this platform");
CKR rv = CKR.CKR_OK;
using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath))
{
rv = pkcs11.C_Initialize(Settings.InitArgs41);
if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED))
Assert.Fail(rv.ToString());
// Find first slot with token present
uint slotId = Helpers.GetUsableSlot(pkcs11);
uint session = CK.CK_INVALID_HANDLE;
rv = pkcs11.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Login as normal user
rv = pkcs11.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, Convert.ToUInt32(Settings.NormalUserPinArray.Length));
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Generate asymetric key pair
uint pubKeyId = CK.CK_INVALID_HANDLE;
uint privKeyId = CK.CK_INVALID_HANDLE;
rv = Helpers.GenerateKeyPair(pkcs11, session, ref pubKeyId, ref privKeyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Specify signing mechanism (needs no parameter => no unamanaged memory is needed)
CK_MECHANISM mechanism = CkmUtils.CreateMechanism(CKM.CKM_SHA1_RSA_PKCS);
// Initialize signing operation
rv = pkcs11.C_SignInit(session, ref mechanism, privKeyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
byte[] sourceData = ConvertUtils.Utf8StringToBytes("Hello world");
// Get length of signature in first call
uint signatureLen = 0;
rv = pkcs11.C_Sign(session, sourceData, Convert.ToUInt32(sourceData.Length), null, ref signatureLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
Assert.IsTrue(signatureLen > 0);
// Allocate array for signature
byte[] signature = new byte[signatureLen];
// Get signature in second call
rv = pkcs11.C_Sign(session, sourceData, Convert.ToUInt32(sourceData.Length), signature, ref signatureLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Do something interesting with signature
// Initialize verification operation
rv = pkcs11.C_VerifyInit(session, ref mechanism, pubKeyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Verify signature
rv = pkcs11.C_Verify(session, sourceData, Convert.ToUInt32(sourceData.Length), signature, Convert.ToUInt32(signature.Length));
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Do something interesting with verification result
rv = pkcs11.C_DestroyObject(session, privKeyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11.C_DestroyObject(session, pubKeyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11.C_Logout(session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11.C_CloseSession(session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11.C_Finalize(IntPtr.Zero);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
}
}
/// <summary>
/// C_SignInit, C_SignUpdate, C_SignFinal, C_VerifyInit, C_VerifyUpdate and C_VerifyFinal test.
/// </summary>
[TestMethod]
public void _02_SignAndVerifyMultiPartTest()
{
if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 1)
Assert.Inconclusive("Test cannot be executed on this platform");
CKR rv = CKR.CKR_OK;
using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath))
{
rv = pkcs11.C_Initialize(Settings.InitArgs41);
if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED))
Assert.Fail(rv.ToString());
// Find first slot with token present
uint slotId = Helpers.GetUsableSlot(pkcs11);
uint session = CK.CK_INVALID_HANDLE;
rv = pkcs11.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Login as normal user
rv = pkcs11.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, Convert.ToUInt32(Settings.NormalUserPinArray.Length));
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Generate asymetric key pair
uint pubKeyId = CK.CK_INVALID_HANDLE;
uint privKeyId = CK.CK_INVALID_HANDLE;
rv = Helpers.GenerateKeyPair(pkcs11, session, ref pubKeyId, ref privKeyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Specify signing mechanism (needs no parameter => no unamanaged memory is needed)
CK_MECHANISM mechanism = CkmUtils.CreateMechanism(CKM.CKM_SHA1_RSA_PKCS);
byte[] sourceData = ConvertUtils.Utf8StringToBytes("Hello world");
byte[] signature = null;
// Multipart signature functions C_SignUpdate and C_SignFinal can be used i.e. for signing of streamed data
using (MemoryStream inputStream = new MemoryStream(sourceData))
{
// Initialize signing operation
rv = pkcs11.C_SignInit(session, ref mechanism, privKeyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Prepare buffer for source data part
// Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long
byte[] part = new byte[8];
// Read input stream with source data
int bytesRead = 0;
while ((bytesRead = inputStream.Read(part, 0, part.Length)) > 0)
{
// Process each individual source data part
rv = pkcs11.C_SignUpdate(session, part, Convert.ToUInt32(bytesRead));
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
}
// Get the length of signature in first call
uint signatureLen = 0;
rv = pkcs11.C_SignFinal(session, null, ref signatureLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
Assert.IsTrue(signatureLen > 0);
// Allocate array for signature
signature = new byte[signatureLen];
// Get signature in second call
rv = pkcs11.C_SignFinal(session, signature, ref signatureLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
}
// Do something interesting with signature
// Multipart verification functions C_VerifyUpdate and C_VerifyFinal can be used i.e. for signature verification of streamed data
using (MemoryStream inputStream = new MemoryStream(sourceData))
{
// Initialize verification operation
rv = pkcs11.C_VerifyInit(session, ref mechanism, pubKeyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Prepare buffer for source data part
// Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long
byte[] part = new byte[8];
// Read input stream with source data
int bytesRead = 0;
while ((bytesRead = inputStream.Read(part, 0, part.Length)) > 0)
{
// Process each individual source data part
rv = pkcs11.C_VerifyUpdate(session, part, Convert.ToUInt32(bytesRead));
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
}
// Verify signature
rv = pkcs11.C_VerifyFinal(session, signature, Convert.ToUInt32(signature.Length));
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
}
// Do something interesting with verification result
rv = pkcs11.C_DestroyObject(session, privKeyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11.C_DestroyObject(session, pubKeyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11.C_Logout(session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11.C_CloseSession(session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11.C_Finalize(IntPtr.Zero);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
}
}
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
Copyright (C) 2011 Peter Gill <peter@majorsilence.com>
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.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Xml;
using System.Globalization;
using fyiReporting.RdlDesign.Resources;
namespace fyiReporting.RdlDesign
{
/// <summary>
/// Summary description for StyleCtl.
/// </summary>
internal class StyleTextCtl : System.Windows.Forms.UserControl, IProperty
{
private List<XmlNode> _ReportItems;
private DesignXmlDraw _Draw;
private string _DataSetName;
private bool fHorzAlign, fFormat, fDirection, fWritingMode, fTextDecoration;
private bool fColor, fVerticalAlign, fFontStyle, fFontWeight, fFontSize, fFontFamily;
private bool fValue;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.Label lFont;
private System.Windows.Forms.Button bFont;
private System.Windows.Forms.ComboBox cbHorzAlign;
private System.Windows.Forms.ComboBox cbFormat;
private System.Windows.Forms.ComboBox cbDirection;
private System.Windows.Forms.ComboBox cbWritingMode;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.ComboBox cbTextDecoration;
private System.Windows.Forms.Button bColor;
private System.Windows.Forms.Label label9;
private System.Windows.Forms.ComboBox cbColor;
private System.Windows.Forms.ComboBox cbVerticalAlign;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.ComboBox cbFontStyle;
private System.Windows.Forms.ComboBox cbFontWeight;
private System.Windows.Forms.Label label10;
private System.Windows.Forms.ComboBox cbFontSize;
private System.Windows.Forms.Label label11;
private System.Windows.Forms.ComboBox cbFontFamily;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.Label lblValue;
private ComboBox cbValue;
private System.Windows.Forms.Button bValueExpr;
private System.Windows.Forms.Button bFamily;
private System.Windows.Forms.Button bStyle;
private System.Windows.Forms.Button bColorEx;
private System.Windows.Forms.Button bSize;
private System.Windows.Forms.Button bWeight;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Button bAlignment;
private System.Windows.Forms.Button bDirection;
private System.Windows.Forms.Button bVertical;
private System.Windows.Forms.Button bWrtMode;
private System.Windows.Forms.Button bFormat;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
internal StyleTextCtl(DesignXmlDraw dxDraw, List<XmlNode> styles, PropertyDialog myDialog)
{
_ReportItems = styles;
_Draw = dxDraw;
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
// Initialize form using the style node values
InitTextStyles();
myDialog.Shown += MyDialog_Shown;
}
private void MyDialog_Shown(object sender, EventArgs e)
{
cbValue.Focus();
}
private void InitTextStyles()
{
cbColor.Items.AddRange(StaticLists.ColorList);
XmlNode sNode = _ReportItems[0];
if (_ReportItems.Count > 1)
{
cbValue.Text = Strings.PositionCtl_InitValues_GroupSelected;
cbValue.Enabled = false;
lblValue.Enabled = false;
}
else if (sNode.Name == "Textbox")
{
XmlNode vNode = _Draw.GetNamedChildNode(sNode, "Value");
if (vNode != null)
cbValue.Text = vNode.InnerText;
// now populate the combo box
// Find the dataregion that contains the Textbox (if any)
for (XmlNode pNode = sNode.ParentNode; pNode != null; pNode = pNode.ParentNode)
{
if (pNode.Name == "List" ||
pNode.Name == "Table" ||
pNode.Name == "Matrix" ||
pNode.Name == "Chart")
{
_DataSetName = _Draw.GetDataSetNameValue(pNode);
if (_DataSetName != null) // found it
{
string[] f = _Draw.GetFields(_DataSetName, true);
if (f != null)
cbValue.Items.AddRange(f);
}
}
}
// parameters
string[] ps = _Draw.GetReportParameters(true);
if (ps != null)
cbValue.Items.AddRange(ps);
// globals
cbValue.Items.AddRange(StaticLists.GlobalList);
}
else if (sNode.Name == "Title" || sNode.Name == "fyi:Title2" || sNode.Name == "Title2")// 20022008 AJM GJL
{
lblValue.Text = Strings.StyleTextCtl_InitTextStyles_Caption; // Note: label needs to equal the element name
XmlNode vNode = _Draw.GetNamedChildNode(sNode, "Caption");
if (vNode != null)
cbValue.Text = vNode.InnerText;
}
else
{
lblValue.Visible = false;
cbValue.Visible = false;
bValueExpr.Visible = false;
}
sNode = _Draw.GetNamedChildNode(sNode, "Style");
string sFontStyle="Normal";
string sFontFamily="Arial";
string sFontWeight="Normal";
string sFontSize="10pt";
string sTextDecoration="None";
string sHorzAlign="General";
string sVerticalAlign="Top";
string sColor="Black";
string sFormat="";
string sDirection="LTR";
string sWritingMode="lr-tb";
foreach (XmlNode lNode in sNode)
{
if (lNode.NodeType != XmlNodeType.Element)
continue;
switch (lNode.Name)
{
case "FontStyle":
sFontStyle = lNode.InnerText;
break;
case "FontFamily":
sFontFamily = lNode.InnerText;
break;
case "FontWeight":
sFontWeight = lNode.InnerText;
break;
case "FontSize":
sFontSize = lNode.InnerText;
break;
case "TextDecoration":
sTextDecoration = lNode.InnerText;
break;
case "TextAlign":
sHorzAlign = lNode.InnerText;
break;
case "VerticalAlign":
sVerticalAlign = lNode.InnerText;
break;
case "Color":
sColor = lNode.InnerText;
break;
case "Format":
sFormat = lNode.InnerText;
break;
case "Direction":
sDirection = lNode.InnerText;
break;
case "WritingMode":
sWritingMode = lNode.InnerText;
break;
}
}
// Population Font Family dropdown
foreach (FontFamily ff in FontFamily.Families)
{
cbFontFamily.Items.Add(ff.Name);
}
this.cbFontStyle.Text = sFontStyle;
this.cbFontFamily.Text = sFontFamily;
this.cbFontWeight.Text = sFontWeight;
this.cbFontSize.Text = sFontSize;
this.cbTextDecoration.Text = sTextDecoration;
this.cbHorzAlign.Text = sHorzAlign;
this.cbVerticalAlign.Text = sVerticalAlign;
this.cbColor.Text = sColor;
this.cbFormat.Text = sFormat;
this.cbDirection.Text = sDirection;
this.cbWritingMode.Text = sWritingMode;
fHorzAlign = fFormat = fDirection = fWritingMode = fTextDecoration =
fColor = fVerticalAlign = fFontStyle = fFontWeight = fFontSize = fFontFamily =
fValue = false;
return;
}
/// <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()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(StyleTextCtl));
this.label4 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.label6 = new System.Windows.Forms.Label();
this.label7 = new System.Windows.Forms.Label();
this.label8 = new System.Windows.Forms.Label();
this.lFont = new System.Windows.Forms.Label();
this.bFont = new System.Windows.Forms.Button();
this.cbVerticalAlign = new System.Windows.Forms.ComboBox();
this.cbHorzAlign = new System.Windows.Forms.ComboBox();
this.cbFormat = new System.Windows.Forms.ComboBox();
this.cbDirection = new System.Windows.Forms.ComboBox();
this.cbWritingMode = new System.Windows.Forms.ComboBox();
this.label2 = new System.Windows.Forms.Label();
this.cbTextDecoration = new System.Windows.Forms.ComboBox();
this.bColor = new System.Windows.Forms.Button();
this.label9 = new System.Windows.Forms.Label();
this.cbColor = new System.Windows.Forms.ComboBox();
this.label3 = new System.Windows.Forms.Label();
this.cbFontStyle = new System.Windows.Forms.ComboBox();
this.cbFontWeight = new System.Windows.Forms.ComboBox();
this.label10 = new System.Windows.Forms.Label();
this.cbFontSize = new System.Windows.Forms.ComboBox();
this.label11 = new System.Windows.Forms.Label();
this.cbFontFamily = new System.Windows.Forms.ComboBox();
this.lblValue = new System.Windows.Forms.Label();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.button2 = new System.Windows.Forms.Button();
this.bWeight = new System.Windows.Forms.Button();
this.bSize = new System.Windows.Forms.Button();
this.bColorEx = new System.Windows.Forms.Button();
this.bStyle = new System.Windows.Forms.Button();
this.bFamily = new System.Windows.Forms.Button();
this.cbValue = new System.Windows.Forms.ComboBox();
this.bValueExpr = new System.Windows.Forms.Button();
this.bAlignment = new System.Windows.Forms.Button();
this.bDirection = new System.Windows.Forms.Button();
this.bVertical = new System.Windows.Forms.Button();
this.bWrtMode = new System.Windows.Forms.Button();
this.bFormat = new System.Windows.Forms.Button();
this.groupBox1.SuspendLayout();
this.SuspendLayout();
//
// label4
//
resources.ApplyResources(this.label4, "label4");
this.label4.Name = "label4";
//
// label5
//
resources.ApplyResources(this.label5, "label5");
this.label5.Name = "label5";
//
// label6
//
resources.ApplyResources(this.label6, "label6");
this.label6.Name = "label6";
//
// label7
//
resources.ApplyResources(this.label7, "label7");
this.label7.Name = "label7";
//
// label8
//
resources.ApplyResources(this.label8, "label8");
this.label8.Name = "label8";
//
// lFont
//
resources.ApplyResources(this.lFont, "lFont");
this.lFont.Name = "lFont";
//
// bFont
//
resources.ApplyResources(this.bFont, "bFont");
this.bFont.Name = "bFont";
this.bFont.Click += new System.EventHandler(this.bFont_Click);
//
// cbVerticalAlign
//
this.cbVerticalAlign.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbVerticalAlign.Items.AddRange(new object[] {
resources.GetString("cbVerticalAlign.Items"),
resources.GetString("cbVerticalAlign.Items1"),
resources.GetString("cbVerticalAlign.Items2")});
resources.ApplyResources(this.cbVerticalAlign, "cbVerticalAlign");
this.cbVerticalAlign.Name = "cbVerticalAlign";
this.cbVerticalAlign.SelectedIndexChanged += new System.EventHandler(this.cbVerticalAlign_TextChanged);
this.cbVerticalAlign.TextChanged += new System.EventHandler(this.cbVerticalAlign_TextChanged);
//
// cbHorzAlign
//
this.cbHorzAlign.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbHorzAlign.Items.AddRange(new object[] {
resources.GetString("cbHorzAlign.Items"),
resources.GetString("cbHorzAlign.Items1"),
resources.GetString("cbHorzAlign.Items2"),
resources.GetString("cbHorzAlign.Items3"),
resources.GetString("cbHorzAlign.Items4")});
resources.ApplyResources(this.cbHorzAlign, "cbHorzAlign");
this.cbHorzAlign.Name = "cbHorzAlign";
this.cbHorzAlign.SelectedIndexChanged += new System.EventHandler(this.cbHorzAlign_TextChanged);
this.cbHorzAlign.TextChanged += new System.EventHandler(this.cbHorzAlign_TextChanged);
//
// cbFormat
//
this.cbFormat.Items.AddRange(new object[] {
resources.GetString("cbFormat.Items"),
resources.GetString("cbFormat.Items1"),
resources.GetString("cbFormat.Items2"),
resources.GetString("cbFormat.Items3"),
resources.GetString("cbFormat.Items4"),
resources.GetString("cbFormat.Items5"),
resources.GetString("cbFormat.Items6"),
resources.GetString("cbFormat.Items7"),
resources.GetString("cbFormat.Items8"),
resources.GetString("cbFormat.Items9"),
resources.GetString("cbFormat.Items10"),
resources.GetString("cbFormat.Items11"),
resources.GetString("cbFormat.Items12"),
resources.GetString("cbFormat.Items13"),
resources.GetString("cbFormat.Items14"),
resources.GetString("cbFormat.Items15"),
resources.GetString("cbFormat.Items16"),
resources.GetString("cbFormat.Items17"),
resources.GetString("cbFormat.Items18"),
resources.GetString("cbFormat.Items19")});
resources.ApplyResources(this.cbFormat, "cbFormat");
this.cbFormat.Name = "cbFormat";
this.cbFormat.TextChanged += new System.EventHandler(this.cbFormat_TextChanged);
//
// cbDirection
//
this.cbDirection.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbDirection.Items.AddRange(new object[] {
resources.GetString("cbDirection.Items"),
resources.GetString("cbDirection.Items1")});
resources.ApplyResources(this.cbDirection, "cbDirection");
this.cbDirection.Name = "cbDirection";
this.cbDirection.SelectedIndexChanged += new System.EventHandler(this.cbDirection_TextChanged);
this.cbDirection.TextChanged += new System.EventHandler(this.cbDirection_TextChanged);
//
// cbWritingMode
//
this.cbWritingMode.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbWritingMode.Items.AddRange(new object[] {
resources.GetString("cbWritingMode.Items"),
resources.GetString("cbWritingMode.Items1")});
resources.ApplyResources(this.cbWritingMode, "cbWritingMode");
this.cbWritingMode.Name = "cbWritingMode";
this.cbWritingMode.SelectedIndexChanged += new System.EventHandler(this.cbWritingMode_TextChanged);
this.cbWritingMode.TextChanged += new System.EventHandler(this.cbWritingMode_TextChanged);
//
// label2
//
resources.ApplyResources(this.label2, "label2");
this.label2.Name = "label2";
//
// cbTextDecoration
//
this.cbTextDecoration.Items.AddRange(new object[] {
resources.GetString("cbTextDecoration.Items"),
resources.GetString("cbTextDecoration.Items1"),
resources.GetString("cbTextDecoration.Items2"),
resources.GetString("cbTextDecoration.Items3")});
resources.ApplyResources(this.cbTextDecoration, "cbTextDecoration");
this.cbTextDecoration.Name = "cbTextDecoration";
this.cbTextDecoration.SelectedIndexChanged += new System.EventHandler(this.cbTextDecoration_TextChanged);
this.cbTextDecoration.TextChanged += new System.EventHandler(this.cbTextDecoration_TextChanged);
//
// bColor
//
resources.ApplyResources(this.bColor, "bColor");
this.bColor.Name = "bColor";
this.bColor.Click += new System.EventHandler(this.bColor_Click);
//
// label9
//
resources.ApplyResources(this.label9, "label9");
this.label9.Name = "label9";
//
// cbColor
//
resources.ApplyResources(this.cbColor, "cbColor");
this.cbColor.Name = "cbColor";
this.cbColor.TextChanged += new System.EventHandler(this.cbColor_TextChanged);
//
// label3
//
resources.ApplyResources(this.label3, "label3");
this.label3.Name = "label3";
//
// cbFontStyle
//
this.cbFontStyle.Items.AddRange(new object[] {
resources.GetString("cbFontStyle.Items"),
resources.GetString("cbFontStyle.Items1")});
resources.ApplyResources(this.cbFontStyle, "cbFontStyle");
this.cbFontStyle.Name = "cbFontStyle";
this.cbFontStyle.TextChanged += new System.EventHandler(this.cbFontStyle_TextChanged);
//
// cbFontWeight
//
this.cbFontWeight.Items.AddRange(new object[] {
resources.GetString("cbFontWeight.Items"),
resources.GetString("cbFontWeight.Items1"),
resources.GetString("cbFontWeight.Items2"),
resources.GetString("cbFontWeight.Items3"),
resources.GetString("cbFontWeight.Items4"),
resources.GetString("cbFontWeight.Items5"),
resources.GetString("cbFontWeight.Items6"),
resources.GetString("cbFontWeight.Items7"),
resources.GetString("cbFontWeight.Items8"),
resources.GetString("cbFontWeight.Items9"),
resources.GetString("cbFontWeight.Items10"),
resources.GetString("cbFontWeight.Items11"),
resources.GetString("cbFontWeight.Items12")});
resources.ApplyResources(this.cbFontWeight, "cbFontWeight");
this.cbFontWeight.Name = "cbFontWeight";
this.cbFontWeight.TextChanged += new System.EventHandler(this.cbFontWeight_TextChanged);
//
// label10
//
resources.ApplyResources(this.label10, "label10");
this.label10.Name = "label10";
//
// cbFontSize
//
this.cbFontSize.Items.AddRange(new object[] {
resources.GetString("cbFontSize.Items"),
resources.GetString("cbFontSize.Items1"),
resources.GetString("cbFontSize.Items2"),
resources.GetString("cbFontSize.Items3"),
resources.GetString("cbFontSize.Items4"),
resources.GetString("cbFontSize.Items5"),
resources.GetString("cbFontSize.Items6"),
resources.GetString("cbFontSize.Items7"),
resources.GetString("cbFontSize.Items8"),
resources.GetString("cbFontSize.Items9"),
resources.GetString("cbFontSize.Items10"),
resources.GetString("cbFontSize.Items11"),
resources.GetString("cbFontSize.Items12"),
resources.GetString("cbFontSize.Items13"),
resources.GetString("cbFontSize.Items14"),
resources.GetString("cbFontSize.Items15")});
resources.ApplyResources(this.cbFontSize, "cbFontSize");
this.cbFontSize.Name = "cbFontSize";
this.cbFontSize.TextChanged += new System.EventHandler(this.cbFontSize_TextChanged);
//
// label11
//
resources.ApplyResources(this.label11, "label11");
this.label11.Name = "label11";
//
// cbFontFamily
//
this.cbFontFamily.Items.AddRange(new object[] {
resources.GetString("cbFontFamily.Items")});
resources.ApplyResources(this.cbFontFamily, "cbFontFamily");
this.cbFontFamily.Name = "cbFontFamily";
this.cbFontFamily.TextChanged += new System.EventHandler(this.cbFontFamily_TextChanged);
//
// lblValue
//
resources.ApplyResources(this.lblValue, "lblValue");
this.lblValue.Name = "lblValue";
//
// groupBox1
//
this.groupBox1.Controls.Add(this.cbTextDecoration);
this.groupBox1.Controls.Add(this.cbFontFamily);
this.groupBox1.Controls.Add(this.button2);
this.groupBox1.Controls.Add(this.bWeight);
this.groupBox1.Controls.Add(this.bSize);
this.groupBox1.Controls.Add(this.bColorEx);
this.groupBox1.Controls.Add(this.bStyle);
this.groupBox1.Controls.Add(this.bFamily);
this.groupBox1.Controls.Add(this.lFont);
this.groupBox1.Controls.Add(this.bFont);
this.groupBox1.Controls.Add(this.label2);
this.groupBox1.Controls.Add(this.bColor);
this.groupBox1.Controls.Add(this.label9);
this.groupBox1.Controls.Add(this.cbColor);
this.groupBox1.Controls.Add(this.label3);
this.groupBox1.Controls.Add(this.cbFontStyle);
this.groupBox1.Controls.Add(this.cbFontWeight);
this.groupBox1.Controls.Add(this.label10);
this.groupBox1.Controls.Add(this.cbFontSize);
this.groupBox1.Controls.Add(this.label11);
resources.ApplyResources(this.groupBox1, "groupBox1");
this.groupBox1.Name = "groupBox1";
this.groupBox1.TabStop = false;
//
// button2
//
resources.ApplyResources(this.button2, "button2");
this.button2.Name = "button2";
this.button2.Tag = "decoration";
this.button2.Click += new System.EventHandler(this.bExpr_Click);
//
// bWeight
//
resources.ApplyResources(this.bWeight, "bWeight");
this.bWeight.Name = "bWeight";
this.bWeight.Tag = "weight";
this.bWeight.Click += new System.EventHandler(this.bExpr_Click);
//
// bSize
//
resources.ApplyResources(this.bSize, "bSize");
this.bSize.Name = "bSize";
this.bSize.Tag = "size";
this.bSize.Click += new System.EventHandler(this.bExpr_Click);
//
// bColorEx
//
resources.ApplyResources(this.bColorEx, "bColorEx");
this.bColorEx.Name = "bColorEx";
this.bColorEx.Tag = "color";
this.bColorEx.Click += new System.EventHandler(this.bExpr_Click);
//
// bStyle
//
resources.ApplyResources(this.bStyle, "bStyle");
this.bStyle.Name = "bStyle";
this.bStyle.Tag = "style";
this.bStyle.Click += new System.EventHandler(this.bExpr_Click);
//
// bFamily
//
resources.ApplyResources(this.bFamily, "bFamily");
this.bFamily.Name = "bFamily";
this.bFamily.Tag = "family";
this.bFamily.Click += new System.EventHandler(this.bExpr_Click);
//
// cbValue
//
resources.ApplyResources(this.cbValue, "cbValue");
this.cbValue.Name = "cbValue";
this.cbValue.TextChanged += new System.EventHandler(this.cbValue_TextChanged);
//
// bValueExpr
//
resources.ApplyResources(this.bValueExpr, "bValueExpr");
this.bValueExpr.Name = "bValueExpr";
this.bValueExpr.Tag = "value";
this.bValueExpr.Click += new System.EventHandler(this.bExpr_Click);
//
// bAlignment
//
resources.ApplyResources(this.bAlignment, "bAlignment");
this.bAlignment.Name = "bAlignment";
this.bAlignment.Tag = "halign";
this.bAlignment.Click += new System.EventHandler(this.bExpr_Click);
//
// bDirection
//
resources.ApplyResources(this.bDirection, "bDirection");
this.bDirection.Name = "bDirection";
this.bDirection.Tag = "direction";
this.bDirection.Click += new System.EventHandler(this.bExpr_Click);
//
// bVertical
//
resources.ApplyResources(this.bVertical, "bVertical");
this.bVertical.Name = "bVertical";
this.bVertical.Tag = "valign";
this.bVertical.Click += new System.EventHandler(this.bExpr_Click);
//
// bWrtMode
//
resources.ApplyResources(this.bWrtMode, "bWrtMode");
this.bWrtMode.Name = "bWrtMode";
this.bWrtMode.Tag = "writing";
this.bWrtMode.Click += new System.EventHandler(this.bExpr_Click);
//
// bFormat
//
resources.ApplyResources(this.bFormat, "bFormat");
this.bFormat.Name = "bFormat";
this.bFormat.Tag = "format";
this.bFormat.Click += new System.EventHandler(this.bExpr_Click);
//
// StyleTextCtl
//
this.Controls.Add(this.bFormat);
this.Controls.Add(this.bWrtMode);
this.Controls.Add(this.bVertical);
this.Controls.Add(this.bDirection);
this.Controls.Add(this.bAlignment);
this.Controls.Add(this.bValueExpr);
this.Controls.Add(this.cbValue);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.lblValue);
this.Controls.Add(this.cbWritingMode);
this.Controls.Add(this.cbDirection);
this.Controls.Add(this.cbFormat);
this.Controls.Add(this.cbHorzAlign);
this.Controls.Add(this.cbVerticalAlign);
this.Controls.Add(this.label8);
this.Controls.Add(this.label7);
this.Controls.Add(this.label6);
this.Controls.Add(this.label5);
this.Controls.Add(this.label4);
this.Name = "StyleTextCtl";
resources.ApplyResources(this, "$this");
this.groupBox1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
public bool IsValid()
{
if (fFontSize)
{
try
{
if (!cbFontSize.Text.Trim().StartsWith("="))
DesignerUtility.ValidateSize(cbFontSize.Text, false, false);
}
catch (Exception e)
{
MessageBox.Show(e.Message, Strings.StyleTextCtl_Show_InvalidFontSize);
return false;
}
}
return true;
}
public void Apply()
{
// take information in control and apply to all the style nodes
// Only change information that has been marked as modified;
// this way when group is selected it is possible to change just
// the items you want and keep the rest the same.
foreach (XmlNode riNode in this._ReportItems)
ApplyChanges(riNode);
fHorzAlign = fFormat = fDirection = fWritingMode = fTextDecoration =
fColor = fVerticalAlign = fFontStyle = fFontWeight = fFontSize = fFontFamily =
fValue = false;
}
public void ApplyChanges(XmlNode node)
{
if (cbValue.Enabled)
{
if (fValue)
_Draw.SetElement(node, "Value", cbValue.Text); // only adjust value when single item selected
}
XmlNode sNode = _Draw.GetNamedChildNode(node, "Style");
if (fFontStyle)
_Draw.SetElement(sNode, "FontStyle", cbFontStyle.Text);
if (fFontFamily)
_Draw.SetElement(sNode, "FontFamily", cbFontFamily.Text);
if (fFontWeight)
_Draw.SetElement(sNode, "FontWeight", cbFontWeight.Text);
if (fFontSize)
{
float size=10;
size = DesignXmlDraw.GetSize(cbFontSize.Text);
if (size <= 0)
{
size = DesignXmlDraw.GetSize(cbFontSize.Text+"pt"); // Try assuming pt
if (size <= 0) // still no good
size = 10; // just set default value
}
string rs = string.Format(NumberFormatInfo.InvariantInfo, "{0:0.#}pt", size);
_Draw.SetElement(sNode, "FontSize", rs); // force to string
}
if (fTextDecoration)
_Draw.SetElement(sNode, "TextDecoration", cbTextDecoration.Text);
if (fHorzAlign)
_Draw.SetElement(sNode, "TextAlign", cbHorzAlign.Text);
if (fVerticalAlign)
_Draw.SetElement(sNode, "VerticalAlign", cbVerticalAlign.Text);
if (fColor)
_Draw.SetElement(sNode, "Color", cbColor.Text);
if (fFormat)
{
if (cbFormat.Text.Length == 0) // Don't put out a format if no format value
_Draw.RemoveElement(sNode, "Format");
else
_Draw.SetElement(sNode, "Format", cbFormat.Text);
}
if (fDirection)
_Draw.SetElement(sNode, "Direction", cbDirection.Text);
if (fWritingMode)
_Draw.SetElement(sNode, "WritingMode", cbWritingMode.Text);
return;
}
private void bFont_Click(object sender, System.EventArgs e)
{
FontDialog fd = new FontDialog();
fd.ShowColor = true;
// STYLE
System.Drawing.FontStyle fs = 0;
if (cbFontStyle.Text == "Italic")
fs |= System.Drawing.FontStyle.Italic;
if (cbTextDecoration.Text == "Underline")
fs |= FontStyle.Underline;
else if (cbTextDecoration.Text == "LineThrough")
fs |= FontStyle.Strikeout;
// WEIGHT
switch (cbFontWeight.Text)
{
case "Bold":
case "Bolder":
case "500":
case "600":
case "700":
case "800":
case "900":
fs |= System.Drawing.FontStyle.Bold;
break;
default:
break;
}
float size=10;
size = DesignXmlDraw.GetSize(cbFontSize.Text);
if (size <= 0)
{
size = DesignXmlDraw.GetSize(cbFontSize.Text+"pt"); // Try assuming pt
if (size <= 0) // still no good
size = 10; // just set default value
}
Font drawFont = new Font(cbFontFamily.Text, size, fs); // si.FontSize already in points
fd.Font = drawFont;
fd.Color =
DesignerUtility.ColorFromHtml(cbColor.Text, System.Drawing.Color.Black);
try
{
DialogResult dr = fd.ShowDialog();
if (dr != DialogResult.OK)
{
drawFont.Dispose();
return;
}
// Apply all the font info
cbFontWeight.Text = fd.Font.Bold ? "Bold" : "Normal";
cbFontStyle.Text = fd.Font.Italic ? "Italic" : "Normal";
cbFontFamily.Text = fd.Font.FontFamily.Name;
cbFontSize.Text = fd.Font.Size.ToString() + "pt";
cbColor.Text = ColorTranslator.ToHtml(fd.Color);
if (fd.Font.Underline)
this.cbTextDecoration.Text = "Underline";
else if (fd.Font.Strikeout)
this.cbTextDecoration.Text = "LineThrough";
else
this.cbTextDecoration.Text = "None";
drawFont.Dispose();
}
finally
{
fd.Dispose();
}
return;
}
private void bColor_Click(object sender, System.EventArgs e)
{
using (ColorDialog cd = new ColorDialog())
{
cd.AnyColor = true;
cd.FullOpen = true;
cd.CustomColors = RdlDesigner.GetCustomColors();
cd.Color =
DesignerUtility.ColorFromHtml(cbColor.Text, System.Drawing.Color.Black);
if (cd.ShowDialog() != DialogResult.OK)
return;
RdlDesigner.SetCustomColors(cd.CustomColors);
if (sender == this.bColor)
cbColor.Text = ColorTranslator.ToHtml(cd.Color);
}
return;
}
private void cbValue_TextChanged(object sender, System.EventArgs e)
{
fValue = true;
}
private void cbFontFamily_TextChanged(object sender, System.EventArgs e)
{
fFontFamily = true;
}
private void cbFontSize_TextChanged(object sender, System.EventArgs e)
{
fFontSize = true;
}
private void cbFontStyle_TextChanged(object sender, System.EventArgs e)
{
fFontStyle = true;
}
private void cbFontWeight_TextChanged(object sender, System.EventArgs e)
{
fFontWeight = true;
}
private void cbColor_TextChanged(object sender, System.EventArgs e)
{
fColor = true;
}
private void cbTextDecoration_TextChanged(object sender, System.EventArgs e)
{
fTextDecoration = true;
}
private void cbHorzAlign_TextChanged(object sender, System.EventArgs e)
{
fHorzAlign = true;
}
private void cbVerticalAlign_TextChanged(object sender, System.EventArgs e)
{
fVerticalAlign = true;
}
private void cbDirection_TextChanged(object sender, System.EventArgs e)
{
fDirection = true;
}
private void cbWritingMode_TextChanged(object sender, System.EventArgs e)
{
fWritingMode = true;
}
private void cbFormat_TextChanged(object sender, System.EventArgs e)
{
fFormat = true;
}
private void bExpr_Click(object sender, System.EventArgs e)
{
Button b = sender as Button;
if (b == null)
return;
Control c = null;
bool bColor=false;
switch (b.Tag as string)
{
case "value":
c = cbValue;
break;
case "family":
c = cbFontFamily;
break;
case "style":
c = cbFontStyle;
break;
case "color":
c = cbColor;
bColor = true;
break;
case "size":
c = cbFontSize;
break;
case "weight":
c = cbFontWeight;
break;
case "decoration":
c = cbTextDecoration;
break;
case "halign":
c = cbHorzAlign;
break;
case "valign":
c = cbVerticalAlign;
break;
case "direction":
c = cbDirection;
break;
case "writing":
c = cbWritingMode;
break;
case "format":
c = cbFormat;
break;
}
if (c == null)
return;
XmlNode sNode = _ReportItems[0];
using (DialogExprEditor ee = new DialogExprEditor(_Draw, c.Text, sNode, bColor))
{
DialogResult dr = ee.ShowDialog();
if (dr == DialogResult.OK)
c.Text = ee.Expression;
}
return;
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.AzureStack.Management;
using Microsoft.AzureStack.Management.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.AzureStack.Management
{
/// <summary>
/// Operations on the curation items (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXX.aspx for
/// more information)
/// </summary>
internal partial class CurationOperations : IServiceOperations<AzureStackClient>, ICurationOperations
{
/// <summary>
/// Initializes a new instance of the CurationOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal CurationOperations(AzureStackClient client)
{
this._client = client;
}
private AzureStackClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.AzureStack.Management.AzureStackClient.
/// </summary>
public AzureStackClient Client
{
get { return this._client; }
}
/// <summary>
/// Lists the curation results
/// </summary>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Result of the curation list operation
/// </returns>
public async Task<CurationListResult> ListAsync(CancellationToken cancellationToken)
{
// Validate
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/providers/Microsoft.Gallery/Curation";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=" + Uri.EscapeDataString(this.Client.ApiVersion));
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
CurationListResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new CurationListResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken curationItemsArray = responseDoc;
if (curationItemsArray != null && curationItemsArray.Type != JTokenType.Null)
{
foreach (JToken curationItemsValue in ((JArray)curationItemsArray))
{
CurationItem curationItemInstance = new CurationItem();
result.CurationItems.Add(curationItemInstance);
JToken identityValue = curationItemsValue["identity"];
if (identityValue != null && identityValue.Type != JTokenType.Null)
{
string identityInstance = ((string)identityValue);
curationItemInstance.Identity = identityInstance;
}
JToken itemUriValue = curationItemsValue["itemUri"];
if (itemUriValue != null && itemUriValue.Type != JTokenType.Null)
{
string itemUriInstance = ((string)itemUriValue);
curationItemInstance.ItemUri = itemUriInstance;
}
JToken isDefaultValue = curationItemsValue["isDefault"];
if (isDefaultValue != null && isDefaultValue.Type != JTokenType.Null)
{
bool isDefaultInstance = ((bool)isDefaultValue);
curationItemInstance.IsDefault = isDefaultInstance;
}
}
}
}
}
result.StatusCode = statusCode;
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
// InstallModule.cs
//
using System;
using System.Collections.Generic;
using System.Html;
using System.Runtime.CompilerServices;
using afung.MangaWeb3.Client.Install.Modal;
using afung.MangaWeb3.Client.Modal;
using afung.MangaWeb3.Client.Module;
using afung.MangaWeb3.Common;
using jQueryApi;
namespace afung.MangaWeb3.Client.Install.Module
{
public class InstallModule : ModuleBase
{
private bool _canEnableZip = false;
private bool CanEnableZip
{
get
{
return _canEnableZip;
}
set
{
if (value)
{
jQuery.Select("#install-zip-checkbox", attachedObject).RemoveAttr("disabled");
}
else
{
jQuery.Select("#install-zip-checkbox", attachedObject)
.Attribute("disabled", "disabled")
.RemoveAttr("checked");
}
_canEnableZip = value;
}
}
private bool _canEnableRar = false;
private bool CanEnableRar
{
get
{
return _canEnableRar;
}
set
{
if (value)
{
jQuery.Select("#install-rar-checkbox", attachedObject).RemoveAttr("disabled");
}
else
{
jQuery.Select("#install-rar-checkbox", attachedObject)
.Attribute("disabled", "disabled")
.RemoveAttr("checked");
}
_canEnableRar = value;
}
}
private bool _canEnablePdf = false;
private bool CanEnablePdf
{
get
{
return _canEnablePdf;
}
set
{
if (value)
{
jQuery.Select("#install-pdf-checkbox", attachedObject).RemoveAttr("disabled");
}
else
{
jQuery.Select("#install-pdf-checkbox", attachedObject)
.Attribute("disabled", "disabled")
.RemoveAttr("checked");
}
_canEnablePdf = value;
}
}
private bool AllRequiredComponentLoaded;
private static InstallModule _instance = null;
public static InstallModule Instance
{
get
{
if (_instance == null)
{
_instance = new InstallModule();
}
return _instance;
}
}
private InstallModule()
: base("install", "install-module")
{
jQuery.Select("#install-form").Hide();
jQuery.Select("#install-language").Change(LanguageChange);
}
protected override void OnShow()
{
Request.Send(new PreInstallCheckRequest(), OnPreInstallCheckRequestFinished);
jQuery.Select("#install-language").Value(Settings.UserLanguage);
}
[AlternateSignature]
private extern void OnPreInstallCheckRequestFinished(JsonResponse response);
private void OnPreInstallCheckRequestFinished(PreInstallCheckResponse response)
{
if (response.installed)
{
// switch to install finish module
return;
}
jQuery.Select("#install-preinstall-check").Hide();
jQuery.Select("#install-form").Show();
jQuery.Select("#install-mysql-check").Hide();
jQuery.Select("#install-mysql-loading").Hide();
jQuery.Select("#install-sevenzip-check").Hide();
jQuery.Select("#install-sevenzip-loading").Hide();
jQuery.Select("#install-admin-username-check").Hide();
jQuery.Select("#install-admin-password-check").Hide();
jQuery.Select("#install-admin-password2-check").Hide();
if (Environment.ServerType == ServerType.AspNet)
{
CanEnableZip = CanEnableRar = false;
CanEnablePdf = AllRequiredComponentLoaded = true;
// other components text input
jQuery.Select("#install-sevenzip-dll").Change(OtherComponentInputChanged);
}
else
{
jQuery.Select("#install-sevenzip").Hide();
CanEnableZip = response.zip;
CanEnableRar = response.rar;
CanEnablePdf = response.pdfinfo && response.pdfdraw;
AllRequiredComponentLoaded = response.mySql && response.gd;
if (!response.mySql)
{
Template.Get("install", "install-mysql-error").AppendTo(jQuery.Select("#mysql-error-area"));
}
if (!response.gd)
{
Template.Get("install", "install-gd-error").AppendTo(jQuery.Select("#gd-error-area"));
}
if (!response.zip)
{
Template.Get("install", "install-zip-error").AppendTo(jQuery.Select("#zip-error-area"));
}
if (!response.rar)
{
Template.Get("install", "install-rar-error").AppendTo(jQuery.Select("#rar-error-area"));
}
if (!response.pdfinfo)
{
Template.Get("install", "install-pdfinfo-error").AppendTo(jQuery.Select("#pdfinfo-error-area"));
}
if (!response.pdfdraw)
{
Template.Get("install", "install-pdfdraw-error").AppendTo(jQuery.Select("#mudraw-error-area"));
}
}
// MySql text inputs and button
jQuery.Select("#install-mysql-check-setting").Click(MySqlCheckSettingClicked);
jQuery.Select("#install-mysql-server").Change(MySqlCheckSettingChanged);
jQuery.Select("#install-mysql-port").Change(MySqlCheckSettingChanged);
jQuery.Select("#install-mysql-username").Change(MySqlCheckSettingChanged);
jQuery.Select("#install-mysql-password").Change(MySqlCheckSettingChanged);
jQuery.Select("#install-mysql-database").Change(MySqlCheckSettingChanged);
// Admin Section
jQuery.Select("#install-admin-username").Change(AdminUserChanged);
jQuery.Select("#install-admin-password").Change(AdminPasswordChanged);
jQuery.Select("#install-admin-password2").Change(AdminConfirmPasswordChanged);
// Submit button
jQuery.Select("#install-submit-btn").Click(SubmitButtonClicked);
}
private bool _mySqlSettingChecking = false;
private bool MySqlSettingChecking
{
get
{
return _mySqlSettingChecking;
}
set
{
_mySqlSettingChecking = value;
if (value)
{
jQuery.Select("#install-mysql-loading").Show();
}
else
{
jQuery.Select("#install-mysql-loading").Hide();
}
}
}
private bool _mySqlSettingOkay = false;
private bool MySqlSettingOkay
{
get
{
return _mySqlSettingOkay;
}
set
{
_mySqlSettingOkay = value;
if (value)
{
jQuery.Select("#install-mysql-check").Show();
}
else
{
jQuery.Select("#install-mysql-check").Hide();
}
}
}
private void MySqlCheckSettingChanged(jQueryEvent e)
{
MySqlSettingOkay = false;
}
private void MySqlCheckSettingClicked(jQueryEvent e)
{
if (MySqlSettingChecking) return;
string server = jQuery.Select("#install-mysql-server").GetValue();
string portString = jQuery.Select("#install-mysql-port").GetValue();
string username = jQuery.Select("#install-mysql-username").GetValue();
string password = jQuery.Select("#install-mysql-password").GetValue();
string database = jQuery.Select("#install-mysql-database").GetValue();
if (String.IsNullOrEmpty(server) || String.IsNullOrEmpty(portString) || String.IsNullOrEmpty(username) || String.IsNullOrEmpty(database))
{
return;
}
int port = int.Parse(portString, 10);
CheckMySqlSettingRequest request = new CheckMySqlSettingRequest();
request.server = server;
request.port = port;
request.username = username;
request.password = password;
request.database = database;
jQuery.Select("#install-mysql-connect-error").Remove();
MySqlSettingChecking = true;
MySqlSettingOkay = false;
Request.Send(request, MysqlCheckSuccess, MySqlCheckFailed);
}
[AlternateSignature]
private extern void MysqlCheckSuccess(JsonResponse response);
private void MysqlCheckSuccess(CheckMySqlSettingResponse response)
{
MySqlSettingChecking = false;
MySqlSettingOkay = response.pass;
if (!response.pass)
{
MySqlCheckFailed();
}
}
[AlternateSignature]
private extern void MySqlCheckFailed(Exception error);
private void MySqlCheckFailed()
{
MySqlSettingOkay = MySqlSettingChecking = false;
Template.Get("install", "install-mysql-connect-error").AppendTo(jQuery.Select("#mysql-error-area"));
}
private bool _sevenZipSettingChecking = false;
private bool SevenZipSettingChecking
{
get
{
return _sevenZipSettingChecking;
}
set
{
_sevenZipSettingChecking = value;
if (value)
{
jQuery.Select("#install-sevenzip-loading").Show();
jQuery.Select("#install-sevenzip-dll").Attribute("disabled", "disabled");
}
else
{
jQuery.Select("#install-sevenzip-loading").Hide();
jQuery.Select("#install-sevenzip-dll").RemoveAttr("disabled");
}
}
}
private bool _sevenZipSettingOkay = false;
private bool SevenZipSettingOkay
{
get
{
return _sevenZipSettingOkay;
}
set
{
CanEnableZip = CanEnableRar = _sevenZipSettingOkay = value;
if (value)
{
jQuery.Select("#install-sevenzip-check").Show();
}
else
{
jQuery.Select("#install-sevenzip-check").Hide();
}
}
}
private int checkingComponent;
private void OtherComponentInputChanged(jQueryEvent e)
{
jQueryObject eventSource = jQuery.FromElement(e.Target);
string inputId = eventSource.GetAttribute("id");
bool checking = false;
switch (inputId)
{
case "install-sevenzip-dll":
checking = SevenZipSettingChecking;
break;
default:
return;
}
if (checking)
{
return;
}
string path = eventSource.GetValue();
checking = !String.IsNullOrEmpty(path);
CheckOtherComponentRequest request = new CheckOtherComponentRequest();
request.path = path;
switch (inputId)
{
case "install-sevenzip-dll":
SevenZipSettingChecking = checking;
SevenZipSettingOkay = false;
request.component = 0;
jQuery.Select("#install-sevenzip-error").Remove();
break;
default:
return;
}
if (!checking)
{
return;
}
checkingComponent = request.component;
Request.Send(request, OtherComponentCheckSuccess, OtherComponentCheckFailed);
}
[AlternateSignature]
private extern void OtherComponentCheckSuccess(JsonResponse response);
private void OtherComponentCheckSuccess(CheckOtherComponentResponse response)
{
if (response.pass)
{
switch (checkingComponent)
{
case 0:
SevenZipSettingChecking = false;
SevenZipSettingOkay = true;
break;
default:
return;
}
}
else
{
OtherComponentCheckFailed();
}
}
[AlternateSignature]
private extern void OtherComponentCheckFailed(Exception error);
private void OtherComponentCheckFailed()
{
switch (checkingComponent)
{
case 0:
SevenZipSettingOkay = SevenZipSettingChecking = false;
Template.Get("install", "install-sevenzip-error").AppendTo(jQuery.Select("#sevenzip-error-area"));
break;
default:
return;
}
}
private void AdminUserChanged(jQueryEvent e)
{
RegularExpression regex = new RegularExpression("[^a-zA-Z0-9]");
string username = jQuery.Select("#install-admin-username").GetValue();
if (username == "" || regex.Test(username))
{
jQuery.Select("#install-admin-username-check").Hide();
}
else
{
jQuery.Select("#install-admin-username-check").Show();
}
}
private void AdminPasswordChanged(jQueryEvent e)
{
if (jQuery.Select("#install-admin-password").GetValue().Length >= 8)
{
jQuery.Select("#install-admin-password-check").Show();
}
else
{
jQuery.Select("#install-admin-password-check").Hide();
}
}
private void AdminConfirmPasswordChanged(jQueryEvent e)
{
if (jQuery.Select("#install-admin-password2").GetValue().Length >= 8 && jQuery.Select("#install-admin-password").GetValue() == jQuery.Select("#install-admin-password2").GetValue())
{
jQuery.Select("#install-admin-password2-check").Show();
}
else
{
jQuery.Select("#install-admin-password2-check").Hide();
}
}
private void SubmitButtonClicked(jQueryEvent e)
{
// return if anything is checking
if (MySqlSettingChecking || SevenZipSettingChecking)
{
return;
}
if (!AllRequiredComponentLoaded)
{
ErrorModal.ShowError(Strings.Get("MissingRequiredComponent"));
return;
}
if (!CanEnableZip && !CanEnableRar && !CanEnablePdf)
{
ErrorModal.ShowError(Strings.Get("NeedFileSupport"));
return;
}
string username = jQuery.Select("#install-admin-username").GetValue();
string password = jQuery.Select("#install-admin-password").GetValue();
string password2 = jQuery.Select("#install-admin-password2").GetValue();
RegularExpression regex = new RegularExpression("[^a-zA-Z0-9]");
if (username == "" || regex.Test(username) || password.Length < 8 || password != password2)
{
ErrorModal.ShowError(Strings.Get("AdminUserSettingFailed"));
return;
}
InstallRequest request = new InstallRequest();
request.mysqlServer = jQuery.Select("#install-mysql-server").GetValue();
request.mysqlPort = int.Parse(jQuery.Select("#install-mysql-port").GetValue(), 10);
request.mysqlUser = jQuery.Select("#install-mysql-username").GetValue();
request.mysqlPassword = jQuery.Select("#install-mysql-password").GetValue();
request.mysqlDatabase = jQuery.Select("#install-mysql-database").GetValue();
request.sevenZipPath = jQuery.Select("#install-sevenzip-dll").GetValue();
request.zip = jQuery.Select("#install-zip-checkbox").Is(":checked");
request.rar = jQuery.Select("#install-rar-checkbox").Is(":checked");
request.pdf = jQuery.Select("#install-pdf-checkbox").Is(":checked");
request.admin = username;
request.password = password;
request.password2 = password2;
new InstallingModal().SendInstallRequest(request);
}
[AlternateSignature]
private extern void LanguageChange(jQueryEvent e);
private void LanguageChange()
{
string newLanguage = jQuery.Select("#install-language").GetValue();
if (newLanguage != Settings.UserLanguage)
{
Settings.UserLanguage = newLanguage;
Window.Location.Href = "install.html";
}
}
}
}
| |
/*
* XmlParserInputBase.cs - Implementation of the
* "System.Xml.Private.XmlParserInputBase" class.
*
* Copyright (C) 2004 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
*/
namespace System.Xml.Private
{
using System;
using System.Text;
internal abstract class XmlParserInputBase : XmlErrorProcessor
{
// Internal state.
private EOFHandler eofHandler;
private XmlNameTable nameTable;
protected LogManager logger;
// Fields.
public char currChar;
public char peekChar;
// Constructor.
protected XmlParserInputBase
(XmlNameTable nameTable,
EOFHandler eof,
ErrorHandler error)
: base(error)
{
this.nameTable = nameTable;
this.eofHandler = eof;
this.currChar = '\0';
this.peekChar = '\0';
this.logger = new LogManager();
}
// Get or set the end of file handler.
public virtual EOFHandler EOFHandler
{
get { return eofHandler; }
set { eofHandler = value; }
}
// Get the current line number.
public abstract int LineNumber { get; }
// Get the current line position.
public abstract int LinePosition { get; }
// Get the logger.
public virtual LogManager Logger
{
get { return logger; }
}
// Handle the end of file state.
protected virtual void EOF()
{
if(eofHandler != null)
{
eofHandler();
}
}
// Expect the next character to match `expected'.
public virtual void Expect(char expected)
{
if(!NextChar()) { Error("Xml_UnexpectedEOF"); }
if(currChar != expected) { Error(/* TODO */); }
}
// Expect the stream characters to match `expected'.
public virtual void Expect(String expected)
{
int len = expected.Length;
for(int i = 0; i < len; ++i)
{
if(!NextChar()) { Error("Xml_UnexpectedEOF"); }
if(currChar != expected[i]) { Error(/* TODO */); }
}
}
// Move to the next character, returning false on EOF.
public abstract bool NextChar();
// Peek at the next character, returning false on EOF.
public abstract bool PeekChar();
// Read a name, calling Error if there are no valid characters.
public virtual String ReadName()
{
// push a new log
Logger.Push(new StringBuilder());
// require an initial name character
if(!NextChar()) { Error("Xml_UnexpectedEOF"); }
if(!XmlCharInfo.IsNameInit(currChar)) { Error(/* TODO */); }
// read until we consume all the name characters
while(PeekChar() && XmlCharInfo.IsNameChar(peekChar))
{
NextChar();
}
// get the result from the log and pop it from the logger
String result = Logger.Pop().ToString();
// return our result
return nameTable.Add(result);
}
// Read a name token, calling Error if there are no valid characters.
public virtual String ReadNameToken()
{
// push a new log
Logger.Push(new StringBuilder());
// require at least one name character
if(!NextChar()) { Error("Xml_UnexpectedEOF"); }
if(!XmlCharInfo.IsNameChar(currChar)) { Error(/* TODO */); }
// read until we consume all the name characters
while(PeekChar() && XmlCharInfo.IsNameChar(peekChar))
{
NextChar();
}
// get the result from the log and pop it from the logger
String result = Logger.Pop().ToString();
// return our result
return nameTable.Add(result);
}
// Read characters until target, calling Error on EOF.
public virtual String ReadTo(char target)
{
return ReadTo(target, false);
}
public virtual String ReadTo(char target, bool includeTarget)
{
// push a new log
Logger.Push(new StringBuilder());
// read until we hit the target
while(PeekChar() && peekChar != target) { NextChar(); }
// if we didn't hit the target we hit eof, so give an error
if(peekChar != target)
{
Logger.Pop();
Error("Xml_UnexpectedEOF");
}
// check if we should include the target, and do so if need be
if(includeTarget) { NextChar(); }
// get the result from the log and pop it from the logger
String result = Logger.Pop().ToString();
// return our result
return result;
}
// Skip whitespace characters, returning false if nothing is skipped.
public virtual bool SkipWhitespace()
{
bool skipped = false;
while(PeekChar() && XmlCharInfo.IsWhitespace(peekChar))
{
NextChar();
skipped = true;
}
return skipped;
}
public class LogManager
{
// Internal state.
private int top;
private StringBuilder[] logs;
// Constructor.
public LogManager()
{
top = -1;
logs = new StringBuilder[2];
}
// Append the input to the logs.
public void Append(char c)
{
for(int i = 0; i <= top; ++i)
{
logs[i].Append(c);
}
}
public void Append(String s)
{
for(int i = 0; i <= top; ++i)
{
logs[i].Append(s);
}
}
// Clear the log stack.
public void Clear()
{
while(top >= 0)
{
logs[top--] = null;
}
}
// Push a log onto the log stack.
public void Push(StringBuilder sb)
{
if(sb == null) { return; }
++top;
if(top == logs.Length)
{
StringBuilder[] tmp = new StringBuilder[top*2];
Array.Copy(logs, 0, tmp, 0, top);
logs = tmp;
}
logs[top] = sb;
}
// Pop a log off the log stack.
public StringBuilder Pop()
{
StringBuilder tmp = logs[top];
logs[top--] = null;
return tmp;
}
// Peek at the log on top of the log stack.
public StringBuilder Peek()
{
return logs[top];
}
}; // class LogManager
}; // class XmlParserInputBase
}; // namespace System.Xml.Private
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using Sandbox.Game.Entities;
using Sandbox.Game.EntityComponents;
using Sandbox.ModAPI;
using VRage;
using VRage.Game;
using VRage.Game.Entity;
using VRage.ModAPI;
using VRageMath;
using VRage.Utils;
using VRage.ObjectBuilders;
using Ingame = VRage.Game.ModAPI.Ingame;
//using Ingame = VRage.ModAPI.Ingame;
using VRage.Game.ModAPI;
using Sandbox.Definitions;
using NaniteConstructionSystem.Extensions;
using NaniteConstructionSystem.Particles;
using NaniteConstructionSystem.Entities.Tools;
using NaniteConstructionSystem.Entities.Beacons;
namespace NaniteConstructionSystem.Entities.Targets
{
public class NaniteConstructionTarget
{
public int ParticleCount { get; set; }
public NaniteAreaBeacon AreaBeacon { get; set; }
}
public class NaniteConstructionTargets : NaniteTargetBlocksBase
{
public override string TargetName
{
get { return "Construction"; }
}
private Dictionary<IMySlimBlock, int> m_targetBlocks;
private Dictionary<IMySlimBlock, NaniteAreaBeacon> m_areaTargetBlocks;
private float m_maxDistance = 300f;
private HashSet<IMySlimBlock> m_remoteTargets;
private FastResourceLock m_remoteLock;
public NaniteConstructionTargets(NaniteConstructionBlock constructionBlock) : base(constructionBlock)
{
m_targetBlocks = new Dictionary<IMySlimBlock, int>();
m_maxDistance = NaniteConstructionManager.Settings.ConstructionMaxBeaconDistance;
m_remoteTargets = new HashSet<IMySlimBlock>();
m_remoteLock = new FastResourceLock();
m_areaTargetBlocks = new Dictionary<IMySlimBlock, NaniteAreaBeacon>();
}
public override int GetMaximumTargets()
{
MyCubeBlock block = (MyCubeBlock)m_constructionBlock.ConstructionBlock;
return (int)Math.Min(NaniteConstructionManager.Settings.ConstructionNanitesNoUpgrade + (block.UpgradeValues["ConstructionNanites"] * NaniteConstructionManager.Settings.ConstructionNanitesPerUpgrade), NaniteConstructionManager.Settings.ConstructionMaxStreams);
}
public override float GetPowerUsage()
{
MyCubeBlock block = (MyCubeBlock)m_constructionBlock.ConstructionBlock;
return Math.Max(1, NaniteConstructionManager.Settings.ConstructionPowerPerStream - (int)(block.UpgradeValues["PowerNanites"] * NaniteConstructionManager.Settings.PowerDecreasePerUpgrade));
}
public override float GetMinTravelTime()
{
MyCubeBlock block = (MyCubeBlock)m_constructionBlock.ConstructionBlock;
return Math.Max(1f, NaniteConstructionManager.Settings.ConstructionMinTravelTime - (block.UpgradeValues["SpeedNanites"] * NaniteConstructionManager.Settings.MinTravelTimeReductionPerUpgrade));
}
public override float GetSpeed()
{
MyCubeBlock block = (MyCubeBlock)m_constructionBlock.ConstructionBlock;
return NaniteConstructionManager.Settings.ConstructionDistanceDivisor + (block.UpgradeValues["SpeedNanites"] * (float)NaniteConstructionManager.Settings.SpeedIncreasePerUpgrade);
}
public override bool IsEnabled()
{
bool result = true;
if (!((IMyFunctionalBlock)m_constructionBlock.ConstructionBlock).Enabled ||
!((IMyFunctionalBlock)m_constructionBlock.ConstructionBlock).IsFunctional ||
m_constructionBlock.ConstructionBlock.CustomName.ToLower().Contains("NoConstruction".ToLower()))
result = false;
if(NaniteConstructionManager.TerminalSettings.ContainsKey(m_constructionBlock.ConstructionBlock.EntityId))
{
if (!NaniteConstructionManager.TerminalSettings[m_constructionBlock.ConstructionBlock.EntityId].AllowRepair)
return false;
}
return result;
}
public override void FindTargets(ref Dictionary<string, int> available)
{
if (!IsEnabled())
return;
ComponentsRequired.Clear();
if (m_targetList.Count >= GetMaximumTargets())
{
if (PotentialTargetList.Count > 0)
m_lastInvalidTargetReason = "Maximum targets reached. Add more upgrades!";
return;
}
NaniteConstructionInventory inventoryManager = m_constructionBlock.InventoryManager;
Vector3D sourcePosition = m_constructionBlock.ConstructionBlock.GetPosition();
Dictionary<string, int> missing = new Dictionary<string, int>();
using (Lock.AcquireExclusiveUsing())
{
var potentialList = m_potentialTargetList.OrderByDescending(x => GetMissingComponentCount(inventoryManager, (IMySlimBlock)x)).ToList();
for (int r = potentialList.Count - 1; r >= 0; r--)
{
if (m_constructionBlock.IsUserDefinedLimitReached())
{
m_lastInvalidTargetReason = "User defined maximum nanite limit reached";
return;
}
var item = (IMySlimBlock)potentialList[r];
if (TargetList.Contains(item))
continue;
missing.Clear();
item.GetMissingComponents(missing);
bool foundMissingComponents = true;
if (MyAPIGateway.Session.CreativeMode)
foundMissingComponents = true;
else if (missing.Count > 0)
{
foundMissingComponents = inventoryManager.CheckComponentsAvailable(ref missing, ref available);
}
if (foundMissingComponents && NaniteConstructionPower.HasRequiredPowerForNewTarget((IMyFunctionalBlock)m_constructionBlock.ConstructionBlock, this))
{
// Check to see if another block targetting this for construction
var blockList = NaniteConstructionManager.GetConstructionBlocks((IMyCubeGrid)m_constructionBlock.ConstructionBlock.CubeGrid);
bool found = false;
foreach (var block in blockList)
{
if (block.Targets.First(y => y is NaniteConstructionTargets).TargetList.Contains(item as IMySlimBlock))
{
found = true;
break;
}
}
if (found)
{
m_lastInvalidTargetReason = "Another factory has this block as a target";
continue;
}
m_potentialTargetList.RemoveAt(r);
m_targetList.Add(item);
var def = item.BlockDefinition as MyCubeBlockDefinition;
Logging.Instance.WriteLine(string.Format("ADDING Construction/Repair Target: conid={0} subtype={1} entityID={2} position={3}", m_constructionBlock.ConstructionBlock.EntityId, def.Id.SubtypeId, item.FatBlock != null ? item.FatBlock.EntityId : 0, item.Position));
if (m_targetList.Count >= GetMaximumTargets())
break;
}
else if (!foundMissingComponents)
{
foreach (var component in missing)
{
if (!ComponentsRequired.ContainsKey(component.Key))
ComponentsRequired.Add(component.Key, component.Value);
else
ComponentsRequired[component.Key] += component.Value;
}
m_lastInvalidTargetReason = "Missing components";
}
else if (!NaniteConstructionPower.HasRequiredPowerForNewTarget((IMyFunctionalBlock)m_constructionBlock.ConstructionBlock, this))
{
m_lastInvalidTargetReason = "Insufficient power for another target.";
}
}
}
}
private int GetMissingComponentCount(NaniteConstructionInventory inventoryManager, IMySlimBlock block)
{
Dictionary<string, int> missing = new Dictionary<string, int>();
block.GetMissingComponents(missing);
if (missing.Count == 0)
return 0;
Dictionary<string, int> available = new Dictionary<string, int>();
inventoryManager.GetAvailableComponents(ref available);
for (int r = missing.Count - 1; r >= 0; r--)
{
var item = missing.ElementAt(r);
if (available.ContainsKey(item.Key))
{
int amount = Math.Min(item.Value, available[item.Key]);
available[item.Key] -= amount;
missing[item.Key] -= amount;
}
}
return missing.Sum(x => x.Value);
}
public override void Update()
{
foreach (var item in m_targetList.ToList())
{
var block = item as IMySlimBlock;
if (block != null)
ProcessConstructionItem(block);
}
}
private void ProcessConstructionItem(IMySlimBlock target)
{
if (Sync.IsServer)
{
if (!IsEnabled())
{
Logging.Instance.WriteLine("CANCELLING Construction/Repair Target due to being disabled");
CancelTarget(target);
return;
}
if (!NaniteConstructionPower.HasRequiredPowerForCurrentTarget((IMyFunctionalBlock)m_constructionBlock.ConstructionBlock))
{
Logging.Instance.WriteLine("CANCELLING Construction/Repair Target due to power shortage");
CancelTarget(target);
return;
}
if (m_constructionBlock.FactoryState != NaniteConstructionBlock.FactoryStates.Active)
return;
if (!m_targetBlocks.ContainsKey(target))
m_targetBlocks.Add(target, 0);
NaniteWelder welder = (NaniteWelder)m_constructionBlock.ToolManager.Tools.FirstOrDefault(x => x.TargetBlock == target && x is NaniteWelder);
if (welder == null)
{
double distance = EntityHelper.GetDistanceBetweenBlockAndSlimblock((IMyCubeBlock)m_constructionBlock.ConstructionBlock, target);
int time = (int)Math.Max(GetMinTravelTime() * 1000f, (distance / GetSpeed()) * 1000f);
welder = new NaniteWelder(m_constructionBlock, target, (int)(time / 2.5f), false);
m_constructionBlock.ToolManager.Tools.Add(welder);
m_constructionBlock.SendAddTarget(target, TargetTypes.Construction);
}
if (target.IsFullIntegrity && !target.HasDeformation)
{
CompleteTarget(target);
return;
}
if (m_areaTargetBlocks.ContainsKey(target))
{
BoundingBoxD bb;
target.GetWorldBoundingBox(out bb, true);
if (!m_areaTargetBlocks[target].IsInsideBox(bb))
{
CancelTarget(target);
return;
}
}
if (target.IsDestroyed || target.IsFullyDismounted || (target.FatBlock != null && target.FatBlock.Closed))
{
Logging.Instance.WriteLine("CANCELLING Construction/Repair Target due to target being destroyed");
CancelTarget(target);
return;
}
if (welder != null && MyAPIGateway.Session.ElapsedPlayTime.TotalMilliseconds - welder.StartTime >= welder.WaitTime)
{
target.MoveItemsToConstructionStockpile(((MyEntity)m_constructionBlock.ConstructionBlock).GetInventory());
Dictionary<string, int> missing = new Dictionary<string, int>();
target.GetMissingComponents(missing);
if (!target.HasDeformation && !target.CanContinueBuild(((MyEntity)m_constructionBlock.ConstructionBlock).GetInventory()))
{
if (!MyAPIGateway.Session.CreativeMode)
{
Logging.Instance.WriteLine("CANCELLING Construction/Repair Target due to missing components");
foreach (var item in missing)
{
Logging.Instance.WriteLine(string.Format("Missing component: {0} - {1}", item.Value, item.Key));
}
CancelTarget(target);
}
}
return;
}
bool isRemote = false;
using (m_remoteLock.AcquireExclusiveUsing())
{
isRemote = m_remoteTargets.Contains(target);
}
if (isRemote && EntityHelper.GetDistanceBetweenBlockAndSlimblock((IMyCubeBlock)m_constructionBlock.ConstructionBlock, target) > m_maxDistance)
{
Logging.Instance.WriteLine("CANCELLING Repair Target due to target being out of range");
CancelTarget(target);
return;
}
}
CreateConstructionParticle(target);
}
private void CreateConstructionParticle(IMySlimBlock target)
{
if (!m_targetBlocks.ContainsKey(target))
m_targetBlocks.Add(target, 0);
if (NaniteParticleManager.TotalParticleCount > NaniteParticleManager.MaxTotalParticles)
return;
m_targetBlocks[target]++;
int size = (int)Math.Max(60f, NaniteParticleManager.TotalParticleCount);
if ((float)m_targetBlocks[target] / size < 1f)
return;
m_targetBlocks[target] = 0;
Vector4 startColor = new Vector4(0.55f, 0.55f, 0.95f, 0.75f);
Vector4 endColor = new Vector4(0.05f, 0.05f, 0.35f, 0.75f);
m_constructionBlock.ParticleManager.AddParticle(startColor, endColor, GetMinTravelTime() * 1000f, GetSpeed(), target);
}
public void CompleteTarget(IMySlimBlock obj)
{
Logging.Instance.WriteLine(string.Format("COMPLETING Construction/Repair Target: {0} - {1} (EntityID={2},Position={3})", m_constructionBlock.ConstructionBlock.EntityId, obj.GetType().Name, obj.FatBlock != null ? obj.FatBlock.EntityId : 0, obj.Position));
if (Sync.IsServer)
m_constructionBlock.SendCompleteTarget(obj, TargetTypes.Construction);
m_constructionBlock.ParticleManager.CompleteTarget(obj);
m_constructionBlock.ToolManager.Remove(obj);
Remove(obj);
m_remoteTargets.Remove(obj);
if(m_areaTargetBlocks.ContainsKey(obj))
m_areaTargetBlocks.Remove(obj);
}
public void CancelTarget(IMySlimBlock obj)
{
Logging.Instance.WriteLine(string.Format("CANCELLING Construction/Repair Target: {0} - {1} (EntityID={2},Position={3})", m_constructionBlock.ConstructionBlock.EntityId, obj.GetType().Name, obj.FatBlock != null ? obj.FatBlock.EntityId : 0, obj.Position));
if (Sync.IsServer)
m_constructionBlock.SendCancelTarget(obj, TargetTypes.Construction);
m_constructionBlock.ParticleManager.CancelTarget(obj);
m_constructionBlock.ToolManager.Remove(obj);
Remove(obj);
m_remoteTargets.Remove(obj);
if (m_areaTargetBlocks.ContainsKey(obj))
m_areaTargetBlocks.Remove(obj);
}
public override void CancelTarget(object obj)
{
var target = obj as IMySlimBlock;
if (target == null)
return;
CancelTarget(target);
}
public override void CompleteTarget(object obj)
{
var target = obj as IMySlimBlock;
if (target == null)
return;
CompleteTarget(target);
}
public override void ParallelUpdate(List<IMyCubeGrid> gridList, List<IMySlimBlock> blocks)
{
using (Lock.AcquireExclusiveUsing())
{
PotentialTargetList.Clear();
}
var remoteList = new HashSet<IMySlimBlock>();
if (!IsEnabled())
return;
foreach (var block in blocks)
{
AddPotentialBlock(block);
}
foreach (var beaconBlock in NaniteConstructionManager.BeaconList.Where(x => x is NaniteBeaconConstruct && Vector3D.DistanceSquared(m_constructionBlock.ConstructionBlock.GetPosition(), x.BeaconBlock.GetPosition()) < m_maxDistance * m_maxDistance))
{
IMyCubeBlock item = (IMyCubeBlock)beaconBlock.BeaconBlock;
MyRelationsBetweenPlayerAndBlock relation = item.GetUserRelationToOwner(m_constructionBlock.ConstructionBlock.OwnerId);
if (!(relation == MyRelationsBetweenPlayerAndBlock.Owner || relation == MyRelationsBetweenPlayerAndBlock.FactionShare || (MyAPIGateway.Session.CreativeMode && relation == MyRelationsBetweenPlayerAndBlock.NoOwnership)))
continue;
if (!((IMyFunctionalBlock)item).Enabled)
continue;
List<IMyCubeGrid> beaconGridList = GridHelper.GetGridGroup((IMyCubeGrid)item.CubeGrid);
List<IMySlimBlock> beaconBlocks = new List<IMySlimBlock>();
foreach (var grid in beaconGridList)
{
grid.GetBlocks(beaconBlocks);
}
foreach (var block in beaconBlocks)
{
if(AddPotentialBlock(block, true))
{
remoteList.Add(block);
}
}
}
CheckAreaBeacons();
using (m_remoteLock.AcquireExclusiveUsing())
{
m_remoteTargets = remoteList;
}
}
private void CheckAreaBeacons()
{
foreach(var beaconBlock in NaniteConstructionManager.BeaconList.Where(x => x is NaniteAreaBeacon))
{
IMyCubeBlock cubeBlock = beaconBlock.BeaconBlock;
//MyRelationsBetweenPlayerAndBlock relation = cubeBlock.GetUserRelationToOwner(m_constructionBlock.ConstructionBlock.OwnerId);
//if (!(relation == MyRelationsBetweenPlayerAndBlock.Owner || relation == MyRelationsBetweenPlayerAndBlock.FactionShare || (MyAPIGateway.Session.CreativeMode && relation == MyRelationsBetweenPlayerAndBlock.NoOwnership)))
// continue;
if (!((IMyFunctionalBlock)cubeBlock).Enabled)
continue;
var item = beaconBlock as NaniteAreaBeacon;
if (!item.Settings.AllowRepair)
continue;
HashSet<IMyEntity> entities = new HashSet<IMyEntity>();
MyAPIGateway.Entities.GetEntities(entities);
foreach(var entity in entities)
{
var grid = entity as IMyCubeGrid;
if (grid == null)
continue;
if (grid.Physics == null)
continue;
if((grid.GetPosition() - cubeBlock.GetPosition()).LengthSquared() < m_maxDistance * m_maxDistance)
{
foreach(IMySlimBlock block in ((MyCubeGrid)grid).GetBlocks())
{
BoundingBoxD blockbb;
block.GetWorldBoundingBox(out blockbb);
if (item.IsInsideBox(blockbb))
{
AddPotentialBlock(block, true, item);
}
}
}
}
}
}
private bool AddPotentialBlock(IMySlimBlock block, bool remote = false, NaniteAreaBeacon areaBeacon = null)
{
if (TargetList.Contains(block))
return false;
if (!remote && block.FatBlock != null && block.FatBlock is IMyTerminalBlock && block.FatBlock.OwnerId != 0)
{
IMyTerminalBlock terminal = (IMyTerminalBlock)block.FatBlock;
MyRelationsBetweenPlayerAndBlock relation = terminal.GetUserRelationToOwner(m_constructionBlock.ConstructionBlock.OwnerId);
if (relation == MyRelationsBetweenPlayerAndBlock.Neutral ||
relation == MyRelationsBetweenPlayerAndBlock.Enemies)
{
return false;
}
}
else if(remote)
{
//if (block.CubeGrid.BigOwners.Count < 1)
// return false;
foreach (var item in block.CubeGrid.BigOwners)
{
MyRelationsBetweenPlayerAndBlock relation = m_constructionBlock.ConstructionBlock.GetUserRelationToOwner(item);
if (relation == MyRelationsBetweenPlayerAndBlock.Neutral ||
relation == MyRelationsBetweenPlayerAndBlock.Enemies)
{
return false;
}
}
}
if (!block.IsFullIntegrity || block.HasDeformation)
{
using (Lock.AcquireExclusiveUsing())
{
if(areaBeacon != null)
{
if (!m_areaTargetBlocks.ContainsKey(block))
m_areaTargetBlocks.Add(block, areaBeacon);
else
m_areaTargetBlocks[block] = areaBeacon;
}
PotentialTargetList.Add(block);
return true;
}
}
return false;
}
}
}
| |
using Lucene.Net.Search;
using Lucene.Net.Support;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Text;
using JCG = J2N.Collections.Generic;
namespace Lucene.Net.Util
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using IndexReader = Lucene.Net.Index.IndexReader;
/// <summary>
/// <para>
/// Provides methods for sanity checking that entries in the FieldCache
/// are not wasteful or inconsistent.
/// </para>
/// <para>
/// Lucene 2.9 Introduced numerous enhancements into how the FieldCache
/// is used by the low levels of Lucene searching (for Sorting and
/// ValueSourceQueries) to improve both the speed for Sorting, as well
/// as reopening of IndexReaders. But these changes have shifted the
/// usage of FieldCache from "top level" IndexReaders (frequently a
/// MultiReader or DirectoryReader) down to the leaf level SegmentReaders.
/// As a result, existing applications that directly access the FieldCache
/// may find RAM usage increase significantly when upgrading to 2.9 or
/// Later. This class provides an API for these applications (or their
/// Unit tests) to check at run time if the FieldCache contains "insane"
/// usages of the FieldCache.
/// </para>
/// @lucene.experimental
/// </summary>
/// <seealso cref="IFieldCache"/>
/// <seealso cref="FieldCacheSanityChecker.Insanity"/>
/// <seealso cref="FieldCacheSanityChecker.InsanityType"/>
public sealed class FieldCacheSanityChecker
{
private readonly bool estimateRam;
public FieldCacheSanityChecker()
{
/* NOOP */
}
/// <param name="estimateRam">If set, estimate size for all <see cref="FieldCache.CacheEntry"/> objects will be calculated.</param>
// LUCENENET specific - added this constructor overload so we wouldn't need a (ridiculous) SetRamUsageEstimator() method
public FieldCacheSanityChecker(bool estimateRam)
{
this.estimateRam = estimateRam;
}
// LUCENENET specific - using constructor overload to replace this method
///// <summary>
///// If set, estimate size for all CacheEntry objects will be calculateed.
///// </summary>
//public bool SetRamUsageEstimator(bool flag)
//{
// estimateRam = flag;
//}
/// <summary>
/// Quick and dirty convenience method </summary>
/// <seealso cref="Check(FieldCache.CacheEntry[])"/>
public static Insanity[] CheckSanity(IFieldCache cache)
{
return CheckSanity(cache.GetCacheEntries());
}
/// <summary>
/// Quick and dirty convenience method that instantiates an instance with
/// "good defaults" and uses it to test the <see cref="FieldCache.CacheEntry"/>s </summary>
/// <seealso cref="Check(FieldCache.CacheEntry[])"/>
public static Insanity[] CheckSanity(params FieldCache.CacheEntry[] cacheEntries)
{
FieldCacheSanityChecker sanityChecker = new FieldCacheSanityChecker(estimateRam: true);
return sanityChecker.Check(cacheEntries);
}
/// <summary>
/// Tests a CacheEntry[] for indication of "insane" cache usage.
/// <para>
/// <b>NOTE:</b>FieldCache CreationPlaceholder objects are ignored.
/// (:TODO: is this a bad idea? are we masking a real problem?)
/// </para>
/// </summary>
public Insanity[] Check(params FieldCache.CacheEntry[] cacheEntries)
{
if (null == cacheEntries || 0 == cacheEntries.Length)
{
return Arrays.Empty<Insanity>();
}
if (estimateRam)
{
for (int i = 0; i < cacheEntries.Length; i++)
{
cacheEntries[i].EstimateSize();
}
}
// the indirect mapping lets MapOfSet dedup identical valIds for us
// maps the (valId) identityhashCode of cache values to
// sets of CacheEntry instances
MapOfSets<int, FieldCache.CacheEntry> valIdToItems = new MapOfSets<int, FieldCache.CacheEntry>(new Dictionary<int, ISet<FieldCache.CacheEntry>>(17));
// maps ReaderField keys to Sets of ValueIds
MapOfSets<ReaderField, int> readerFieldToValIds = new MapOfSets<ReaderField, int>(new Dictionary<ReaderField, ISet<int>>(17));
// any keys that we know result in more then one valId
ISet<ReaderField> valMismatchKeys = new JCG.HashSet<ReaderField>();
// iterate over all the cacheEntries to get the mappings we'll need
for (int i = 0; i < cacheEntries.Length; i++)
{
FieldCache.CacheEntry item = cacheEntries[i];
object val = item.Value;
// It's OK to have dup entries, where one is eg
// float[] and the other is the Bits (from
// getDocWithField())
if (val is IBits)
{
continue;
}
if (val is FieldCache.CreationPlaceholder)
{
continue;
}
ReaderField rf = new ReaderField(item.ReaderKey, item.FieldName);
int valId = RuntimeHelpers.GetHashCode(val);
// indirect mapping, so the MapOfSet will dedup identical valIds for us
valIdToItems.Put(valId, item);
if (1 < readerFieldToValIds.Put(rf, valId))
{
valMismatchKeys.Add(rf);
}
}
List<Insanity> insanity = new List<Insanity>(valMismatchKeys.Count * 3);
insanity.AddRange(CheckValueMismatch(valIdToItems, readerFieldToValIds, valMismatchKeys));
insanity.AddRange(CheckSubreaders(valIdToItems, readerFieldToValIds));
return insanity.ToArray();
}
/// <summary>
/// Internal helper method used by check that iterates over
/// <paramref name="valMismatchKeys"/> and generates a <see cref="ICollection{T}"/> of <see cref="Insanity"/>
/// instances accordingly. The <see cref="MapOfSets{TKey, TValue}"/> are used to populate
/// the <see cref="Insanity"/> objects. </summary>
/// <seealso cref="InsanityType.VALUEMISMATCH"/>
private ICollection<Insanity> CheckValueMismatch(MapOfSets<int, FieldCache.CacheEntry> valIdToItems, MapOfSets<ReaderField, int> readerFieldToValIds, ISet<ReaderField> valMismatchKeys)
{
List<Insanity> insanity = new List<Insanity>(valMismatchKeys.Count * 3);
if (valMismatchKeys.Count != 0)
{
// we have multiple values for some ReaderFields
IDictionary<ReaderField, ISet<int>> rfMap = readerFieldToValIds.Map;
IDictionary<int, ISet<FieldCache.CacheEntry>> valMap = valIdToItems.Map;
foreach (ReaderField rf in valMismatchKeys)
{
IList<FieldCache.CacheEntry> badEntries = new List<FieldCache.CacheEntry>(valMismatchKeys.Count * 2);
foreach (int value in rfMap[rf])
{
foreach (FieldCache.CacheEntry cacheEntry in valMap[value])
{
badEntries.Add(cacheEntry);
}
}
FieldCache.CacheEntry[] badness = new FieldCache.CacheEntry[badEntries.Count];
badEntries.CopyTo(badness, 0);
insanity.Add(new Insanity(InsanityType.VALUEMISMATCH, "Multiple distinct value objects for " + rf.ToString(), badness));
}
}
return insanity;
}
/// <summary>
/// Internal helper method used by check that iterates over
/// the keys of <paramref name="readerFieldToValIds"/> and generates a <see cref="ICollection{T}"/>
/// of <see cref="Insanity"/> instances whenever two (or more) <see cref="ReaderField"/> instances are
/// found that have an ancestry relationships.
/// </summary>
/// <seealso cref="InsanityType.SUBREADER"/>
private ICollection<Insanity> CheckSubreaders(MapOfSets<int, FieldCache.CacheEntry> valIdToItems, MapOfSets<ReaderField, int> readerFieldToValIds)
{
List<Insanity> insanity = new List<Insanity>(23);
Dictionary<ReaderField, ISet<ReaderField>> badChildren = new Dictionary<ReaderField, ISet<ReaderField>>(17);
MapOfSets<ReaderField, ReaderField> badKids = new MapOfSets<ReaderField, ReaderField>(badChildren); // wrapper
IDictionary<int, ISet<FieldCache.CacheEntry>> viToItemSets = valIdToItems.Map;
IDictionary<ReaderField, ISet<int>> rfToValIdSets = readerFieldToValIds.Map;
HashSet<ReaderField> seen = new HashSet<ReaderField>();
//IDictionary<ReaderField, ISet<int>>.KeyCollection readerFields = rfToValIdSets.Keys;
foreach (ReaderField rf in rfToValIdSets.Keys)
{
if (seen.Contains(rf))
{
continue;
}
IList<object> kids = GetAllDescendantReaderKeys(rf.ReaderKey);
foreach (object kidKey in kids)
{
ReaderField kid = new ReaderField(kidKey, rf.FieldName);
// LUCENENET: Eliminated extra lookup by using TryGetValue instead of ContainsKey
if (badChildren.TryGetValue(kid, out ISet<ReaderField> badKid))
{
// we've already process this kid as RF and found other problems
// track those problems as our own
badKids.Put(rf, kid);
badKids.PutAll(rf, badKid);
badChildren.Remove(kid);
}
else if (rfToValIdSets.ContainsKey(kid))
{
// we have cache entries for the kid
badKids.Put(rf, kid);
}
seen.Add(kid);
}
seen.Add(rf);
}
// every mapping in badKids represents an Insanity
foreach (ReaderField parent in badChildren.Keys)
{
ISet<ReaderField> kids = badChildren[parent];
List<FieldCache.CacheEntry> badEntries = new List<FieldCache.CacheEntry>(kids.Count * 2);
// put parent entr(ies) in first
{
foreach (int value in rfToValIdSets[parent])
{
badEntries.AddRange(viToItemSets[value]);
}
}
// now the entries for the descendants
foreach (ReaderField kid in kids)
{
foreach (int value in rfToValIdSets[kid])
{
badEntries.AddRange(viToItemSets[value]);
}
}
FieldCache.CacheEntry[] badness = badEntries.ToArray();
insanity.Add(new Insanity(InsanityType.SUBREADER, "Found caches for descendants of " + parent.ToString(), badness));
}
return insanity;
}
/// <summary>
/// Checks if the <paramref name="seed"/> is an <see cref="IndexReader"/>, and if so will walk
/// the hierarchy of subReaders building up a list of the objects
/// returned by <c>seed.CoreCacheKey</c>
/// </summary>
private IList<object> GetAllDescendantReaderKeys(object seed)
{
var all = new List<object>(17) {seed}; // will grow as we iter
for (var i = 0; i < all.Count; i++)
{
var obj = all[i];
// TODO: We don't check closed readers here (as getTopReaderContext
// throws ObjectDisposedException), what should we do? Reflection?
var reader = obj as IndexReader;
if (reader != null)
{
try
{
var childs = reader.Context.Children;
if (childs != null) // it is composite reader
{
foreach (var ctx in childs)
{
all.Add(ctx.Reader.CoreCacheKey);
}
}
}
catch (ObjectDisposedException)
{
// ignore this reader
}
}
}
// need to skip the first, because it was the seed
return all.GetRange(1, all.Count - 1);
}
/// <summary>
/// Simple pair object for using "readerKey + fieldName" a Map key
/// </summary>
private sealed class ReaderField
{
public object ReaderKey => readerKey;
private readonly object readerKey;
public string FieldName { get; private set; }
public ReaderField(object readerKey, string fieldName)
{
this.readerKey = readerKey;
this.FieldName = fieldName;
}
public override int GetHashCode()
{
return RuntimeHelpers.GetHashCode(readerKey) * FieldName.GetHashCode();
}
public override bool Equals(object that)
{
if (!(that is ReaderField))
{
return false;
}
ReaderField other = (ReaderField)that;
return (object.ReferenceEquals(this.readerKey, other.readerKey)
&& this.FieldName.Equals(other.FieldName, StringComparison.Ordinal));
}
public override string ToString()
{
return readerKey.ToString() + "+" + FieldName;
}
}
/// <summary>
/// Simple container for a collection of related <see cref="FieldCache.CacheEntry"/> objects that
/// in conjunction with each other represent some "insane" usage of the
/// <see cref="IFieldCache"/>.
/// </summary>
public sealed class Insanity
{
private readonly InsanityType type;
private readonly string msg;
private readonly FieldCache.CacheEntry[] entries;
public Insanity(InsanityType type, string msg, params FieldCache.CacheEntry[] entries)
{
if (null == type)
{
throw new ArgumentException("Insanity requires non-null InsanityType");
}
if (null == entries || 0 == entries.Length)
{
throw new ArgumentException("Insanity requires non-null/non-empty CacheEntry[]");
}
this.type = type;
this.msg = msg;
this.entries = entries;
}
/// <summary>
/// Type of insane behavior this object represents
/// </summary>
public InsanityType Type => type;
/// <summary>
/// Description of the insane behavior
/// </summary>
public string Msg => msg;
/// <summary>
/// <see cref="FieldCache.CacheEntry"/> objects which suggest a problem
/// </summary>
[WritableArray]
[SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")]
public FieldCache.CacheEntry[] CacheEntries => entries;
/// <summary>
/// Multi-Line representation of this <see cref="Insanity"/> object, starting with
/// the Type and Msg, followed by each CacheEntry.ToString() on it's
/// own line prefaced by a tab character
/// </summary>
public override string ToString()
{
StringBuilder buf = new StringBuilder();
buf.Append(Type).Append(": ");
string m = Msg;
if (null != m)
{
buf.Append(m);
}
buf.Append('\n');
FieldCache.CacheEntry[] ce = CacheEntries;
for (int i = 0; i < ce.Length; i++)
{
buf.Append('\t').Append(ce[i].ToString()).Append('\n');
}
return buf.ToString();
}
}
/// <summary>
/// An Enumeration of the different types of "insane" behavior that
/// may be detected in a <see cref="IFieldCache"/>.
/// </summary>
/// <seealso cref="InsanityType.SUBREADER"/>
/// <seealso cref="InsanityType.VALUEMISMATCH"/>
/// <seealso cref="InsanityType.EXPECTED"/>
public sealed class InsanityType
{
private readonly string label;
private InsanityType(string label)
{
this.label = label;
}
public override string ToString()
{
return label;
}
/// <summary>
/// Indicates an overlap in cache usage on a given field
/// in sub/super readers.
/// </summary>
public static readonly InsanityType SUBREADER = new InsanityType("SUBREADER");
/// <summary>
/// <para>
/// Indicates entries have the same reader+fieldname but
/// different cached values. This can happen if different datatypes,
/// or parsers are used -- and while it's not necessarily a bug
/// it's typically an indication of a possible problem.
/// </para>
/// <para>
/// <b>NOTE:</b> Only the reader, fieldname, and cached value are actually
/// tested -- if two cache entries have different parsers or datatypes but
/// the cached values are the same Object (== not just Equal()) this method
/// does not consider that a red flag. This allows for subtle variations
/// in the way a Parser is specified (null vs DEFAULT_INT64_PARSER, etc...)
/// </para>
/// </summary>
public static readonly InsanityType VALUEMISMATCH = new InsanityType("VALUEMISMATCH");
/// <summary>
/// Indicates an expected bit of "insanity". This may be useful for
/// clients that wish to preserve/log information about insane usage
/// but indicate that it was expected.
/// </summary>
public static readonly InsanityType EXPECTED = new InsanityType("EXPECTED");
}
}
}
| |
#region License
// Copyright (c) Jeremy Skinner (http://www.jeremyskinner.co.uk)
//
// 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.
//
// The latest version of this file can be found at http://www.codeplex.com/FluentValidation
#endregion
namespace FluentValidation.Tests {
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Internal;
using Xunit;
using Validators;
public class DefaultValidatorExtensionTester {
private AbstractValidator<Person> validator;
public DefaultValidatorExtensionTester() {
validator = new TestValidator();
}
[Fact]
public void NotNull_should_create_NotNullValidator() {
validator.RuleFor(x => x.Surname).NotNull();
AssertValidator<NotNullValidator>();
}
[Fact]
public void NotEmpty_should_create_NotEmptyValidator() {
validator.RuleFor(x => x.Surname).NotEmpty();
AssertValidator<NotEmptyValidator>();
}
[Fact]
public void Empty_should_create_EmptyValidator() {
validator.RuleFor(x => x.Surname).Empty();
AssertValidator<EmptyValidator>();
}
[Fact]
public void Length_should_create_LengthValidator() {
validator.RuleFor(x => x.Surname).Length(1, 20);
AssertValidator<LengthValidator>();
}
[Fact]
public void Length_should_create_ExactLengthValidator() {
validator.RuleFor(x => x.Surname).Length(5);
AssertValidator<ExactLengthValidator>();
}
[Fact]
public void NotEqual_should_create_NotEqualValidator_with_explicit_value() {
validator.RuleFor(x => x.Surname).NotEqual("Foo");
AssertValidator<NotEqualValidator>();
}
[Fact]
public void NotEqual_should_create_NotEqualValidator_with_lambda() {
validator.RuleFor(x => x.Surname).NotEqual(x => "Foo");
AssertValidator<NotEqualValidator>();
}
[Fact]
public void Equal_should_create_EqualValidator_with_explicit_value() {
validator.RuleFor(x => x.Surname).Equal("Foo");
AssertValidator<EqualValidator>();
}
[Fact]
public void Equal_should_create_EqualValidator_with_lambda() {
validator.RuleFor(x => x.Surname).Equal(x => "Foo");
AssertValidator<EqualValidator>();
}
[Fact]
public void Must_should_create_PredicteValidator() {
validator.RuleFor(x => x.Surname).Must(x => true);
AssertValidator<PredicateValidator>();
}
[Fact]
public void Must_should_create_PredicateValidator_with_context() {
validator.RuleFor(x => x.Surname).Must((x, val) => true);
AssertValidator<PredicateValidator>();
}
[Fact]
public void Must_should_create_PredicateValidator_with_PropertyValidatorContext() {
var hasPropertyValidatorContext = false;
this.validator.RuleFor(x => x.Surname).Must((x, val, ctx) => {
hasPropertyValidatorContext = ctx != null;
return true;
});
this.validator.Validate(new Person() {
Surname = "Surname"
});
this.AssertValidator<PredicateValidator>();
hasPropertyValidatorContext.ShouldBeTrue();
}
[Fact]
public void MustAsync_should_create_AsyncPredicteValidator() {
validator.RuleFor(x => x.Surname).MustAsync((x, cancel) => TaskHelpers.FromResult(true));
AssertValidator<AsyncPredicateValidator>();
}
[Fact]
public void MustAsync_should_create_AsyncPredicateValidator_with_context() {
validator.RuleFor(x => x.Surname).MustAsync((x, val) => TaskHelpers.FromResult(true));
AssertValidator<AsyncPredicateValidator>();
}
[Fact]
public void MustAsync_should_create_AsyncPredicateValidator_with_PropertyValidatorContext() {
var hasPropertyValidatorContext = false;
this.validator.RuleFor(x => x.Surname).MustAsync((x, val, ctx, cancel) => {
hasPropertyValidatorContext = ctx != null;
return TaskHelpers.FromResult(true);
});
this.validator.ValidateAsync(new Person {
Surname = "Surname"
}).Wait();
this.AssertValidator<AsyncPredicateValidator>();
hasPropertyValidatorContext.ShouldBeTrue();
}
[Fact]
public void LessThan_should_create_LessThanValidator_with_explicit_value() {
validator.RuleFor(x => x.Surname).LessThan("foo");
AssertValidator<LessThanValidator>();
}
[Fact]
public void LessThan_should_create_LessThanValidator_with_lambda() {
validator.RuleFor(x => x.Surname).LessThan(x => "foo");
AssertValidator<LessThanValidator>();
}
[Fact]
public void LessThanOrEqual_should_create_LessThanOrEqualValidator_with_explicit_value() {
validator.RuleFor(x => x.Surname).LessThanOrEqualTo("foo");
AssertValidator<LessThanOrEqualValidator>();
}
[Fact]
public void LessThanOrEqual_should_create_LessThanOrEqualValidator_with_lambda() {
validator.RuleFor(x => x.Surname).LessThanOrEqualTo(x => "foo");
AssertValidator<LessThanOrEqualValidator>();
}
[Fact]
public void LessThanOrEqual_should_create_LessThanOrEqualValidator_with_lambda_with_other_Nullable() {
validator.RuleFor(x => x.NullableInt).LessThanOrEqualTo(x => x.OtherNullableInt);
AssertValidator<LessThanOrEqualValidator>();
}
[Fact]
public void GreaterThan_should_create_GreaterThanValidator_with_explicit_value() {
validator.RuleFor(x => x.Surname).GreaterThan("foo");
AssertValidator<GreaterThanValidator>();
}
[Fact]
public void GreaterThan_should_create_GreaterThanValidator_with_lambda() {
validator.RuleFor(x => x.Surname).GreaterThan(x => "foo");
AssertValidator<GreaterThanValidator>();
}
[Fact]
public void GreaterThanOrEqual_should_create_GreaterThanOrEqualValidator_with_explicit_value() {
validator.RuleFor(x => x.Surname).GreaterThanOrEqualTo("foo");
AssertValidator<GreaterThanOrEqualValidator>();
}
[Fact]
public void GreaterThanOrEqual_should_create_GreaterThanOrEqualValidator_with_lambda() {
validator.RuleFor(x => x.Surname).GreaterThanOrEqualTo(x => "foo");
AssertValidator<GreaterThanOrEqualValidator>();
}
[Fact]
public void GreaterThanOrEqual_should_create_GreaterThanOrEqualValidator_with_lambda_with_other_Nullable() {
validator.RuleFor(x => x.NullableInt).GreaterThanOrEqualTo(x => x.OtherNullableInt);
AssertValidator<GreaterThanOrEqualValidator>();
}
[Fact]
public void MustAsync_should_not_throw_InvalidCastException() {
var model = new Model
{
Ids = new Guid[0]
};
var validator = new AsyncModelTestValidator();
// this fails with "Specified cast is not valid" error
var result = validator.ValidateAsync(model).Result;
result.IsValid.ShouldBeTrue();
}
private void AssertValidator<TValidator>() {
var rule = (PropertyRule)validator.First();
rule.CurrentValidator.ShouldBe<TValidator>();
}
class Model
{
public IEnumerable<Guid> Ids { get; set; }
}
class AsyncModelTestValidator : AbstractValidator<Model>
{
public AsyncModelTestValidator()
{
RuleForEach(m => m.Ids)
.MustAsync((g, cancel) => Task.FromResult(true));
}
}
}
}
| |
/*
* 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;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Drawing;
using System.Drawing.Imaging;
using System.Reflection;
using System.IO;
using System.Web;
using log4net;
using Nini.Config;
using Mono.Addins;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenMetaverse.Imaging;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using Caps = OpenSim.Framework.Capabilities.Caps;
using OpenSim.Capabilities.Handlers;
namespace OpenSim.Region.ClientStack.Linden
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "RegionConsoleModule")]
public class RegionConsoleModule : INonSharedRegionModule, IRegionConsole
{
// private static readonly ILog m_log =
// LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private Scene m_scene;
private IEventQueue m_eventQueue;
private Commands m_commands = new Commands();
public ICommands Commands { get { return m_commands; } }
public void Initialise(IConfigSource source)
{
m_commands.AddCommand( "Help", false, "help", "help [<item>]", "Display help on a particular command or on a list of commands in a category", Help);
}
public void AddRegion(Scene s)
{
m_scene = s;
m_scene.RegisterModuleInterface<IRegionConsole>(this);
}
public void RemoveRegion(Scene s)
{
m_scene.EventManager.OnRegisterCaps -= RegisterCaps;
m_scene = null;
}
public void RegionLoaded(Scene s)
{
m_scene.EventManager.OnRegisterCaps += RegisterCaps;
m_eventQueue = m_scene.RequestModuleInterface<IEventQueue>();
}
public void PostInitialise()
{
}
public void Close() { }
public string Name { get { return "RegionConsoleModule"; } }
public Type ReplaceableInterface
{
get { return null; }
}
public void RegisterCaps(UUID agentID, Caps caps)
{
if (!m_scene.RegionInfo.EstateSettings.IsEstateManagerOrOwner(agentID))
return;
UUID capID = UUID.Random();
// m_log.DebugFormat("[REGION CONSOLE]: /CAPS/{0} in region {1}", capID, m_scene.RegionInfo.RegionName);
caps.RegisterHandler(
"SimConsoleAsync",
new ConsoleHandler("/CAPS/" + capID + "/", "SimConsoleAsync", agentID, this, m_scene));
}
public void SendConsoleOutput(UUID agentID, string message)
{
OSD osd = OSD.FromString(message);
m_eventQueue.Enqueue(EventQueueHelper.BuildEvent("SimConsoleResponse", osd), agentID);
}
public bool RunCommand(string command, UUID invokerID)
{
string[] parts = Parser.Parse(command);
Array.Resize(ref parts, parts.Length + 1);
parts[parts.Length - 1] = invokerID.ToString();
if (m_commands.Resolve(parts).Length == 0)
return false;
return true;
}
private void Help(string module, string[] cmd)
{
UUID agentID = new UUID(cmd[cmd.Length - 1]);
Array.Resize(ref cmd, cmd.Length - 1);
List<string> help = Commands.GetHelp(cmd);
string reply = String.Empty;
foreach (string s in help)
{
reply += s + "\n";
}
SendConsoleOutput(agentID, reply);
}
public void AddCommand(string module, bool shared, string command, string help, string longhelp, CommandDelegate fn)
{
m_commands.AddCommand(module, shared, command, help, longhelp, fn);
}
}
public class ConsoleHandler : BaseStreamHandler
{
// private static readonly ILog m_log =
// LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private RegionConsoleModule m_consoleModule;
private UUID m_agentID;
private bool m_isGod;
private Scene m_scene;
private bool m_consoleIsOn = false;
public ConsoleHandler(string path, string name, UUID agentID, RegionConsoleModule module, Scene scene)
:base("POST", path, name, agentID.ToString())
{
m_agentID = agentID;
m_consoleModule = module;
m_scene = scene;
m_isGod = m_scene.Permissions.IsGod(agentID);
}
protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
{
StreamReader reader = new StreamReader(request);
string message = reader.ReadToEnd();
OSD osd = OSDParser.DeserializeLLSDXml(message);
string cmd = osd.AsString();
if (cmd == "set console on")
{
if (m_isGod)
{
MainConsole.Instance.OnOutput += ConsoleSender;
m_consoleIsOn = true;
m_consoleModule.SendConsoleOutput(m_agentID, "Console is now on");
}
return new byte[0];
}
else if (cmd == "set console off")
{
MainConsole.Instance.OnOutput -= ConsoleSender;
m_consoleIsOn = false;
m_consoleModule.SendConsoleOutput(m_agentID, "Console is now off");
return new byte[0];
}
if (m_consoleIsOn == false && m_consoleModule.RunCommand(osd.AsString().Trim(), m_agentID))
return new byte[0];
if (m_isGod && m_consoleIsOn)
{
MainConsole.Instance.RunCommand(osd.AsString().Trim());
}
else
{
m_consoleModule.SendConsoleOutput(m_agentID, "Unknown command");
}
return new byte[0];
}
private void ConsoleSender(string text)
{
m_consoleModule.SendConsoleOutput(m_agentID, text);
}
private void OnMakeChildAgent(ScenePresence presence)
{
if (presence.UUID == m_agentID)
{
MainConsole.Instance.OnOutput -= ConsoleSender;
m_consoleIsOn = false;
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
#if !NOT_UNITY3D
using UnityEngine;
#endif
namespace ModestTree.Util
{
public static class ReflectionUtil
{
public static bool IsGenericList(Type type)
{
return type.IsGenericType()
&& (type.GetGenericTypeDefinition() == typeof(List<>)
|| type.GetGenericTypeDefinition() == typeof(IList<>));
}
public static bool IsGenericList(Type type, out Type contentsType)
{
if (IsGenericList(type))
{
contentsType = type.GenericArguments().Single();
return true;
}
contentsType = null;
return false;
}
public static IList CreateGenericList(Type elementType, object[] contentsAsObj)
{
var genericType = typeof(List<>).MakeGenericType(elementType);
var list = (IList)Activator.CreateInstance(genericType);
foreach (var obj in contentsAsObj)
{
if (obj != null)
{
Assert.That(obj.GetType().DerivesFromOrEqual(elementType),
"Wrong type when creating generic list, expected something assignable from '"+ elementType +"', but found '" + obj.GetType() + "'");
}
list.Add(obj);
}
return list;
}
public static IDictionary CreateGenericDictionary(
Type keyType, Type valueType, object[] keysAsObj, object[] valuesAsObj)
{
Assert.That(keysAsObj.Length == valuesAsObj.Length);
var genericType = typeof(Dictionary<,>).MakeGenericType(keyType, valueType);
var dictionary = (IDictionary)Activator.CreateInstance(genericType);
for (int i = 0; i < keysAsObj.Length; i++)
{
dictionary.Add(keysAsObj[i], valuesAsObj[i]);
}
return dictionary;
}
public static object DowncastList<TFrom, TTo>(IEnumerable<TFrom> fromList) where TTo : class, TFrom
{
var toList = new List<TTo>();
foreach (var obj in fromList)
{
toList.Add(obj as TTo);
}
return toList;
}
public static IEnumerable<IMemberInfo> GetFieldsAndProperties<T>(BindingFlags flags)
{
return GetFieldsAndProperties(typeof(T), flags);
}
public static IEnumerable<IMemberInfo> GetFieldsAndProperties(Type type, BindingFlags flags)
{
foreach (var propInfo in type.GetProperties(flags))
{
yield return new PropertyMemberInfo(propInfo);
}
foreach (var fieldInfo in type.GetFields(flags))
{
yield return new FieldMemberInfo(fieldInfo);
}
}
public static string ToDebugString(this MethodInfo method)
{
return "{0}.{1}".Fmt(method.DeclaringType.Name(), method.Name);
}
public static string ToDebugString(this Action action)
{
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
return action.ToString();
#else
return action.Method.ToDebugString();
#endif
}
public static string ToDebugString<TParam1>(this Action<TParam1> action)
{
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
return action.ToString();
#else
return action.Method.ToDebugString();
#endif
}
public static string ToDebugString<TParam1, TParam2>(this Action<TParam1, TParam2> action)
{
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
return action.ToString();
#else
return action.Method.ToDebugString();
#endif
}
public static string ToDebugString<TParam1, TParam2, TParam3>(this Action<TParam1, TParam2, TParam3> action)
{
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
return action.ToString();
#else
return action.Method.ToDebugString();
#endif
}
public static string ToDebugString<TParam1, TParam2, TParam3, TParam4>(this Action<TParam1, TParam2, TParam3, TParam4> action)
{
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
return action.ToString();
#else
return action.Method.ToDebugString();
#endif
}
public static string ToDebugString<TParam1, TParam2, TParam3, TParam4, TParam5>(this ModestTree.Util.Action<TParam1, TParam2, TParam3, TParam4, TParam5> action)
{
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
return action.ToString();
#else
return action.Method.ToDebugString();
#endif
}
public static string ToDebugString<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6>(this ModestTree.Util.Action<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6> action)
{
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
return action.ToString();
#else
return action.Method.ToDebugString();
#endif
}
public static string ToDebugString<TParam1>(this Func<TParam1> func)
{
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
return func.ToString();
#else
return func.Method.ToDebugString();
#endif
}
public static string ToDebugString<TParam1, TParam2>(this Func<TParam1, TParam2> func)
{
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
return func.ToString();
#else
return func.Method.ToDebugString();
#endif
}
public static string ToDebugString<TParam1, TParam2, TParam3>(this Func<TParam1, TParam2, TParam3> func)
{
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
return func.ToString();
#else
return func.Method.ToDebugString();
#endif
}
public static string ToDebugString<TParam1, TParam2, TParam3, TParam4>(this Func<TParam1, TParam2, TParam3, TParam4> func)
{
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
return func.ToString();
#else
return func.Method.ToDebugString();
#endif
}
public interface IMemberInfo
{
Type MemberType
{
get;
}
string MemberName
{
get;
}
object GetValue(object instance);
void SetValue(object instance, object value);
}
public class PropertyMemberInfo : IMemberInfo
{
PropertyInfo _propInfo;
public PropertyMemberInfo(PropertyInfo propInfo)
{
_propInfo = propInfo;
}
public Type MemberType
{
get
{
return _propInfo.PropertyType;
}
}
public string MemberName
{
get
{
return _propInfo.Name;
}
}
public object GetValue(object instance)
{
try
{
#if NOT_UNITY3D
return _propInfo.GetValue(instance, null);
#else
if (Application.platform == RuntimePlatform.WebGLPlayer)
{
// GetValue() doesn't work on webgl for some reason
// This is a bit slower though so only do this on webgl
return _propInfo.GetGetMethod().Invoke(instance, null);
}
else
{
return _propInfo.GetValue(instance, null);
}
#endif
}
catch (Exception e)
{
throw new Exception("Error occurred while accessing property '{0}'".Fmt(_propInfo.Name), e);
}
}
public void SetValue(object instance, object value)
{
_propInfo.SetValue(instance, value, null);
}
}
public class FieldMemberInfo : IMemberInfo
{
FieldInfo _fieldInfo;
public FieldMemberInfo(FieldInfo fieldInfo)
{
_fieldInfo = fieldInfo;
}
public Type MemberType
{
get
{
return _fieldInfo.FieldType;
}
}
public string MemberName
{
get
{
return _fieldInfo.Name;
}
}
public object GetValue(object instance)
{
return _fieldInfo.GetValue(instance);
}
public void SetValue(object instance, object value)
{
_fieldInfo.SetValue(instance, value);
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
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>
/// VirtualNetworkGatewayConnectionsOperations operations.
/// </summary>
internal partial class VirtualNetworkGatewayConnectionsOperations : IServiceOperations<NetworkManagementClient>, IVirtualNetworkGatewayConnectionsOperations
{
/// <summary>
/// Initializes a new instance of the VirtualNetworkGatewayConnectionsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal VirtualNetworkGatewayConnectionsOperations(NetworkManagementClient client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the NetworkManagementClient
/// </summary>
public NetworkManagementClient Client { get; private set; }
/// <summary>
/// The Put VirtualNetworkGatewayConnection operation creates/updates a
/// virtual network gateway connection in the specified resource group
/// through Network resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The name of the virtual network gateway conenction.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Begin Create or update Virtual Network Gateway
/// connection operation through Network resource provider.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<VirtualNetworkGatewayConnection>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, VirtualNetworkGatewayConnection parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<VirtualNetworkGatewayConnection> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(
resourceGroupName, virtualNetworkGatewayConnectionName, parameters, customHeaders, cancellationToken);
return await this.Client.GetPutOrPatchOperationResultAsync(_response,
customHeaders,
cancellationToken);
}
/// <summary>
/// The Put VirtualNetworkGatewayConnection operation creates/updates a
/// virtual network gateway connection in the specified resource group
/// through Network resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The name of the virtual network gateway conenction.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Begin Create or update Virtual Network Gateway
/// connection operation through Network resource provider.
/// </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<VirtualNetworkGatewayConnection>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, VirtualNetworkGatewayConnection parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (virtualNetworkGatewayConnectionName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkGatewayConnectionName");
}
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("virtualNetworkGatewayConnectionName", virtualNetworkGatewayConnectionName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{virtualNetworkGatewayConnectionName}", Uri.EscapeDataString(virtualNetworkGatewayConnectionName));
_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<VirtualNetworkGatewayConnection>();
_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<VirtualNetworkGatewayConnection>(_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<VirtualNetworkGatewayConnection>(_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>
/// The Get VirtualNetworkGatewayConnection operation retrieves information
/// about the specified virtual network gateway connection through Network
/// resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The name of the virtual network gateway connection.
/// </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<VirtualNetworkGatewayConnection>> GetWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (virtualNetworkGatewayConnectionName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkGatewayConnectionName");
}
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("virtualNetworkGatewayConnectionName", virtualNetworkGatewayConnectionName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{virtualNetworkGatewayConnectionName}", Uri.EscapeDataString(virtualNetworkGatewayConnectionName));
_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<VirtualNetworkGatewayConnection>();
_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<VirtualNetworkGatewayConnection>(_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>
/// The Delete VirtualNetworkGatewayConnection operation deletes the specifed
/// virtual network Gateway connection through Network resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The name of the virtual network gateway connection.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(
resourceGroupName, virtualNetworkGatewayConnectionName, customHeaders, cancellationToken);
return await this.Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken);
}
/// <summary>
/// The Delete VirtualNetworkGatewayConnection operation deletes the specifed
/// virtual network Gateway connection through Network resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The name of the virtual network gateway connection.
/// </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> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (virtualNetworkGatewayConnectionName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkGatewayConnectionName");
}
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("virtualNetworkGatewayConnectionName", virtualNetworkGatewayConnectionName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{virtualNetworkGatewayConnectionName}", Uri.EscapeDataString(virtualNetworkGatewayConnectionName));
_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 != 202 && (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>
/// The Get VirtualNetworkGatewayConnectionSharedKey operation retrieves
/// information about the specified virtual network gateway connection shared
/// key through Network resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='connectionSharedKeyName'>
/// The virtual network gateway connection shared key name.
/// </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<ConnectionSharedKeyResult>> GetSharedKeyWithHttpMessagesAsync(string resourceGroupName, string connectionSharedKeyName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (connectionSharedKeyName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "connectionSharedKeyName");
}
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("connectionSharedKeyName", connectionSharedKeyName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetSharedKey", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{connectionSharedKeyName}/sharedkey").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{connectionSharedKeyName}", Uri.EscapeDataString(connectionSharedKeyName));
_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<ConnectionSharedKeyResult>();
_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<ConnectionSharedKeyResult>(_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>
/// The List VirtualNetworkGatewayConnections operation retrieves all the
/// virtual network gateways connections created.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </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<IPage<VirtualNetworkGatewayConnection>>> 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.Network/connections").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<IPage<VirtualNetworkGatewayConnection>>();
_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<Page<VirtualNetworkGatewayConnection>>(_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>
/// The VirtualNetworkGatewayConnectionResetSharedKey operation resets the
/// virtual network gateway connection shared key for passed virtual network
/// gateway connection in the specified resource group through Network
/// resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The virtual network gateway connection reset shared key Name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Begin Reset Virtual Network Gateway connection
/// shared key operation through Network resource provider.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<ConnectionResetSharedKey>> ResetSharedKeyWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionResetSharedKey parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse<ConnectionResetSharedKey> _response = await BeginResetSharedKeyWithHttpMessagesAsync(
resourceGroupName, virtualNetworkGatewayConnectionName, parameters, customHeaders, cancellationToken);
return await this.Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken);
}
/// <summary>
/// The VirtualNetworkGatewayConnectionResetSharedKey operation resets the
/// virtual network gateway connection shared key for passed virtual network
/// gateway connection in the specified resource group through Network
/// resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The virtual network gateway connection reset shared key Name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Begin Reset Virtual Network Gateway connection
/// shared key operation through Network resource provider.
/// </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<ConnectionResetSharedKey>> BeginResetSharedKeyWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionResetSharedKey parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (virtualNetworkGatewayConnectionName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkGatewayConnectionName");
}
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("virtualNetworkGatewayConnectionName", virtualNetworkGatewayConnectionName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginResetSharedKey", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}/sharedkey/reset").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{virtualNetworkGatewayConnectionName}", Uri.EscapeDataString(virtualNetworkGatewayConnectionName));
_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("POST");
_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 != 202)
{
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<ConnectionResetSharedKey>();
_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<ConnectionResetSharedKey>(_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>
/// The Put VirtualNetworkGatewayConnectionSharedKey operation sets the
/// virtual network gateway connection shared key for passed virtual network
/// gateway connection in the specified resource group through Network
/// resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The virtual network gateway connection name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Begin Set Virtual Network Gateway conection
/// Shared key operation throughNetwork resource provider.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<ConnectionSharedKey>> SetSharedKeyWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionSharedKey parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<ConnectionSharedKey> _response = await BeginSetSharedKeyWithHttpMessagesAsync(
resourceGroupName, virtualNetworkGatewayConnectionName, parameters, customHeaders, cancellationToken);
return await this.Client.GetPutOrPatchOperationResultAsync(_response,
customHeaders,
cancellationToken);
}
/// <summary>
/// The Put VirtualNetworkGatewayConnectionSharedKey operation sets the
/// virtual network gateway connection shared key for passed virtual network
/// gateway connection in the specified resource group through Network
/// resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The virtual network gateway connection name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Begin Set Virtual Network Gateway conection
/// Shared key operation throughNetwork resource provider.
/// </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<ConnectionSharedKey>> BeginSetSharedKeyWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionSharedKey parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (virtualNetworkGatewayConnectionName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkGatewayConnectionName");
}
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("virtualNetworkGatewayConnectionName", virtualNetworkGatewayConnectionName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginSetSharedKey", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}/sharedkey").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{virtualNetworkGatewayConnectionName}", Uri.EscapeDataString(virtualNetworkGatewayConnectionName));
_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 != 201 && (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<ConnectionSharedKey>();
_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 == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<ConnectionSharedKey>(_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 == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<ConnectionSharedKey>(_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>
/// The List VirtualNetworkGatewayConnections operation retrieves all the
/// virtual network gateways connections created.
/// </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>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<VirtualNetworkGatewayConnection>>> 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 += "?" + 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<IPage<VirtualNetworkGatewayConnection>>();
_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<Page<VirtualNetworkGatewayConnection>>(_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;
}
}
}
| |
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
namespace Erlectric {
public class ETFCodec {
public static byte[] Encode(object obj, int? compress = null) {
if(compress != null) {
throw new NotSupportedException("compression not yet supported");
}
var parts = new List<byte[]>();
EncodePart(obj, parts);
var encoded = new byte[1 + parts.Sum(e => e.Length)];
int i = 0;
encoded[i++] = Constants.FORMAT_VERSION;
foreach(var part in parts) {
Buffer.BlockCopy(part, 0, encoded, i, part.Length);
i += part.Length;
}
return encoded;
}
public static byte[] ToBytes(string s) {
return Encoding.UTF8.GetBytes(s);
}
public static string ToUTF8(object bytes) {
return ToString(bytes, Encoding.UTF8);
}
public static string ToASCII(object bytes) {
return ToString(bytes, Encoding.ASCII);
}
public static string ToString(object bytes, Encoding enc) {
return enc.GetString((byte[])bytes);
}
internal static void EncodePart(object obj, List<byte[]> parts) {
switch(Convert.GetTypeCode(obj)) {
case TypeCode.String:
AddByte(parts, Constants.BINARY_EXT);
var bytes = Encoding.UTF8.GetBytes((string)obj);
parts.Add(UIntAsBigEndian((uint)bytes.Length));
parts.Add(bytes);
break;
case TypeCode.SByte:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
EncodePart(Convert.ToInt64(obj), parts);
break;
case TypeCode.UInt64:
EncodePart((ulong)obj, parts);
break;
case TypeCode.Single:
case TypeCode.Double:
AddByte(parts, Constants.NEW_FLOAT_EXT);
var dbytes = BitConverter.GetBytes(Convert.ToDouble(obj));
FlipBigEndian(dbytes);
parts.Add(dbytes);
break;
case TypeCode.Empty:
throw new NotSupportedException("null");
default:
EncodeOther(obj, parts);
break;
}
}
internal static void EncodePart(ulong u, List<byte[]> parts) {
if(u <= Byte.MaxValue) {
parts.Add(new byte[] { Constants.SMALL_INTEGER_EXT, (byte)u });
} else if (u <= Int32.MaxValue) {
EncodeInt((int)u, parts);
} else {
EncodeBig(u, 0, parts);
}
}
internal static void EncodePart(long i, List<byte[]> parts) {
if(i >= Int32.MinValue) {
if(i < 0) {
EncodeInt((int)i, parts);
} else if(i <= Byte.MaxValue) {
parts.Add(new byte[] { Constants.SMALL_INTEGER_EXT, (byte)i });
} else if (i <= Int32.MaxValue) {
EncodeInt((int)i, parts);
} else {
EncodeBig((ulong)i, 0, parts);
}
} else {
if(i == Int64.MinValue) {
parts.Add(new byte[] { Constants.SMALL_BIG_EXT, 8, 1, 0, 0, 0, 0, 0, 0, 0, 128 });
} else {
EncodeBig((ulong)-i, 1, parts);
}
}
}
internal static void EncodeOther(object obj, List<byte[]> parts) {
byte[] b = obj as byte[];
if(b != null) {
AddByte(parts, Constants.BINARY_EXT);
parts.Add(UIntAsBigEndian((uint)b.Length));
parts.Add(b);
return;
}
ETFTuple t = obj as ETFTuple;
if(t != null) {
if(t.Count <= Byte.MaxValue) {
parts.Add(new byte[] { Constants.SMALL_TUPLE_EXT, (byte)t.Count });
} else {
AddByte(parts, Constants.LARGE_TUPLE_EXT);
parts.Add(UIntAsBigEndian((uint)t.Count));
}
foreach(var e in t) {
EncodePart(e, parts);
}
return;
}
Atom a = obj as Atom;
if(a != null) {
if(a.Name.Length <= Byte.MaxValue) {
parts.Add(new byte[] { Constants.SMALL_ATOM_EXT, (byte)a.Name.Length });
} else {
AddByte(parts, Constants.ATOM_EXT);
parts.Add(UshortAsBigEndian((ushort)a.Name.Length));
}
parts.Add(a.Name);
return;
}
IList list = obj as IList;
if(list != null) {
if(list.Count > 0) {
AddByte(parts, Constants.LIST_EXT);
parts.Add(IntAsBigEndian(list.Count));
foreach(var e in list) {
EncodePart(e, parts);
}
}
AddByte(parts, Constants.NIL_EXT);
return;
}
throw new NotSupportedException(string.Format("{0}: {1}", obj.GetType(), obj.ToString()));
}
internal static void EncodeInt(int i, List<byte[]> parts) {
AddByte(parts, Constants.INTEGER_EXT);
parts.Add(IntAsBigEndian(i));
}
internal static void EncodeBig(ulong u, byte sign, List<byte[]> parts) {
var bytes = new List<byte>();
while(u > 0) {
bytes.Add((byte)u);
u >>= 8;
}
if(bytes.Count <= Byte.MaxValue) {
AddByte(parts, Constants.SMALL_BIG_EXT);
AddByte(parts, (byte)bytes.Count);
} else {
AddByte(parts, Constants.LARGE_BIG_EXT);
parts.Add(IntAsBigEndian(bytes.Count));
}
AddByte(parts, sign);
parts.Add(bytes.ToArray());
}
internal static void AddByte(List<byte[]> parts, byte b) {
parts.Add(new byte[] { b });
}
internal static byte[] IntAsBigEndian(int i) {
return FlipBigEndian(BitConverter.GetBytes(i));
}
internal static byte[] UIntAsBigEndian(uint i) {
return FlipBigEndian(BitConverter.GetBytes(i));
}
internal static byte[] UshortAsBigEndian(ushort u) {
return FlipBigEndian(BitConverter.GetBytes(u));
}
internal static byte[] FlipBigEndian(byte[] array) {
if(BitConverter.IsLittleEndian) {
Array.Reverse(array);
}
return array;
}
public static object Decode(byte[] encoded, int offset = 0) {
var version = encoded[offset++];
if(version != Constants.FORMAT_VERSION) {
throw new EncodingError(string.Format("Invalid version number {0} != {1}", version, Constants.FORMAT_VERSION));
}
return DecodePart(encoded, ref offset);
}
internal static object DecodePart(byte[] encoded, ref int offset) {
byte encoding_type = encoded[offset++];
switch(encoding_type) {
case Constants.SMALL_INTEGER_EXT:
return encoded[offset++];
case Constants.INTEGER_EXT:
return DecodeInt(encoded, ref offset);
case Constants.STRING_EXT:
ushort slen = DecodeUshort(encoded, ref offset);
var cl = new List<byte>(slen);
for(var i = 0; i < slen; i++) {
cl.Add(encoded[offset + i]);
}
offset += slen;
return cl;
case Constants.BINARY_EXT:
int blen = (int)DecodeUint(encoded, ref offset);
byte[] b = new byte[blen];
Buffer.BlockCopy(encoded, offset, b, 0, blen);
offset += blen;
return b;
case Constants.LIST_EXT:
uint llen = DecodeUint(encoded, ref offset);
var list = new ArrayList((int)llen);
DecodeList(encoded, ref offset, list, llen, true);
return list;
case Constants.SMALL_TUPLE_EXT:
var stlen = encoded[offset++];
var st = new ETFTuple(stlen);
DecodeList(encoded, ref offset, st, stlen);
return st;
case Constants.LARGE_TUPLE_EXT:
uint ltlen = DecodeUint(encoded, ref offset);
var lt = new ETFTuple((int)ltlen);
DecodeList(encoded, ref offset, lt, ltlen);
return lt;
case Constants.SMALL_ATOM_EXT:
var salen = encoded[offset++];
offset += salen;
return new Atom(encoded, offset - salen, salen);
case Constants.ATOM_EXT:
var alen = DecodeUshort(encoded, ref offset);
offset += alen;
return new Atom(encoded, offset - alen, alen);
case Constants.SMALL_BIG_EXT:
return DecodeBig(encoded, ref offset, encoded[offset++]);
case Constants.LARGE_BIG_EXT:
int size = (int)DecodeUint(encoded, ref offset);
return DecodeBig(encoded, ref offset, size);
case Constants.NEW_FLOAT_EXT:
return DecodeDouble(encoded, ref offset);
case Constants.FLOAT_EXT:
double dret;
string ds = Encoding.ASCII.GetString(encoded, offset, Constants.FLOAT_EXT_BYTES);
offset += Constants.FLOAT_EXT_BYTES;
NumberStyles style =
NumberStyles.AllowDecimalPoint
| NumberStyles.AllowExponent
| NumberStyles.AllowLeadingSign
| NumberStyles.AllowLeadingWhite;
if(Double.TryParse(ds, style, NumberFormatInfo.InvariantInfo, out dret)) {
return dret;
} else {
throw new EncodingError(string.Format("invalid float encoding: \"{0}\"", ds));
}
case Constants.NIL_EXT:
return new ArrayList();
default:
throw new EncodingError(string.Format("invalid encoding type: {0}", encoding_type));
}
}
internal static ArrayList DecodeList(byte[] encoded, ref int offset, ArrayList list, uint len, bool terminator = false) {
while(len-- > 0) {
list.Add(DecodePart(encoded, ref offset));
}
if(terminator && encoded[offset++] != Constants.NIL_EXT) {
throw new NotSupportedException("Improper lists not supported");
}
return list;
}
internal static int DecodeInt(byte[] encoded, ref int offset) {
var bytes = Read4HostEndian(encoded, ref offset);
return BitConverter.ToInt32(bytes, 0);
}
internal static uint DecodeUint(byte[] encoded, ref int offset) {
var bytes = Read4HostEndian(encoded, ref offset);
return BitConverter.ToUInt32(bytes, 0);
}
internal static ushort DecodeUshort(byte[] encoded, ref int offset) {
var bytes = Read2HostEndian(encoded, ref offset);
return BitConverter.ToUInt16(bytes, 0);
}
internal static double DecodeDouble(byte[] encoded, ref int offset) {
var bytes = new byte[8];
Buffer.BlockCopy(encoded, offset, bytes, 0, 8);
offset += 8;
FlipBigEndian(bytes);
return BitConverter.ToDouble(bytes, 0);
}
internal static byte[] Read2HostEndian(byte[] encoded, ref int offset) {
byte[] val;
if(BitConverter.IsLittleEndian) {
val = new byte[] { encoded[offset+1], encoded[offset] };
} else {
val = new byte[] { encoded[offset], encoded[offset+1] };
}
offset += 2;
return val;
}
internal static byte[] Read4HostEndian(byte[] encoded, ref int offset) {
byte[] val;
if(BitConverter.IsLittleEndian) {
val = new byte[] { encoded[offset+3], encoded[offset+2], encoded[offset+1], encoded[offset] };
} else {
val = new byte[] { encoded[offset], encoded[offset+1], encoded[offset+2], encoded[offset+3] };
}
offset += 4;
return val;
}
internal static object DecodeBig(byte[] encoded, ref int offset, int size) {
bool negative = 0x01 == encoded[offset++];
if(size > 8) {
throw new NotSupportedException(string.Format("integer too big to decode ({0} bytes)", size));
}
var buf = new byte[8];
Buffer.BlockCopy(encoded, offset, buf, 0, size);
if(!BitConverter.IsLittleEndian) {
Array.Reverse(buf);
}
offset += size;
ulong magnitude = BitConverter.ToUInt64(buf, 0);
object result = magnitude;
if(negative) {
if(magnitude > ((ulong)Int64.MaxValue) + 1UL) {
throw new NotSupportedException(string.Format("negative integer too big to convert"));
}
result = -(long)magnitude;
}
return result;
}
}
public class EncodingError : ApplicationException {
public EncodingError(string msg) : base(msg) {}
}
}
| |
// 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.IO;
using System.IO.Pipes;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Xunit;
namespace System.Diagnostics.ProcessTests
{
public partial class ProcessTest : IDisposable
{
private const int WaitInMS = 100 * 1000;
private const string CoreRunName = "corerun";
private const string TestExeName = "System.Diagnostics.Process.TestConsoleApp.exe";
private const int SuccessExitCode = 100;
private Process _process;
private List<Process> _processes = new List<Process>();
public ProcessTest()
{
_process = CreateProcessInfinite();
_process.Start();
}
public void Dispose()
{
// Ensure that there are no open processes with the same name as ProcessName
foreach (Process p in _processes)
{
if (!p.HasExited)
{
try
{
p.Kill();
}
catch (InvalidOperationException) { } // in case it was never started
Assert.True(p.WaitForExit(WaitInMS));
}
}
}
Process CreateProcess(string optionalArgument = ""/*String.Empty is not a constant*/)
{
Process p = new Process();
_processes.Add(p);
p.StartInfo.FileName = CoreRunName;
p.StartInfo.Arguments = string.IsNullOrWhiteSpace(optionalArgument) ?
TestExeName :
TestExeName + " " + optionalArgument;
// Profilers / code coverage tools doing coverage of the test process set environment
// variables to tell the targeted process what profiler to load. We don't want the child process
// to be profiled / have code coverage, so we remove these environment variables for that process
// before it's started.
p.StartInfo.Environment.Remove("Cor_Profiler");
p.StartInfo.Environment.Remove("Cor_Enable_Profiling");
p.StartInfo.Environment.Remove("CoreClr_Profiler");
p.StartInfo.Environment.Remove("CoreClr_Enable_Profiling");
return p;
}
Process CreateProcessInfinite()
{
return CreateProcess("infinite");
}
public void SetAndCheckBasePriority(ProcessPriorityClass exPriorityClass, int priority)
{
_process.PriorityClass = exPriorityClass;
_process.Refresh();
Assert.Equal(priority, _process.BasePriority);
}
[Fact, ActiveIssue(1538, PlatformID.OSX)]
public void Process_BasePriority()
{
ProcessPriorityClass originalPriority = _process.PriorityClass;
Assert.Equal(ProcessPriorityClass.Normal, originalPriority);
if (global::Interop.IsWindows)
{
try
{
//SetAndCheckBasePriority(ProcessPriorityClass.RealTime, 24);
SetAndCheckBasePriority(ProcessPriorityClass.High, 13);
SetAndCheckBasePriority(ProcessPriorityClass.Idle, 4);
SetAndCheckBasePriority(ProcessPriorityClass.Normal, 8);
}
finally
{
_process.PriorityClass = originalPriority;
}
}
}
public void Sleep(double delayInMs)
{
Task.Delay(TimeSpan.FromMilliseconds(delayInMs)).Wait();
}
public void Sleep()
{
Sleep(50D);
}
public void StartAndKillProcessWithDelay(Process p)
{
p.Start();
Sleep();
p.Kill();
Assert.True(p.WaitForExit(WaitInMS));
}
[Fact, ActiveIssue(1538, PlatformID.OSX)]
public void Process_EnableRaiseEvents()
{
{
bool isExitedInvoked = false;
// Test behavior when EnableRaisingEvent = true;
// Ensure event is called.
Process p = CreateProcessInfinite();
p.EnableRaisingEvents = true;
p.Exited += delegate { isExitedInvoked = true; };
StartAndKillProcessWithDelay(p);
Assert.True(isExitedInvoked, String.Format("Process_CanRaiseEvents0001: {0}", "isExited Event not called when EnableRaisingEvent is set to true."));
}
{
bool isExitedInvoked = false;
// Check with the default settings (false, events will not be raised)
Process p = CreateProcessInfinite();
p.Exited += delegate { isExitedInvoked = true; };
StartAndKillProcessWithDelay(p);
Assert.False(isExitedInvoked, String.Format("Process_CanRaiseEvents0002: {0}", "isExited Event called with the default settings for EnableRaiseEvents"));
}
{
bool isExitedInvoked = false;
// Same test, this time explicitly set the property to false
Process p = CreateProcessInfinite();
p.EnableRaisingEvents = false;
p.Exited += delegate { isExitedInvoked = true; }; ;
StartAndKillProcessWithDelay(p);
Assert.False(isExitedInvoked, String.Format("Process_CanRaiseEvents0003: {0}", "isExited Event called with the EnableRaiseEvents = false"));
}
}
[Fact, ActiveIssue(1538, PlatformID.OSX)]
public void Process_ExitCode()
{
{
Process p = CreateProcess();
p.Start();
Assert.True(p.WaitForExit(WaitInMS));
Assert.Equal(SuccessExitCode, p.ExitCode);
}
{
Process p = CreateProcessInfinite();
StartAndKillProcessWithDelay(p);
Assert.NotEqual(0, p.ExitCode);
}
}
[Fact]
public void Process_ExitTime()
{
DateTime timeBeforeProcessStart = DateTime.UtcNow;
Process p = CreateProcessInfinite();
StartAndKillProcessWithDelay(p);
Assert.True(p.ExitTime.ToUniversalTime() > timeBeforeProcessStart, "Process_ExitTime is incorrect.");
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void Process_GetHandle()
{
Assert.Equal(_process.Id, Interop.GetProcessId(_process.SafeHandle));
}
[Fact]
public void Process_HasExited()
{
{
Process p = CreateProcess();
p.Start();
Assert.True(p.WaitForExit(WaitInMS));
Assert.True(p.HasExited, "Process_HasExited001 failed");
}
{
Process p = CreateProcessInfinite();
p.Start();
try
{
Assert.False(p.HasExited, "Process_HasExited002 failed");
}
finally
{
p.Kill();
Assert.True(p.WaitForExit(WaitInMS));
}
Assert.True(p.HasExited, "Process_HasExited003 failed");
}
}
[Fact]
public void Process_MachineName()
{
// Checking that the MachineName returns some value.
Assert.NotNull(_process.MachineName);
}
[Fact]
public void Process_MainModule()
{
// Get MainModule property from a Process object
ProcessModule mainModule = null;
if (global::Interop.IsWindows)
{
mainModule = _process.MainModule;
}
else
{
Assert.Throws<PlatformNotSupportedException>(() => _process.MainModule);
}
if (mainModule != null)
{
Assert.Equal(CoreRunName, Path.GetFileNameWithoutExtension(mainModule.ModuleName));
// Check that the mainModule is present in the modules list.
bool foundMainModule = false;
if (_process.Modules != null)
{
foreach (ProcessModule pModule in _process.Modules)
{
if (String.Equals(Path.GetFileNameWithoutExtension(mainModule.ModuleName), CoreRunName, StringComparison.OrdinalIgnoreCase))
{
foundMainModule = true;
break;
}
}
Assert.True(foundMainModule, "Could not found Module " + mainModule.ModuleName);
}
}
}
[Fact, ActiveIssue(1538, PlatformID.OSX)]
public void Process_MaxWorkingSet()
{
IntPtr min, max;
uint flags;
long curValue = (long)_process.MaxWorkingSet;
Assert.True(curValue >= 0);
if (global::Interop.IsWindows)
{
try
{
_process.MaxWorkingSet = (IntPtr)((int)curValue + 1024);
Interop.GetProcessWorkingSetSizeEx(_process.SafeHandle, out min, out max, out flags);
curValue = (int)max;
_process.Refresh();
Assert.Equal(curValue, (int)_process.MaxWorkingSet);
}
finally
{
_process.MaxWorkingSet = (IntPtr)curValue;
}
}
}
[Fact, ActiveIssue(1538, PlatformID.OSX)]
public void Process_MinWorkingSet()
{
long curValue = (long)_process.MinWorkingSet;
Assert.True(curValue >= 0);
if (global::Interop.IsWindows)
{
try
{
_process.MinWorkingSet = (IntPtr)((int)curValue - 1024);
IntPtr min, max;
uint flags;
Interop.GetProcessWorkingSetSizeEx(_process.SafeHandle, out min, out max, out flags);
curValue = (int)min;
_process.Refresh();
Assert.Equal(curValue, (int)_process.MinWorkingSet);
}
finally
{
_process.MinWorkingSet = (IntPtr)curValue;
}
}
}
[Fact]
public void Process_Modules()
{
foreach (ProcessModule pModule in _process.Modules)
{
// Validated that we can get a value for each of the following.
Assert.NotNull(pModule);
Assert.NotNull(pModule.BaseAddress);
Assert.NotNull(pModule.EntryPointAddress);
Assert.NotNull(pModule.FileName);
int memSize = pModule.ModuleMemorySize;
Assert.NotNull(pModule.ModuleName);
}
}
private void AssertNonZeroWindowsZeroUnix(long value)
{
switch (global::Interop.PlatformDetection.OperatingSystem)
{
case global::Interop.OperatingSystem.Windows:
Assert.NotEqual(0, value);
break;
default:
Assert.Equal(0, value);
break;
}
}
[Fact, ActiveIssue(1538, PlatformID.OSX)]
public void Process_NonpagedSystemMemorySize64()
{
AssertNonZeroWindowsZeroUnix(_process.NonpagedSystemMemorySize64);
}
[Fact, ActiveIssue(1538, PlatformID.OSX)]
public void Process_PagedMemorySize64()
{
AssertNonZeroWindowsZeroUnix(_process.PagedMemorySize64);
}
[Fact, ActiveIssue(1538, PlatformID.OSX)]
public void Process_PagedSystemMemorySize64()
{
AssertNonZeroWindowsZeroUnix(_process.PagedSystemMemorySize64);
}
[Fact, ActiveIssue(1538, PlatformID.OSX)]
public void Process_PeakPagedMemorySize64()
{
AssertNonZeroWindowsZeroUnix(_process.PeakPagedMemorySize64);
}
[Fact, ActiveIssue(1538, PlatformID.OSX)]
public void Process_PeakVirtualMemorySize64()
{
AssertNonZeroWindowsZeroUnix(_process.PeakVirtualMemorySize64);
}
[Fact, ActiveIssue(1538, PlatformID.OSX)]
public void Process_PeakWorkingSet64()
{
AssertNonZeroWindowsZeroUnix(_process.PeakWorkingSet64);
}
[Fact, ActiveIssue(1538, PlatformID.OSX)]
public void Process_PrivateMemorySize64()
{
AssertNonZeroWindowsZeroUnix(_process.PrivateMemorySize64);
}
[Fact, ActiveIssue(1538, PlatformID.OSX)]
public void Process_PrivilegedProcessorTime()
{
Assert.True(_process.UserProcessorTime.TotalSeconds >= 0);
Assert.True(_process.PrivilegedProcessorTime.TotalSeconds >= 0);
Assert.True(_process.TotalProcessorTime.TotalSeconds >= 0);
}
[Fact, ActiveIssue(1538, PlatformID.OSX)]
public void Process_ProcessorAffinity()
{
IntPtr curProcessorAffinity = _process.ProcessorAffinity;
try
{
_process.ProcessorAffinity = new IntPtr(0x1);
Assert.Equal(new IntPtr(0x1), _process.ProcessorAffinity);
}
finally
{
_process.ProcessorAffinity = curProcessorAffinity;
Assert.Equal(curProcessorAffinity, _process.ProcessorAffinity);
}
}
[Fact]
public void Process_PriorityBoostEnabled()
{
bool isPriorityBoostEnabled = _process.PriorityBoostEnabled;
try
{
_process.PriorityBoostEnabled = true;
Assert.True(_process.PriorityBoostEnabled, "Process_PriorityBoostEnabled001 failed");
_process.PriorityBoostEnabled = false;
Assert.False(_process.PriorityBoostEnabled, "Process_PriorityBoostEnabled002 failed");
}
finally
{
_process.PriorityBoostEnabled = isPriorityBoostEnabled;
}
}
public void Process_PriorityClass()
{
ProcessPriorityClass priorityClass = _process.PriorityClass;
try
{
_process.PriorityClass = ProcessPriorityClass.High;
Assert.Equal(_process.PriorityClass, ProcessPriorityClass.High);
_process.PriorityClass = ProcessPriorityClass.Normal;
Assert.Equal(_process.PriorityClass, ProcessPriorityClass.Normal);
}
finally
{
_process.PriorityClass = priorityClass;
}
}
[Fact]
public void Process_InvalidPriorityClass()
{
Process p = new Process();
Assert.Throws<ArgumentException>(() => { p.PriorityClass = ProcessPriorityClass.Normal | ProcessPriorityClass.Idle; });
}
[Fact, ActiveIssue(1538, PlatformID.OSX)]
public void ProcessProcessName()
{
Assert.Equal(_process.ProcessName, CoreRunName, StringComparer.OrdinalIgnoreCase);
}
[DllImport("api-ms-win-core-processthreads-l1-1-0.dll")]
internal static extern int GetCurrentProcessId();
[DllImport("libc")]
internal static extern int getpid();
[Fact, ActiveIssue(1538, PlatformID.OSX)]
public void Process_GetCurrentProcess()
{
Process current = Process.GetCurrentProcess();
Assert.NotNull(current);
int currentProcessId = global::Interop.IsWindows ?
GetCurrentProcessId() :
getpid();
Assert.Equal(currentProcessId, current.Id);
Assert.Equal(Process.GetProcessById(currentProcessId).ProcessName, Process.GetCurrentProcess().ProcessName);
}
[Fact, ActiveIssue(1538, PlatformID.OSX)]
public void Process_GetProcesses()
{
// Get all the processes running on the machine.
Process currentProcess = Process.GetCurrentProcess();
var foundCurrentProcess = (from p in Process.GetProcesses()
where (p.Id == currentProcess.Id) && (p.ProcessName.Equals(currentProcess.ProcessName))
select p).Any();
Assert.True(foundCurrentProcess, "Process_GetProcesses001 failed");
foundCurrentProcess = (from p in Process.GetProcesses(currentProcess.MachineName)
where (p.Id == currentProcess.Id) && (p.ProcessName.Equals(currentProcess.ProcessName))
select p).Any();
Assert.True(foundCurrentProcess, "Process_GetProcesses002 failed");
}
[Fact, ActiveIssue(1538, PlatformID.OSX)]
public void Process_GetProcessesByName()
{
// Get the current process using its name
Process currentProcess = Process.GetCurrentProcess();
Assert.True(Process.GetProcessesByName(currentProcess.ProcessName).Count() > 0, "Process_GetProcessesByName001 failed");
Assert.True(Process.GetProcessesByName(currentProcess.ProcessName, currentProcess.MachineName).Count() > 0, "Process_GetProcessesByName001 failed");
}
[Fact]
public void Process_Environment()
{
Assert.NotEqual(0, new Process().StartInfo.Environment.Count);
ProcessStartInfo psi = new ProcessStartInfo();
// Creating a detached ProcessStartInfo will pre-populate the environment
// with current environmental variables.
var Environment2 = psi.Environment;
Assert.NotEqual(Environment2.Count, 0);
int CountItems = Environment2.Count;
Environment2.Add("NewKey", "NewValue");
Environment2.Add("NewKey2", "NewValue2");
Assert.Equal(CountItems + 2, Environment2.Count);
Environment2.Remove("NewKey");
Assert.Equal(CountItems + 1, Environment2.Count);
//Exception not thrown with invalid key
Assert.Throws<ArgumentException>(() => { Environment2.Add("NewKey2", "NewValue2"); });
//Clear
Environment2.Clear();
Assert.Equal(0, Environment2.Count);
//ContainsKey
Environment2.Add("NewKey", "NewValue");
Environment2.Add("NewKey2", "NewValue2");
Assert.True(Environment2.ContainsKey("NewKey"));
if (global::Interop.IsWindows)
{
Assert.True(Environment2.ContainsKey("newkey"));
}
Assert.False(Environment2.ContainsKey("NewKey99"));
//Iterating
string result = null;
int index = 0;
foreach (string e1 in Environment2.Values)
{
index++;
result += e1;
}
Assert.Equal(2, index);
Assert.Equal("NewValueNewValue2", result);
result = null;
index = 0;
foreach (string e1 in Environment2.Keys)
{
index++;
result += e1;
}
Assert.Equal("NewKeyNewKey2", result);
Assert.Equal(2, index);
result = null;
index = 0;
foreach (System.Collections.Generic.KeyValuePair<string, string> e1 in Environment2)
{
index++;
result += e1.Key;
}
Assert.Equal("NewKeyNewKey2", result);
Assert.Equal(2, index);
//Contains
Assert.True(Environment2.Contains(new System.Collections.Generic.KeyValuePair<string, string>("NewKey", "NewValue")));
if (global::Interop.IsWindows)
{
Assert.True(Environment2.Contains(new System.Collections.Generic.KeyValuePair<string, string>("nEwKeY", "NewValue")));
}
Assert.False(Environment2.Contains(new System.Collections.Generic.KeyValuePair<string, string>("NewKey99", "NewValue99")));
//Exception not thrown with invalid key
Assert.Throws<ArgumentNullException>(() =>
{
Environment2.Contains(new System.Collections.Generic.KeyValuePair<string, string>(null, "NewValue99"));
}
);
Environment2.Add(new System.Collections.Generic.KeyValuePair<string, string>("NewKey98", "NewValue98"));
//Indexed
string newIndexItem = Environment2["NewKey98"];
Assert.Equal("NewValue98", newIndexItem);
//TryGetValue
string stringout = null;
bool retval = false;
retval = Environment2.TryGetValue("NewKey", out stringout);
Assert.True(retval);
Assert.Equal("NewValue", stringout);
if (global::Interop.IsWindows)
{
retval = Environment2.TryGetValue("NeWkEy", out stringout);
Assert.True(retval);
Assert.Equal("NewValue", stringout);
}
stringout = null;
retval = false;
retval = Environment2.TryGetValue("NewKey99", out stringout);
Assert.Equal(null, stringout);
Assert.False(retval);
//Exception not thrown with invalid key
Assert.Throws<ArgumentNullException>(() =>
{
string stringout1 = null;
bool retval1 = false;
retval1 = Environment2.TryGetValue(null, out stringout1);
}
);
//Exception not thrown with invalid key
Assert.Throws<ArgumentNullException>(() =>
{
Environment2.Add(null, "NewValue2");
}
);
//Invalid Key to add
Assert.Throws<ArgumentException>(() =>
{
Environment2.Add("NewKey2", "NewValue2");
}
);
//Remove Item
Environment2.Remove("NewKey98");
Environment2.Remove("NewKey98"); //2nd occurrence should not assert
//Exception not thrown with null key
Assert.Throws<ArgumentNullException>(() => { Environment2.Remove(null); });
//"Exception not thrown with null key"
Assert.Throws<System.Collections.Generic.KeyNotFoundException>(() => { string a1 = Environment2["1bB"]; });
Assert.True(Environment2.Contains(new System.Collections.Generic.KeyValuePair<string, string>("NewKey2", "NewValue2")));
if (global::Interop.IsWindows)
{
Assert.True(Environment2.Contains(new System.Collections.Generic.KeyValuePair<string, string>("NEWKeY2", "NewValue2")));
}
Assert.False(Environment2.Contains(new System.Collections.Generic.KeyValuePair<string, string>("NewKey2", "newvalue2")));
Assert.False(Environment2.Contains(new System.Collections.Generic.KeyValuePair<string, string>("newkey2", "newvalue2")));
//Use KeyValuePair Enumerator
var x = Environment2.GetEnumerator();
x.MoveNext();
var y1 = x.Current;
Assert.Equal("NewKey NewValue", y1.Key + " " + y1.Value);
x.MoveNext();
y1 = x.Current;
Assert.Equal("NewKey2 NewValue2", y1.Key + " " + y1.Value);
//IsReadonly
Assert.False(Environment2.IsReadOnly);
Environment2.Add(new System.Collections.Generic.KeyValuePair<string, string>("NewKey3", "NewValue3"));
Environment2.Add(new System.Collections.Generic.KeyValuePair<string, string>("NewKey4", "NewValue4"));
//CopyTo
System.Collections.Generic.KeyValuePair<String, String>[] kvpa = new System.Collections.Generic.KeyValuePair<string, string>[10];
Environment2.CopyTo(kvpa, 0);
Assert.Equal("NewKey", kvpa[0].Key);
Assert.Equal("NewKey3", kvpa[2].Key);
Environment2.CopyTo(kvpa, 6);
Assert.Equal("NewKey", kvpa[6].Key);
//Exception not thrown with null key
Assert.Throws<System.ArgumentOutOfRangeException>(() => { Environment2.CopyTo(kvpa, -1); });
//Exception not thrown with null key
Assert.Throws<System.ArgumentException>(() => { Environment2.CopyTo(kvpa, 9); });
//Exception not thrown with null key
Assert.Throws<System.ArgumentNullException>(() =>
{
System.Collections.Generic.KeyValuePair<String, String>[] kvpanull = null;
Environment2.CopyTo(kvpanull, 0);
}
);
}
[Fact]
public void Process_StartInfo()
{
{
Process process = CreateProcessInfinite();
process.Start();
Assert.Equal(CoreRunName, process.StartInfo.FileName);
process.Kill();
Assert.True(process.WaitForExit(WaitInMS));
}
{
Process process = CreateProcessInfinite();
process.Start();
Assert.Throws<System.InvalidOperationException>(() => (process.StartInfo = new ProcessStartInfo()));
process.Kill();
Assert.True(process.WaitForExit(WaitInMS));
}
{
Process process = new Process();
process.StartInfo = new ProcessStartInfo(TestExeName);
Assert.Equal(TestExeName, process.StartInfo.FileName);
}
{
Process process = new Process();
Assert.Throws<ArgumentNullException>(() => process.StartInfo = null);
}
{
Process process = Process.GetCurrentProcess();
Assert.Throws<System.InvalidOperationException>(() => process.StartInfo);
}
}
[Fact]
public void Process_IPC()
{
Process p = CreateProcess("ipc");
using (var outbound = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable))
using (var inbound = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable))
{
p.StartInfo.Arguments += " " + outbound.GetClientHandleAsString() + " " + inbound.GetClientHandleAsString();
p.Start();
outbound.DisposeLocalCopyOfClientHandle();
inbound.DisposeLocalCopyOfClientHandle();
for (byte i = 0; i < 10; i++)
{
outbound.WriteByte(i);
int received = inbound.ReadByte();
Assert.Equal(i, received);
}
Assert.True(p.WaitForExit(WaitInMS));
Assert.Equal(SuccessExitCode, p.ExitCode);
}
}
}
}
| |
namespace Azure.Analytics.Synapse.Spark
{
public partial class SparkBatchClient
{
protected SparkBatchClient() { }
public SparkBatchClient(System.Uri endpoint, string sparkPoolName, Azure.Core.TokenCredential credential) { }
public SparkBatchClient(System.Uri endpoint, string sparkPoolName, Azure.Core.TokenCredential credential, Azure.Analytics.Synapse.Spark.SparkClientOptions options) { }
public virtual Azure.Response CancelSparkBatchJob(int batchId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response> CancelSparkBatchJobAsync(int batchId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.Analytics.Synapse.Spark.Models.SparkBatchJob> GetSparkBatchJob(int batchId, bool? detailed = default(bool?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Analytics.Synapse.Spark.Models.SparkBatchJob>> GetSparkBatchJobAsync(int batchId, bool? detailed = default(bool?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.Analytics.Synapse.Spark.Models.SparkBatchJobCollection> GetSparkBatchJobs(int? from = default(int?), int? size = default(int?), bool? detailed = default(bool?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Analytics.Synapse.Spark.Models.SparkBatchJobCollection>> GetSparkBatchJobsAsync(int? from = default(int?), int? size = default(int?), bool? detailed = default(bool?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Analytics.Synapse.Spark.SparkBatchOperation StartCreateSparkBatchJob(Azure.Analytics.Synapse.Spark.Models.SparkBatchJobOptions sparkBatchJobOptions, bool? detailed = default(bool?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Analytics.Synapse.Spark.SparkBatchOperation> StartCreateSparkBatchJobAsync(Azure.Analytics.Synapse.Spark.Models.SparkBatchJobOptions sparkBatchJobOptions, bool? detailed = default(bool?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
public partial class SparkBatchOperation : Azure.Operation<Azure.Analytics.Synapse.Spark.Models.SparkBatchJob>
{
internal SparkBatchOperation() { }
public override bool HasCompleted { get { throw null; } }
public override bool HasValue { get { throw null; } }
public override string Id { get { throw null; } }
public override Azure.Analytics.Synapse.Spark.Models.SparkBatchJob Value { get { throw null; } }
public override Azure.Response GetRawResponse() { throw null; }
public override Azure.Response UpdateStatus(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response> UpdateStatusAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.Analytics.Synapse.Spark.Models.SparkBatchJob>> WaitForCompletionAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.Analytics.Synapse.Spark.Models.SparkBatchJob>> WaitForCompletionAsync(System.TimeSpan pollingInterval, System.Threading.CancellationToken cancellationToken) { throw null; }
}
public partial class SparkClientOptions : Azure.Core.ClientOptions
{
public SparkClientOptions(Azure.Analytics.Synapse.Spark.SparkClientOptions.ServiceVersion serviceVersion = Azure.Analytics.Synapse.Spark.SparkClientOptions.ServiceVersion.V2019_11_01_preview) { }
public enum ServiceVersion
{
V2019_11_01_preview = 1,
}
}
public partial class SparkSessionClient
{
protected SparkSessionClient() { }
public SparkSessionClient(System.Uri endpoint, string sparkPoolName, Azure.Core.TokenCredential credential) { }
public SparkSessionClient(System.Uri endpoint, string sparkPoolName, Azure.Core.TokenCredential credential, Azure.Analytics.Synapse.Spark.SparkClientOptions options) { }
public virtual Azure.Response CancelSparkSession(int sessionId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response> CancelSparkSessionAsync(int sessionId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.Analytics.Synapse.Spark.Models.SparkStatementCancellationResult> CancelSparkStatement(int sessionId, int statementId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Analytics.Synapse.Spark.Models.SparkStatementCancellationResult>> CancelSparkStatementAsync(int sessionId, int statementId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.Analytics.Synapse.Spark.Models.SparkSession> GetSparkSession(int sessionId, bool? detailed = default(bool?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Analytics.Synapse.Spark.Models.SparkSession>> GetSparkSessionAsync(int sessionId, bool? detailed = default(bool?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.Analytics.Synapse.Spark.Models.SparkSessionCollection> GetSparkSessions(int? from = default(int?), int? size = default(int?), bool? detailed = default(bool?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Analytics.Synapse.Spark.Models.SparkSessionCollection>> GetSparkSessionsAsync(int? from = default(int?), int? size = default(int?), bool? detailed = default(bool?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.Analytics.Synapse.Spark.Models.SparkStatement> GetSparkStatement(int sessionId, int statementId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Analytics.Synapse.Spark.Models.SparkStatement>> GetSparkStatementAsync(int sessionId, int statementId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.Analytics.Synapse.Spark.Models.SparkStatementCollection> GetSparkStatements(int sessionId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Analytics.Synapse.Spark.Models.SparkStatementCollection>> GetSparkStatementsAsync(int sessionId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response ResetSparkSessionTimeout(int sessionId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response> ResetSparkSessionTimeoutAsync(int sessionId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Analytics.Synapse.Spark.SparkSessionOperation StartCreateSparkSession(Azure.Analytics.Synapse.Spark.Models.SparkSessionOptions sparkSessionOptions, bool? detailed = default(bool?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Analytics.Synapse.Spark.SparkSessionOperation> StartCreateSparkSessionAsync(Azure.Analytics.Synapse.Spark.Models.SparkSessionOptions sparkSessionOptions, bool? detailed = default(bool?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
public partial class SparkSessionOperation : Azure.Operation<Azure.Analytics.Synapse.Spark.Models.SparkSession>
{
internal SparkSessionOperation() { }
public override bool HasCompleted { get { throw null; } }
public override bool HasValue { get { throw null; } }
public override string Id { get { throw null; } }
public override Azure.Analytics.Synapse.Spark.Models.SparkSession Value { get { throw null; } }
public override Azure.Response GetRawResponse() { throw null; }
public override Azure.Response UpdateStatus(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response> UpdateStatusAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.Analytics.Synapse.Spark.Models.SparkSession>> WaitForCompletionAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.Analytics.Synapse.Spark.Models.SparkSession>> WaitForCompletionAsync(System.TimeSpan pollingInterval, System.Threading.CancellationToken cancellationToken) { throw null; }
}
public partial class SparkStatementOperation : Azure.Operation<Azure.Analytics.Synapse.Spark.Models.SparkStatement>
{
internal SparkStatementOperation() { }
public override bool HasCompleted { get { throw null; } }
public override bool HasValue { get { throw null; } }
public override string Id { get { throw null; } }
public override Azure.Analytics.Synapse.Spark.Models.SparkStatement Value { get { throw null; } }
public override Azure.Response GetRawResponse() { throw null; }
public override Azure.Response UpdateStatus(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response> UpdateStatusAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.Analytics.Synapse.Spark.Models.SparkStatement>> WaitForCompletionAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.Analytics.Synapse.Spark.Models.SparkStatement>> WaitForCompletionAsync(System.TimeSpan pollingInterval, System.Threading.CancellationToken cancellationToken) { throw null; }
}
}
namespace Azure.Analytics.Synapse.Spark.Models
{
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct PluginCurrentState : System.IEquatable<Azure.Analytics.Synapse.Spark.Models.PluginCurrentState>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public PluginCurrentState(string value) { throw null; }
public static Azure.Analytics.Synapse.Spark.Models.PluginCurrentState Cleanup { get { throw null; } }
public static Azure.Analytics.Synapse.Spark.Models.PluginCurrentState Ended { get { throw null; } }
public static Azure.Analytics.Synapse.Spark.Models.PluginCurrentState Monitoring { get { throw null; } }
public static Azure.Analytics.Synapse.Spark.Models.PluginCurrentState Preparation { get { throw null; } }
public static Azure.Analytics.Synapse.Spark.Models.PluginCurrentState Queued { get { throw null; } }
public static Azure.Analytics.Synapse.Spark.Models.PluginCurrentState ResourceAcquisition { get { throw null; } }
public static Azure.Analytics.Synapse.Spark.Models.PluginCurrentState Submission { get { throw null; } }
public bool Equals(Azure.Analytics.Synapse.Spark.Models.PluginCurrentState other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.Analytics.Synapse.Spark.Models.PluginCurrentState left, Azure.Analytics.Synapse.Spark.Models.PluginCurrentState right) { throw null; }
public static implicit operator Azure.Analytics.Synapse.Spark.Models.PluginCurrentState (string value) { throw null; }
public static bool operator !=(Azure.Analytics.Synapse.Spark.Models.PluginCurrentState left, Azure.Analytics.Synapse.Spark.Models.PluginCurrentState right) { throw null; }
public override string ToString() { throw null; }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct SchedulerCurrentState : System.IEquatable<Azure.Analytics.Synapse.Spark.Models.SchedulerCurrentState>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public SchedulerCurrentState(string value) { throw null; }
public static Azure.Analytics.Synapse.Spark.Models.SchedulerCurrentState Ended { get { throw null; } }
public static Azure.Analytics.Synapse.Spark.Models.SchedulerCurrentState Queued { get { throw null; } }
public static Azure.Analytics.Synapse.Spark.Models.SchedulerCurrentState Scheduled { get { throw null; } }
public bool Equals(Azure.Analytics.Synapse.Spark.Models.SchedulerCurrentState other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.Analytics.Synapse.Spark.Models.SchedulerCurrentState left, Azure.Analytics.Synapse.Spark.Models.SchedulerCurrentState right) { throw null; }
public static implicit operator Azure.Analytics.Synapse.Spark.Models.SchedulerCurrentState (string value) { throw null; }
public static bool operator !=(Azure.Analytics.Synapse.Spark.Models.SchedulerCurrentState left, Azure.Analytics.Synapse.Spark.Models.SchedulerCurrentState right) { throw null; }
public override string ToString() { throw null; }
}
public partial class SparkBatchJob
{
internal SparkBatchJob() { }
public string AppId { get { throw null; } }
public System.Collections.Generic.IReadOnlyDictionary<string, string> AppInfo { get { throw null; } }
public string ArtifactId { get { throw null; } }
public System.Collections.Generic.IReadOnlyList<Azure.Analytics.Synapse.Spark.Models.SparkServiceError> Errors { get { throw null; } }
public int Id { get { throw null; } }
public Azure.Analytics.Synapse.Spark.Models.SparkJobType? JobType { get { throw null; } }
public Azure.Analytics.Synapse.Spark.Models.SparkBatchJobState LivyInfo { get { throw null; } }
public System.Collections.Generic.IReadOnlyList<string> LogLines { get { throw null; } }
public string Name { get { throw null; } }
public Azure.Analytics.Synapse.Spark.Models.SparkServicePlugin Plugin { get { throw null; } }
public Azure.Analytics.Synapse.Spark.Models.SparkBatchJobResultType? Result { get { throw null; } }
public Azure.Analytics.Synapse.Spark.Models.SparkScheduler Scheduler { get { throw null; } }
public string SparkPoolName { get { throw null; } }
public string State { get { throw null; } }
public string SubmitterId { get { throw null; } }
public string SubmitterName { get { throw null; } }
public System.Collections.Generic.IReadOnlyDictionary<string, string> Tags { get { throw null; } }
public string WorkspaceName { get { throw null; } }
}
public partial class SparkBatchJobCollection
{
internal SparkBatchJobCollection() { }
public int From { get { throw null; } }
public System.Collections.Generic.IReadOnlyList<Azure.Analytics.Synapse.Spark.Models.SparkBatchJob> Sessions { get { throw null; } }
public int Total { get { throw null; } }
}
public partial class SparkBatchJobOptions
{
public SparkBatchJobOptions(string name, string file) { }
public System.Collections.Generic.IList<string> Archives { get { throw null; } }
public System.Collections.Generic.IList<string> Arguments { get { throw null; } }
public string ArtifactId { get { throw null; } set { } }
public string ClassName { get { throw null; } set { } }
public System.Collections.Generic.IDictionary<string, string> Configuration { get { throw null; } }
public int? DriverCores { get { throw null; } set { } }
public string DriverMemory { get { throw null; } set { } }
public int? ExecutorCores { get { throw null; } set { } }
public int? ExecutorCount { get { throw null; } set { } }
public string ExecutorMemory { get { throw null; } set { } }
public string File { get { throw null; } }
public System.Collections.Generic.IList<string> Files { get { throw null; } }
public System.Collections.Generic.IList<string> Jars { get { throw null; } }
public string Name { get { throw null; } }
public System.Collections.Generic.IList<string> PythonFiles { get { throw null; } }
public System.Collections.Generic.IDictionary<string, string> Tags { get { throw null; } }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct SparkBatchJobResultType : System.IEquatable<Azure.Analytics.Synapse.Spark.Models.SparkBatchJobResultType>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public SparkBatchJobResultType(string value) { throw null; }
public static Azure.Analytics.Synapse.Spark.Models.SparkBatchJobResultType Cancelled { get { throw null; } }
public static Azure.Analytics.Synapse.Spark.Models.SparkBatchJobResultType Failed { get { throw null; } }
public static Azure.Analytics.Synapse.Spark.Models.SparkBatchJobResultType Succeeded { get { throw null; } }
public static Azure.Analytics.Synapse.Spark.Models.SparkBatchJobResultType Uncertain { get { throw null; } }
public bool Equals(Azure.Analytics.Synapse.Spark.Models.SparkBatchJobResultType other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.Analytics.Synapse.Spark.Models.SparkBatchJobResultType left, Azure.Analytics.Synapse.Spark.Models.SparkBatchJobResultType right) { throw null; }
public static implicit operator Azure.Analytics.Synapse.Spark.Models.SparkBatchJobResultType (string value) { throw null; }
public static bool operator !=(Azure.Analytics.Synapse.Spark.Models.SparkBatchJobResultType left, Azure.Analytics.Synapse.Spark.Models.SparkBatchJobResultType right) { throw null; }
public override string ToString() { throw null; }
}
public partial class SparkBatchJobState
{
internal SparkBatchJobState() { }
public string CurrentState { get { throw null; } }
public System.DateTimeOffset? DeadAt { get { throw null; } }
public Azure.Analytics.Synapse.Spark.Models.SparkRequest JobCreationRequest { get { throw null; } }
public System.DateTimeOffset? NotStartedAt { get { throw null; } }
public System.DateTimeOffset? RecoveringAt { get { throw null; } }
public System.DateTimeOffset? RunningAt { get { throw null; } }
public System.DateTimeOffset? StartingAt { get { throw null; } }
public System.DateTimeOffset? SuccessAt { get { throw null; } }
public System.DateTimeOffset? TerminatedAt { get { throw null; } }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct SparkErrorSource : System.IEquatable<Azure.Analytics.Synapse.Spark.Models.SparkErrorSource>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public SparkErrorSource(string value) { throw null; }
public static Azure.Analytics.Synapse.Spark.Models.SparkErrorSource DependencyError { get { throw null; } }
public static Azure.Analytics.Synapse.Spark.Models.SparkErrorSource SystemError { get { throw null; } }
public static Azure.Analytics.Synapse.Spark.Models.SparkErrorSource UnknownError { get { throw null; } }
public static Azure.Analytics.Synapse.Spark.Models.SparkErrorSource UserError { get { throw null; } }
public bool Equals(Azure.Analytics.Synapse.Spark.Models.SparkErrorSource other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.Analytics.Synapse.Spark.Models.SparkErrorSource left, Azure.Analytics.Synapse.Spark.Models.SparkErrorSource right) { throw null; }
public static implicit operator Azure.Analytics.Synapse.Spark.Models.SparkErrorSource (string value) { throw null; }
public static bool operator !=(Azure.Analytics.Synapse.Spark.Models.SparkErrorSource left, Azure.Analytics.Synapse.Spark.Models.SparkErrorSource right) { throw null; }
public override string ToString() { throw null; }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct SparkJobType : System.IEquatable<Azure.Analytics.Synapse.Spark.Models.SparkJobType>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public SparkJobType(string value) { throw null; }
public static Azure.Analytics.Synapse.Spark.Models.SparkJobType SparkBatch { get { throw null; } }
public static Azure.Analytics.Synapse.Spark.Models.SparkJobType SparkSession { get { throw null; } }
public bool Equals(Azure.Analytics.Synapse.Spark.Models.SparkJobType other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.Analytics.Synapse.Spark.Models.SparkJobType left, Azure.Analytics.Synapse.Spark.Models.SparkJobType right) { throw null; }
public static implicit operator Azure.Analytics.Synapse.Spark.Models.SparkJobType (string value) { throw null; }
public static bool operator !=(Azure.Analytics.Synapse.Spark.Models.SparkJobType left, Azure.Analytics.Synapse.Spark.Models.SparkJobType right) { throw null; }
public override string ToString() { throw null; }
}
public partial class SparkRequest
{
internal SparkRequest() { }
public System.Collections.Generic.IReadOnlyList<string> Archives { get { throw null; } }
public System.Collections.Generic.IReadOnlyList<string> Arguments { get { throw null; } }
public string ClassName { get { throw null; } }
public System.Collections.Generic.IReadOnlyDictionary<string, string> Configuration { get { throw null; } }
public int? DriverCores { get { throw null; } }
public string DriverMemory { get { throw null; } }
public int? ExecutorCores { get { throw null; } }
public int? ExecutorCount { get { throw null; } }
public string ExecutorMemory { get { throw null; } }
public string File { get { throw null; } }
public System.Collections.Generic.IReadOnlyList<string> Files { get { throw null; } }
public System.Collections.Generic.IReadOnlyList<string> Jars { get { throw null; } }
public string Name { get { throw null; } }
public System.Collections.Generic.IReadOnlyList<string> PythonFiles { get { throw null; } }
}
public partial class SparkScheduler
{
internal SparkScheduler() { }
public System.DateTimeOffset? CancellationRequestedAt { get { throw null; } }
public Azure.Analytics.Synapse.Spark.Models.SchedulerCurrentState? CurrentState { get { throw null; } }
public System.DateTimeOffset? EndedAt { get { throw null; } }
public System.DateTimeOffset? ScheduledAt { get { throw null; } }
public System.DateTimeOffset? SubmittedAt { get { throw null; } }
}
public partial class SparkServiceError
{
internal SparkServiceError() { }
public string ErrorCode { get { throw null; } }
public string Message { get { throw null; } }
public Azure.Analytics.Synapse.Spark.Models.SparkErrorSource? Source { get { throw null; } }
}
public partial class SparkServicePlugin
{
internal SparkServicePlugin() { }
public System.DateTimeOffset? CleanupStartedAt { get { throw null; } }
public Azure.Analytics.Synapse.Spark.Models.PluginCurrentState? CurrentState { get { throw null; } }
public System.DateTimeOffset? MonitoringStartedAt { get { throw null; } }
public System.DateTimeOffset? PreparationStartedAt { get { throw null; } }
public System.DateTimeOffset? ResourceAcquisitionStartedAt { get { throw null; } }
public System.DateTimeOffset? SubmissionStartedAt { get { throw null; } }
}
public partial class SparkSession
{
internal SparkSession() { }
public string AppId { get { throw null; } }
public System.Collections.Generic.IReadOnlyDictionary<string, string> AppInfo { get { throw null; } }
public string ArtifactId { get { throw null; } }
public System.Collections.Generic.IReadOnlyList<Azure.Analytics.Synapse.Spark.Models.SparkServiceError> Errors { get { throw null; } }
public int Id { get { throw null; } }
public Azure.Analytics.Synapse.Spark.Models.SparkJobType? JobType { get { throw null; } }
public Azure.Analytics.Synapse.Spark.Models.SparkSessionState LivyInfo { get { throw null; } }
public System.Collections.Generic.IReadOnlyList<string> LogLines { get { throw null; } }
public string Name { get { throw null; } }
public Azure.Analytics.Synapse.Spark.Models.SparkServicePlugin Plugin { get { throw null; } }
public Azure.Analytics.Synapse.Spark.Models.SparkSessionResultType? Result { get { throw null; } }
public Azure.Analytics.Synapse.Spark.Models.SparkScheduler Scheduler { get { throw null; } }
public string SparkPoolName { get { throw null; } }
public string State { get { throw null; } }
public string SubmitterId { get { throw null; } }
public string SubmitterName { get { throw null; } }
public System.Collections.Generic.IReadOnlyDictionary<string, string> Tags { get { throw null; } }
public string WorkspaceName { get { throw null; } }
}
public partial class SparkSessionCollection
{
internal SparkSessionCollection() { }
public int From { get { throw null; } }
public System.Collections.Generic.IReadOnlyList<Azure.Analytics.Synapse.Spark.Models.SparkSession> Sessions { get { throw null; } }
public int Total { get { throw null; } }
}
public partial class SparkSessionOptions
{
public SparkSessionOptions(string name) { }
public System.Collections.Generic.IList<string> Archives { get { throw null; } }
public System.Collections.Generic.IList<string> Arguments { get { throw null; } }
public string ArtifactId { get { throw null; } set { } }
public string ClassName { get { throw null; } set { } }
public System.Collections.Generic.IDictionary<string, string> Configuration { get { throw null; } }
public int? DriverCores { get { throw null; } set { } }
public string DriverMemory { get { throw null; } set { } }
public int? ExecutorCores { get { throw null; } set { } }
public int? ExecutorCount { get { throw null; } set { } }
public string ExecutorMemory { get { throw null; } set { } }
public string File { get { throw null; } set { } }
public System.Collections.Generic.IList<string> Files { get { throw null; } }
public System.Collections.Generic.IList<string> Jars { get { throw null; } }
public string Name { get { throw null; } }
public System.Collections.Generic.IList<string> PythonFiles { get { throw null; } }
public System.Collections.Generic.IDictionary<string, string> Tags { get { throw null; } }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct SparkSessionResultType : System.IEquatable<Azure.Analytics.Synapse.Spark.Models.SparkSessionResultType>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public SparkSessionResultType(string value) { throw null; }
public static Azure.Analytics.Synapse.Spark.Models.SparkSessionResultType Cancelled { get { throw null; } }
public static Azure.Analytics.Synapse.Spark.Models.SparkSessionResultType Failed { get { throw null; } }
public static Azure.Analytics.Synapse.Spark.Models.SparkSessionResultType Succeeded { get { throw null; } }
public static Azure.Analytics.Synapse.Spark.Models.SparkSessionResultType Uncertain { get { throw null; } }
public bool Equals(Azure.Analytics.Synapse.Spark.Models.SparkSessionResultType other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.Analytics.Synapse.Spark.Models.SparkSessionResultType left, Azure.Analytics.Synapse.Spark.Models.SparkSessionResultType right) { throw null; }
public static implicit operator Azure.Analytics.Synapse.Spark.Models.SparkSessionResultType (string value) { throw null; }
public static bool operator !=(Azure.Analytics.Synapse.Spark.Models.SparkSessionResultType left, Azure.Analytics.Synapse.Spark.Models.SparkSessionResultType right) { throw null; }
public override string ToString() { throw null; }
}
public partial class SparkSessionState
{
internal SparkSessionState() { }
public System.DateTimeOffset? BusyAt { get { throw null; } }
public string CurrentState { get { throw null; } }
public System.DateTimeOffset? DeadAt { get { throw null; } }
public System.DateTimeOffset? ErrorAt { get { throw null; } }
public System.DateTimeOffset? IdleAt { get { throw null; } }
public Azure.Analytics.Synapse.Spark.Models.SparkRequest JobCreationRequest { get { throw null; } }
public System.DateTimeOffset? NotStartedAt { get { throw null; } }
public System.DateTimeOffset? RecoveringAt { get { throw null; } }
public System.DateTimeOffset? ShuttingDownAt { get { throw null; } }
public System.DateTimeOffset? StartingAt { get { throw null; } }
public System.DateTimeOffset? TerminatedAt { get { throw null; } }
}
public partial class SparkStatement
{
internal SparkStatement() { }
public string Code { get { throw null; } }
public int Id { get { throw null; } }
public Azure.Analytics.Synapse.Spark.Models.SparkStatementOutput Output { get { throw null; } }
public string State { get { throw null; } }
}
public partial class SparkStatementCancellationResult
{
internal SparkStatementCancellationResult() { }
public string Message { get { throw null; } }
}
public partial class SparkStatementCollection
{
internal SparkStatementCollection() { }
public System.Collections.Generic.IReadOnlyList<Azure.Analytics.Synapse.Spark.Models.SparkStatement> Statements { get { throw null; } }
public int Total { get { throw null; } }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct SparkStatementLanguageType : System.IEquatable<Azure.Analytics.Synapse.Spark.Models.SparkStatementLanguageType>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public SparkStatementLanguageType(string value) { throw null; }
public static Azure.Analytics.Synapse.Spark.Models.SparkStatementLanguageType DotNetSpark { get { throw null; } }
public static Azure.Analytics.Synapse.Spark.Models.SparkStatementLanguageType PySpark { get { throw null; } }
public static Azure.Analytics.Synapse.Spark.Models.SparkStatementLanguageType Spark { get { throw null; } }
public static Azure.Analytics.Synapse.Spark.Models.SparkStatementLanguageType Sql { get { throw null; } }
public bool Equals(Azure.Analytics.Synapse.Spark.Models.SparkStatementLanguageType other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.Analytics.Synapse.Spark.Models.SparkStatementLanguageType left, Azure.Analytics.Synapse.Spark.Models.SparkStatementLanguageType right) { throw null; }
public static implicit operator Azure.Analytics.Synapse.Spark.Models.SparkStatementLanguageType (string value) { throw null; }
public static bool operator !=(Azure.Analytics.Synapse.Spark.Models.SparkStatementLanguageType left, Azure.Analytics.Synapse.Spark.Models.SparkStatementLanguageType right) { throw null; }
public override string ToString() { throw null; }
}
public partial class SparkStatementOptions
{
public SparkStatementOptions() { }
public string Code { get { throw null; } set { } }
public Azure.Analytics.Synapse.Spark.Models.SparkStatementLanguageType? Kind { get { throw null; } set { } }
}
public partial class SparkStatementOutput
{
internal SparkStatementOutput() { }
public object Data { get { throw null; } }
public string ErrorName { get { throw null; } }
public string ErrorValue { get { throw null; } }
public int ExecutionCount { get { throw null; } }
public string Status { get { throw null; } }
public System.Collections.Generic.IReadOnlyList<string> Traceback { get { throw null; } }
}
}
| |
// <copyright file="BaggagePropagatorTest.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry 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.
// </copyright>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using Xunit;
namespace OpenTelemetry.Context.Propagation.Tests
{
public class BaggagePropagatorTest
{
private static readonly Func<IDictionary<string, string>, string, IEnumerable<string>> Getter =
(d, k) =>
{
d.TryGetValue(k, out var v);
return new string[] { v };
};
private static readonly Func<IList<KeyValuePair<string, string>>, string, IEnumerable<string>> GetterList =
(d, k) =>
{
return d.Where(i => i.Key == k).Select(i => i.Value);
};
private static readonly Action<IDictionary<string, string>, string, string> Setter = (carrier, name, value) =>
{
carrier[name] = value;
};
private readonly BaggagePropagator baggage = new BaggagePropagator();
[Fact]
public void ValidateFieldsProperty()
{
Assert.Equal(new HashSet<string> { BaggagePropagator.BaggageHeaderName }, this.baggage.Fields);
Assert.Single(this.baggage.Fields);
}
[Fact]
public void ValidateDefaultCarrierExtraction()
{
var propagationContext = this.baggage.Extract<string>(default, null, null);
Assert.Equal(default, propagationContext);
}
[Fact]
public void ValidateDefaultGetterExtraction()
{
var carrier = new Dictionary<string, string>();
var propagationContext = this.baggage.Extract(default, carrier, null);
Assert.Equal(default, propagationContext);
}
[Fact]
public void ValidateNoBaggageExtraction()
{
var carrier = new Dictionary<string, string>();
var propagationContext = this.baggage.Extract(default, carrier, Getter);
Assert.Equal(default, propagationContext);
}
[Fact]
public void ValidateOneBaggageExtraction()
{
var carrier = new Dictionary<string, string>
{
{ BaggagePropagator.BaggageHeaderName, "name=test" },
};
var propagationContext = this.baggage.Extract(default, carrier, Getter);
Assert.False(propagationContext == default);
Assert.Single(propagationContext.Baggage.GetBaggage());
var baggage = propagationContext.Baggage.GetBaggage().FirstOrDefault();
Assert.Equal("name", baggage.Key);
Assert.Equal("test", baggage.Value);
}
[Fact]
public void ValidateMultipleBaggageExtraction()
{
var carrier = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>(BaggagePropagator.BaggageHeaderName, "name1=test1"),
new KeyValuePair<string, string>(BaggagePropagator.BaggageHeaderName, "name2=test2"),
new KeyValuePair<string, string>(BaggagePropagator.BaggageHeaderName, "name2=test2"),
};
var propagationContext = this.baggage.Extract(default, carrier, GetterList);
Assert.False(propagationContext == default);
Assert.True(propagationContext.ActivityContext == default);
Assert.Equal(2, propagationContext.Baggage.Count);
var array = propagationContext.Baggage.GetBaggage().ToArray();
Assert.Equal("name1", array[0].Key);
Assert.Equal("test1", array[0].Value);
Assert.Equal("name2", array[1].Key);
Assert.Equal("test2", array[1].Value);
}
[Fact]
public void ValidateLongBaggageExtraction()
{
var carrier = new Dictionary<string, string>
{
{ BaggagePropagator.BaggageHeaderName, $"name={new string('x', 8186)},clientId=1234" },
};
var propagationContext = this.baggage.Extract(default, carrier, Getter);
Assert.False(propagationContext == default);
Assert.Single(propagationContext.Baggage.GetBaggage());
var array = propagationContext.Baggage.GetBaggage().ToArray();
Assert.Equal("name", array[0].Key);
Assert.Equal(new string('x', 8186), array[0].Value);
}
[Fact]
public void ValidateSpecialCharsBaggageExtraction()
{
var encodedKey = WebUtility.UrlEncode("key2");
var encodedValue = WebUtility.UrlEncode("!x_x,x-x&x(x\");:");
var escapedKey = Uri.EscapeDataString("key()3");
var escapedValue = Uri.EscapeDataString("value()!&;:");
Assert.Equal("key2", encodedKey);
Assert.Equal("!x_x%2Cx-x%26x(x%22)%3B%3A", encodedValue);
Assert.Equal("key%28%293", escapedKey);
Assert.Equal("value%28%29%21%26%3B%3A", escapedValue);
var initialBaggage = $"key+1=value+1,{encodedKey}={encodedValue},{escapedKey}={escapedValue}";
var carrier = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>(BaggagePropagator.BaggageHeaderName, initialBaggage),
};
var propagationContext = this.baggage.Extract(default, carrier, GetterList);
Assert.False(propagationContext == default);
Assert.True(propagationContext.ActivityContext == default);
Assert.Equal(3, propagationContext.Baggage.Count);
var actualBaggage = propagationContext.Baggage.GetBaggage();
Assert.Equal(3, actualBaggage.Count);
Assert.True(actualBaggage.ContainsKey("key 1"));
Assert.Equal("value 1", actualBaggage["key 1"]);
Assert.True(actualBaggage.ContainsKey("key2"));
Assert.Equal("!x_x,x-x&x(x\");:", actualBaggage["key2"]);
Assert.True(actualBaggage.ContainsKey("key()3"));
Assert.Equal("value()!&;:", actualBaggage["key()3"]);
}
[Fact]
public void ValidateEmptyBaggageInjection()
{
var carrier = new Dictionary<string, string>();
this.baggage.Inject(default, carrier, Setter);
Assert.Empty(carrier);
}
[Fact]
public void ValidateBaggageInjection()
{
var carrier = new Dictionary<string, string>();
var propagationContext = new PropagationContext(
default,
new Baggage(new Dictionary<string, string>
{
{ "key1", "value1" },
{ "key2", "value2" },
}));
this.baggage.Inject(propagationContext, carrier, Setter);
Assert.Single(carrier);
Assert.Equal("key1=value1,key2=value2", carrier[BaggagePropagator.BaggageHeaderName]);
}
[Fact]
public void ValidateSpecialCharsBaggageInjection()
{
var carrier = new Dictionary<string, string>();
var propagationContext = new PropagationContext(
default,
new Baggage(new Dictionary<string, string>
{
{ "key 1", "value 1" },
{ "key2", "!x_x,x-x&x(x\");:" },
}));
this.baggage.Inject(propagationContext, carrier, Setter);
Assert.Single(carrier);
Assert.Equal("key+1=value+1,key2=!x_x%2Cx-x%26x(x%22)%3B%3A", carrier[BaggagePropagator.BaggageHeaderName]);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net.Cache;
using System.Net.Http;
using System.Net.Security;
using System.Runtime.Serialization;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net
{
public delegate void HttpContinueDelegate(int StatusCode, WebHeaderCollection httpHeaders);
public class HttpWebRequest : WebRequest, ISerializable
{
private const int DefaultContinueTimeout = 350; // Current default value from .NET Desktop.
private const int DefaultReadWriteTimeout = 5 * 60 * 1000; // 5 minutes
private WebHeaderCollection _webHeaderCollection = new WebHeaderCollection();
private Uri _requestUri;
private string _originVerb = HttpMethod.Get.Method;
// We allow getting and setting this (to preserve app-compat). But we don't do anything with it
// as the underlying System.Net.Http API doesn't support it.
private int _continueTimeout = DefaultContinueTimeout;
private bool _allowReadStreamBuffering = false;
private CookieContainer _cookieContainer = null;
private ICredentials _credentials = null;
private IWebProxy _proxy = WebRequest.DefaultWebProxy;
private Task<HttpResponseMessage> _sendRequestTask;
private static int _defaultMaxResponseHeadersLength = HttpHandlerDefaults.DefaultMaxResponseHeadersLength;
private int _beginGetRequestStreamCalled = 0;
private int _beginGetResponseCalled = 0;
private int _endGetRequestStreamCalled = 0;
private int _endGetResponseCalled = 0;
private int _maximumAllowedRedirections = HttpHandlerDefaults.DefaultMaxAutomaticRedirections;
private int _maximumResponseHeadersLen = _defaultMaxResponseHeadersLength;
private ServicePoint _servicePoint;
private int _timeout = WebRequest.DefaultTimeoutMilliseconds;
private int _readWriteTimeout = DefaultReadWriteTimeout;
private HttpContinueDelegate _continueDelegate;
// stores the user provided Host header as Uri. If the user specified a default port explicitly we'll lose
// that information when converting the host string to a Uri. _HostHasPort will store that information.
private bool _hostHasPort;
private Uri _hostUri;
private RequestStream _requestStream;
private TaskCompletionSource<Stream> _requestStreamOperation = null;
private TaskCompletionSource<WebResponse> _responseOperation = null;
private AsyncCallback _requestStreamCallback = null;
private AsyncCallback _responseCallback = null;
private int _abortCalled = 0;
private CancellationTokenSource _sendRequestCts;
private X509CertificateCollection _clientCertificates;
private Booleans _booleans = Booleans.Default;
private bool _pipelined = true;
private bool _preAuthenticate;
private DecompressionMethods _automaticDecompression = HttpHandlerDefaults.DefaultAutomaticDecompression;
//these should be safe.
[Flags]
private enum Booleans : uint
{
AllowAutoRedirect = 0x00000001,
AllowWriteStreamBuffering = 0x00000002,
ExpectContinue = 0x00000004,
ProxySet = 0x00000010,
UnsafeAuthenticatedConnectionSharing = 0x00000040,
IsVersionHttp10 = 0x00000080,
SendChunked = 0x00000100,
EnableDecompression = 0x00000200,
IsTunnelRequest = 0x00000400,
IsWebSocketRequest = 0x00000800,
Default = AllowAutoRedirect | AllowWriteStreamBuffering | ExpectContinue
}
private const string ContinueHeader = "100-continue";
private const string ChunkedHeader = "chunked";
private const string GZipHeader = "gzip";
private const string DeflateHeader = "deflate";
public HttpWebRequest()
{
}
[Obsolete("Serialization is obsoleted for this type. https://go.microsoft.com/fwlink/?linkid=14202")]
protected HttpWebRequest(SerializationInfo serializationInfo, StreamingContext streamingContext) : base(serializationInfo, streamingContext)
{
throw new PlatformNotSupportedException();
}
void ISerializable.GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
throw new PlatformNotSupportedException();
}
protected override void GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
throw new PlatformNotSupportedException();
}
internal HttpWebRequest(Uri uri)
{
_requestUri = uri;
}
private void SetSpecialHeaders(string HeaderName, string value)
{
_webHeaderCollection.Remove(HeaderName);
if (!string.IsNullOrEmpty(value))
{
_webHeaderCollection[HeaderName] = value;
}
}
public string Accept
{
get
{
return _webHeaderCollection[HttpKnownHeaderNames.Accept];
}
set
{
SetSpecialHeaders(HttpKnownHeaderNames.Accept, value);
}
}
public virtual bool AllowReadStreamBuffering
{
get
{
return _allowReadStreamBuffering;
}
set
{
_allowReadStreamBuffering = value;
}
}
public int MaximumResponseHeadersLength
{
get => _maximumResponseHeadersLen;
set
{
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_reqsubmitted);
}
if (value < 0 && value != System.Threading.Timeout.Infinite)
{
throw new ArgumentOutOfRangeException(nameof(value), SR.net_toosmall);
}
_maximumResponseHeadersLen = value;
}
}
public int MaximumAutomaticRedirections
{
get
{
return _maximumAllowedRedirections;
}
set
{
if (value <= 0)
{
throw new ArgumentException(SR.net_toosmall, nameof(value));
}
_maximumAllowedRedirections = value;
}
}
public override string ContentType
{
get
{
return _webHeaderCollection[HttpKnownHeaderNames.ContentType];
}
set
{
SetSpecialHeaders(HttpKnownHeaderNames.ContentType, value);
}
}
public int ContinueTimeout
{
get
{
return _continueTimeout;
}
set
{
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_reqsubmitted);
}
if ((value < 0) && (value != System.Threading.Timeout.Infinite))
{
throw new ArgumentOutOfRangeException(nameof(value), SR.net_io_timeout_use_ge_zero);
}
_continueTimeout = value;
}
}
public override int Timeout
{
get
{
return _timeout;
}
set
{
if (value < 0 && value != System.Threading.Timeout.Infinite)
{
throw new ArgumentOutOfRangeException(nameof(value), SR.net_io_timeout_use_ge_zero);
}
_timeout = value;
}
}
public override long ContentLength
{
get
{
long value;
long.TryParse(_webHeaderCollection[HttpKnownHeaderNames.ContentLength], out value);
return value;
}
set
{
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_writestarted);
}
if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(value), SR.net_clsmall);
}
SetSpecialHeaders(HttpKnownHeaderNames.ContentLength, value.ToString());
}
}
public Uri Address
{
get
{
return _requestUri;
}
}
public string UserAgent
{
get
{
return _webHeaderCollection[HttpKnownHeaderNames.UserAgent];
}
set
{
SetSpecialHeaders(HttpKnownHeaderNames.UserAgent, value);
}
}
public string Host
{
get
{
Uri hostUri = _hostUri ?? Address;
return (_hostUri == null || !_hostHasPort) && Address.IsDefaultPort ?
hostUri.Host :
hostUri.Host + ":" + hostUri.Port;
}
set
{
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_writestarted);
}
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
Uri hostUri;
if ((value.Contains('/')) || (!TryGetHostUri(value, out hostUri)))
{
throw new ArgumentException(SR.net_invalid_host, nameof(value));
}
_hostUri = hostUri;
// Determine if the user provided string contains a port
if (!_hostUri.IsDefaultPort)
{
_hostHasPort = true;
}
else if (!value.Contains(':'))
{
_hostHasPort = false;
}
else
{
int endOfIPv6Address = value.IndexOf(']');
_hostHasPort = endOfIPv6Address == -1 || value.LastIndexOf(':') > endOfIPv6Address;
}
}
}
public bool Pipelined
{
get
{
return _pipelined;
}
set
{
_pipelined = value;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the value of the Referer header.
/// </para>
/// </devdoc>
public string Referer
{
get
{
return _webHeaderCollection[HttpKnownHeaderNames.Referer];
}
set
{
SetSpecialHeaders(HttpKnownHeaderNames.Referer, value);
}
}
/// <devdoc>
/// <para>Sets the media type header</para>
/// </devdoc>
public string MediaType
{
get;
set;
}
/// <devdoc>
/// <para>
/// Gets or sets the value of the Transfer-Encoding header. Setting null clears it out.
/// </para>
/// </devdoc>
public string TransferEncoding
{
get
{
return _webHeaderCollection[HttpKnownHeaderNames.TransferEncoding];
}
set
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
bool fChunked;
//
// on blank string, remove current header
//
if (string.IsNullOrWhiteSpace(value))
{
//
// if the value is blank, then remove the header
//
_webHeaderCollection.Remove(HttpKnownHeaderNames.TransferEncoding);
return;
}
//
// if not check if the user is trying to set chunked:
//
string newValue = value.ToLower();
fChunked = (newValue.IndexOf(ChunkedHeader) != -1);
//
// prevent them from adding chunked, or from adding an Encoding without
// turning on chunked, the reason is due to the HTTP Spec which prevents
// additional encoding types from being used without chunked
//
if (fChunked)
{
throw new ArgumentException(SR.net_nochunked, nameof(value));
}
else if (!SendChunked)
{
throw new InvalidOperationException(SR.net_needchunked);
}
else
{
string checkedValue = HttpValidationHelpers.CheckBadHeaderValueChars(value);
_webHeaderCollection[HttpKnownHeaderNames.TransferEncoding] = checkedValue;
}
#if DEBUG
}
#endif
}
}
public bool KeepAlive { get; set; } = true;
public bool UnsafeAuthenticatedConnectionSharing
{
get
{
return (_booleans & Booleans.UnsafeAuthenticatedConnectionSharing) != 0;
}
set
{
if (value)
{
_booleans |= Booleans.UnsafeAuthenticatedConnectionSharing;
}
else
{
_booleans &= ~Booleans.UnsafeAuthenticatedConnectionSharing;
}
}
}
public DecompressionMethods AutomaticDecompression
{
get
{
return _automaticDecompression;
}
set
{
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_writestarted);
}
_automaticDecompression = value;
}
}
public virtual bool AllowWriteStreamBuffering
{
get
{
return (_booleans & Booleans.AllowWriteStreamBuffering) != 0;
}
set
{
if (value)
{
_booleans |= Booleans.AllowWriteStreamBuffering;
}
else
{
_booleans &= ~Booleans.AllowWriteStreamBuffering;
}
}
}
/// <devdoc>
/// <para>
/// Enables or disables automatically following redirection responses.
/// </para>
/// </devdoc>
public virtual bool AllowAutoRedirect
{
get
{
return (_booleans & Booleans.AllowAutoRedirect) != 0;
}
set
{
if (value)
{
_booleans |= Booleans.AllowAutoRedirect;
}
else
{
_booleans &= ~Booleans.AllowAutoRedirect;
}
}
}
public override string ConnectionGroupName { get; set; }
public override bool PreAuthenticate
{
get
{
return _preAuthenticate;
}
set
{
_preAuthenticate = value;
}
}
public string Connection
{
get
{
return _webHeaderCollection[HttpKnownHeaderNames.Connection];
}
set
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
bool fKeepAlive;
bool fClose;
//
// on blank string, remove current header
//
if (string.IsNullOrWhiteSpace(value))
{
_webHeaderCollection.Remove(HttpKnownHeaderNames.Connection);
return;
}
string newValue = value.ToLower();
fKeepAlive = (newValue.IndexOf("keep-alive") != -1);
fClose = (newValue.IndexOf("close") != -1);
//
// Prevent keep-alive and close from being added
//
if (fKeepAlive ||
fClose)
{
throw new ArgumentException(SR.net_connarg, nameof(value));
}
else
{
string checkedValue = HttpValidationHelpers.CheckBadHeaderValueChars(value);
_webHeaderCollection[HttpKnownHeaderNames.Connection] = checkedValue;
}
#if DEBUG
}
#endif
}
}
/*
Accessor: Expect
The property that controls the Expect header
Input:
string Expect, null clears the Expect except for 100-continue value
Returns: The value of the Expect on get.
*/
public string Expect
{
get
{
return _webHeaderCollection[HttpKnownHeaderNames.Expect];
}
set
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
// only remove everything other than 100-cont
bool fContinue100;
//
// on blank string, remove current header
//
if (string.IsNullOrWhiteSpace(value))
{
_webHeaderCollection.Remove(HttpKnownHeaderNames.Expect);
return;
}
//
// Prevent 100-continues from being added
//
string newValue = value.ToLower();
fContinue100 = (newValue.IndexOf(ContinueHeader) != -1);
if (fContinue100)
{
throw new ArgumentException(SR.net_no100, nameof(value));
}
else
{
string checkedValue = HttpValidationHelpers.CheckBadHeaderValueChars(value);
_webHeaderCollection[HttpKnownHeaderNames.Expect] = checkedValue;
}
#if DEBUG
}
#endif
}
}
/// <devdoc>
/// <para>
/// Gets or sets the default for the MaximumResponseHeadersLength property.
/// </para>
/// <remarks>
/// This value can be set in the config file, the default can be overridden using the MaximumResponseHeadersLength property.
/// </remarks>
/// </devdoc>
public static int DefaultMaximumResponseHeadersLength
{
get
{
return _defaultMaxResponseHeadersLength;
}
set
{
_defaultMaxResponseHeadersLength = value;
}
}
// NOP
public static int DefaultMaximumErrorResponseLength
{
get; set;
}
public static new RequestCachePolicy DefaultCachePolicy { get; set; } = new RequestCachePolicy(RequestCacheLevel.BypassCache);
public DateTime IfModifiedSince
{
get
{
return GetDateHeaderHelper(HttpKnownHeaderNames.IfModifiedSince);
}
set
{
SetDateHeaderHelper(HttpKnownHeaderNames.IfModifiedSince, value);
}
}
/// <devdoc>
/// <para>
/// Gets or sets the value of the Date header.
/// </para>
/// </devdoc>
public DateTime Date
{
get
{
return GetDateHeaderHelper(HttpKnownHeaderNames.Date);
}
set
{
SetDateHeaderHelper(HttpKnownHeaderNames.Date, value);
}
}
public bool SendChunked
{
get
{
return (_booleans & Booleans.SendChunked) != 0;
}
set
{
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_writestarted);
}
if (value)
{
_booleans |= Booleans.SendChunked;
}
else
{
_booleans &= ~Booleans.SendChunked;
}
}
}
public HttpContinueDelegate ContinueDelegate
{
// Nop since the underlying API do not expose 100 continue.
get
{
return _continueDelegate;
}
set
{
_continueDelegate = value;
}
}
public ServicePoint ServicePoint
{
get
{
if (_servicePoint == null)
{
_servicePoint = ServicePointManager.FindServicePoint(Address, Proxy);
}
return _servicePoint;
}
}
public RemoteCertificateValidationCallback ServerCertificateValidationCallback { get; set; }
//
// ClientCertificates - sets our certs for our reqest,
// uses a hash of the collection to create a private connection
// group, to prevent us from using the same Connection as
// non-Client Authenticated requests.
//
public X509CertificateCollection ClientCertificates
{
get
{
if (_clientCertificates == null)
_clientCertificates = new X509CertificateCollection();
return _clientCertificates;
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
_clientCertificates = value;
}
}
// HTTP Version
/// <devdoc>
/// <para>
/// Gets and sets
/// the HTTP protocol version used in this request.
/// </para>
/// </devdoc>
public Version ProtocolVersion
{
get
{
return IsVersionHttp10 ? HttpVersion.Version10 : HttpVersion.Version11;
}
set
{
if (value.Equals(HttpVersion.Version11))
{
IsVersionHttp10 = false;
}
else if (value.Equals(HttpVersion.Version10))
{
IsVersionHttp10 = true;
}
else
{
throw new ArgumentException(SR.net_wrongversion, nameof(value));
}
}
}
public int ReadWriteTimeout
{
get
{
return _readWriteTimeout;
}
set
{
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_reqsubmitted);
}
if (value <= 0 && value != System.Threading.Timeout.Infinite)
{
throw new ArgumentOutOfRangeException(nameof(value), SR.net_io_timeout_use_gt_zero);
}
_readWriteTimeout = value;
}
}
public virtual CookieContainer CookieContainer
{
get
{
return _cookieContainer;
}
set
{
_cookieContainer = value;
}
}
public override ICredentials Credentials
{
get
{
return _credentials;
}
set
{
_credentials = value;
}
}
public virtual bool HaveResponse
{
get
{
return (_sendRequestTask != null) && (_sendRequestTask.IsCompletedSuccessfully);
}
}
public override WebHeaderCollection Headers
{
get
{
return _webHeaderCollection;
}
set
{
// We can't change headers after they've already been sent.
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_reqsubmitted);
}
WebHeaderCollection webHeaders = value;
WebHeaderCollection newWebHeaders = new WebHeaderCollection();
// Copy And Validate -
// Handle the case where their object tries to change
// name, value pairs after they call set, so therefore,
// we need to clone their headers.
foreach (string headerName in webHeaders.AllKeys)
{
newWebHeaders[headerName] = webHeaders[headerName];
}
_webHeaderCollection = newWebHeaders;
}
}
public override string Method
{
get
{
return _originVerb;
}
set
{
if (string.IsNullOrEmpty(value))
{
throw new ArgumentException(SR.net_badmethod, nameof(value));
}
if (HttpValidationHelpers.IsInvalidMethodOrHeaderString(value))
{
throw new ArgumentException(SR.net_badmethod, nameof(value));
}
_originVerb = value;
}
}
public override Uri RequestUri
{
get
{
return _requestUri;
}
}
public virtual bool SupportsCookieContainer
{
get
{
return true;
}
}
public override bool UseDefaultCredentials
{
get
{
return (_credentials == CredentialCache.DefaultCredentials);
}
set
{
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_writestarted);
}
// Match Desktop behavior. Changing this property will also
// change the .Credentials property as well.
_credentials = value ? CredentialCache.DefaultCredentials : null;
}
}
public override IWebProxy Proxy
{
get
{
return _proxy;
}
set
{
// We can't change the proxy while the request is already fired.
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_reqsubmitted);
}
_proxy = value;
}
}
public override void Abort()
{
if (Interlocked.Exchange(ref _abortCalled, 1) != 0)
{
return;
}
// .NET Desktop behavior requires us to invoke outstanding callbacks
// before returning if used in either the BeginGetRequestStream or
// BeginGetResponse methods.
//
// If we can transition the task to the canceled state, then we invoke
// the callback. If we can't transition the task, it is because it is
// already in the terminal state and the callback has already been invoked
// via the async task continuation.
if (_responseOperation != null)
{
if (_responseOperation.TrySetCanceled() && _responseCallback != null)
{
_responseCallback(_responseOperation.Task);
}
// Cancel the underlying send operation.
Debug.Assert(_sendRequestCts != null);
_sendRequestCts.Cancel();
}
else if (_requestStreamOperation != null)
{
if (_requestStreamOperation.TrySetCanceled() && _requestStreamCallback != null)
{
_requestStreamCallback(_requestStreamOperation.Task);
}
}
}
// HTTP version of the request
private bool IsVersionHttp10
{
get
{
return (_booleans & Booleans.IsVersionHttp10) != 0;
}
set
{
if (value)
{
_booleans |= Booleans.IsVersionHttp10;
}
else
{
_booleans &= ~Booleans.IsVersionHttp10;
}
}
}
public override WebResponse GetResponse()
{
try
{
_sendRequestCts = new CancellationTokenSource();
return SendRequest().GetAwaiter().GetResult();
}
catch (Exception ex)
{
throw WebException.CreateCompatibleException(ex);
}
}
public override Stream GetRequestStream()
{
return InternalGetRequestStream().Result;
}
private Task<Stream> InternalGetRequestStream()
{
CheckAbort();
// Match Desktop behavior: prevent someone from getting a request stream
// if the protocol verb/method doesn't support it. Note that this is not
// entirely compliant RFC2616 for the aforementioned compatibility reasons.
if (string.Equals(HttpMethod.Get.Method, _originVerb, StringComparison.OrdinalIgnoreCase) ||
string.Equals(HttpMethod.Head.Method, _originVerb, StringComparison.OrdinalIgnoreCase) ||
string.Equals("CONNECT", _originVerb, StringComparison.OrdinalIgnoreCase))
{
throw new ProtocolViolationException(SR.net_nouploadonget);
}
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_reqsubmitted);
}
_requestStream = new RequestStream();
return Task.FromResult((Stream)_requestStream);
}
public Stream EndGetRequestStream(IAsyncResult asyncResult, out TransportContext context)
{
context = null;
return EndGetRequestStream(asyncResult);
}
public Stream GetRequestStream(out TransportContext context)
{
context = null;
return GetRequestStream();
}
public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state)
{
CheckAbort();
if (Interlocked.Exchange(ref _beginGetRequestStreamCalled, 1) != 0)
{
throw new InvalidOperationException(SR.net_repcall);
}
_requestStreamCallback = callback;
_requestStreamOperation = InternalGetRequestStream().ToApm(callback, state);
return _requestStreamOperation.Task;
}
public override Stream EndGetRequestStream(IAsyncResult asyncResult)
{
CheckAbort();
if (asyncResult == null || !(asyncResult is Task<Stream>))
{
throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
}
if (Interlocked.Exchange(ref _endGetRequestStreamCalled, 1) != 0)
{
throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndGetRequestStream"));
}
Stream stream;
try
{
stream = ((Task<Stream>)asyncResult).GetAwaiter().GetResult();
}
catch (Exception ex)
{
throw WebException.CreateCompatibleException(ex);
}
return stream;
}
private async Task<WebResponse> SendRequest()
{
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_reqsubmitted);
}
var handler = new HttpClientHandler();
var request = new HttpRequestMessage(new HttpMethod(_originVerb), _requestUri);
using (var client = new HttpClient(handler))
{
if (_requestStream != null)
{
ArraySegment<byte> bytes = _requestStream.GetBuffer();
request.Content = new ByteArrayContent(bytes.Array, bytes.Offset, bytes.Count);
}
handler.AutomaticDecompression = AutomaticDecompression;
handler.Credentials = _credentials;
handler.AllowAutoRedirect = AllowAutoRedirect;
handler.MaxAutomaticRedirections = MaximumAutomaticRedirections;
handler.MaxResponseHeadersLength = MaximumResponseHeadersLength;
handler.PreAuthenticate = PreAuthenticate;
client.Timeout = Timeout == Threading.Timeout.Infinite ?
Threading.Timeout.InfiniteTimeSpan :
TimeSpan.FromMilliseconds(Timeout);
if (_cookieContainer != null)
{
handler.CookieContainer = _cookieContainer;
Debug.Assert(handler.UseCookies); // Default of handler.UseCookies is true.
}
else
{
handler.UseCookies = false;
}
Debug.Assert(handler.UseProxy); // Default of handler.UseProxy is true.
Debug.Assert(handler.Proxy == null); // Default of handler.Proxy is null.
// HttpClientHandler default is to use a proxy which is the system proxy.
// This is indicated by the properties 'UseProxy == true' and 'Proxy == null'.
//
// However, HttpWebRequest doesn't have a separate 'UseProxy' property. Instead,
// the default of the 'Proxy' property is a non-null IWebProxy object which is the
// system default proxy object. If the 'Proxy' property were actually null, then
// that means don't use any proxy.
//
// So, we need to map the desired HttpWebRequest proxy settings to equivalent
// HttpClientHandler settings.
if (_proxy == null)
{
handler.UseProxy = false;
}
else if (!object.ReferenceEquals(_proxy, WebRequest.GetSystemWebProxy()))
{
handler.Proxy = _proxy;
}
handler.ClientCertificates.AddRange(ClientCertificates);
// Set relevant properties from ServicePointManager
handler.SslProtocols = (SslProtocols)ServicePointManager.SecurityProtocol;
handler.CheckCertificateRevocationList = ServicePointManager.CheckCertificateRevocationList;
RemoteCertificateValidationCallback rcvc = ServerCertificateValidationCallback != null ?
ServerCertificateValidationCallback :
ServicePointManager.ServerCertificateValidationCallback;
if (rcvc != null)
{
RemoteCertificateValidationCallback localRcvc = rcvc;
handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => localRcvc(this, cert, chain, errors);
}
if (_hostUri != null)
{
request.Headers.Host = Host;
}
// Copy the HttpWebRequest request headers from the WebHeaderCollection into HttpRequestMessage.Headers and
// HttpRequestMessage.Content.Headers.
foreach (string headerName in _webHeaderCollection)
{
// The System.Net.Http APIs require HttpRequestMessage headers to be properly divided between the request headers
// collection and the request content headers collection for all well-known header names. And custom headers
// are only allowed in the request headers collection and not in the request content headers collection.
if (IsWellKnownContentHeader(headerName))
{
if (request.Content == null)
{
// Create empty content so that we can send the entity-body header.
request.Content = new ByteArrayContent(Array.Empty<byte>());
}
request.Content.Headers.TryAddWithoutValidation(headerName, _webHeaderCollection[headerName]);
}
else
{
request.Headers.TryAddWithoutValidation(headerName, _webHeaderCollection[headerName]);
}
}
request.Headers.TransferEncodingChunked = SendChunked;
if (KeepAlive)
{
request.Headers.Connection.Add(HttpKnownHeaderNames.KeepAlive);
}
else
{
request.Headers.ConnectionClose = true;
}
request.Version = ProtocolVersion;
_sendRequestTask = client.SendAsync(
request,
_allowReadStreamBuffering ? HttpCompletionOption.ResponseContentRead : HttpCompletionOption.ResponseHeadersRead,
_sendRequestCts.Token);
HttpResponseMessage responseMessage = await _sendRequestTask.ConfigureAwait(false);
HttpWebResponse response = new HttpWebResponse(responseMessage, _requestUri, _cookieContainer);
if (!responseMessage.IsSuccessStatusCode)
{
throw new WebException(
SR.Format(SR.net_servererror, (int)response.StatusCode, response.StatusDescription),
null,
WebExceptionStatus.ProtocolError,
response);
}
return response;
}
}
public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state)
{
CheckAbort();
if (Interlocked.Exchange(ref _beginGetResponseCalled, 1) != 0)
{
throw new InvalidOperationException(SR.net_repcall);
}
_sendRequestCts = new CancellationTokenSource();
_responseCallback = callback;
_responseOperation = SendRequest().ToApm(callback, state);
return _responseOperation.Task;
}
public override WebResponse EndGetResponse(IAsyncResult asyncResult)
{
CheckAbort();
if (asyncResult == null || !(asyncResult is Task<WebResponse>))
{
throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
}
if (Interlocked.Exchange(ref _endGetResponseCalled, 1) != 0)
{
throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndGetResponse"));
}
WebResponse response;
try
{
response = ((Task<WebResponse>)asyncResult).GetAwaiter().GetResult();
}
catch (Exception ex)
{
throw WebException.CreateCompatibleException(ex);
}
return response;
}
/// <devdoc>
/// <para>
/// Adds a range header to the request for a specified range.
/// </para>
/// </devdoc>
public void AddRange(int from, int to)
{
AddRange("bytes", (long)from, (long)to);
}
/// <devdoc>
/// <para>
/// Adds a range header to the request for a specified range.
/// </para>
/// </devdoc>
public void AddRange(long from, long to)
{
AddRange("bytes", from, to);
}
/// <devdoc>
/// <para>
/// Adds a range header to a request for a specific
/// range from the beginning or end
/// of the requested data.
/// To add the range from the end pass negative value
/// To add the range from the some offset to the end pass positive value
/// </para>
/// </devdoc>
public void AddRange(int range)
{
AddRange("bytes", (long)range);
}
/// <devdoc>
/// <para>
/// Adds a range header to a request for a specific
/// range from the beginning or end
/// of the requested data.
/// To add the range from the end pass negative value
/// To add the range from the some offset to the end pass positive value
/// </para>
/// </devdoc>
public void AddRange(long range)
{
AddRange("bytes", range);
}
public void AddRange(string rangeSpecifier, int from, int to)
{
AddRange(rangeSpecifier, (long)from, (long)to);
}
public void AddRange(string rangeSpecifier, long from, long to)
{
//
// Do some range checking before assembling the header
//
if (rangeSpecifier == null)
{
throw new ArgumentNullException(nameof(rangeSpecifier));
}
if ((from < 0) || (to < 0))
{
throw new ArgumentOutOfRangeException(from < 0 ? nameof(from) : nameof(to), SR.net_rangetoosmall);
}
if (from > to)
{
throw new ArgumentOutOfRangeException(nameof(from), SR.net_fromto);
}
if (!HttpValidationHelpers.IsValidToken(rangeSpecifier))
{
throw new ArgumentException(SR.net_nottoken, nameof(rangeSpecifier));
}
if (!AddRange(rangeSpecifier, from.ToString(NumberFormatInfo.InvariantInfo), to.ToString(NumberFormatInfo.InvariantInfo)))
{
throw new InvalidOperationException(SR.net_rangetype);
}
}
public void AddRange(string rangeSpecifier, int range)
{
AddRange(rangeSpecifier, (long)range);
}
public void AddRange(string rangeSpecifier, long range)
{
if (rangeSpecifier == null)
{
throw new ArgumentNullException(nameof(rangeSpecifier));
}
if (!HttpValidationHelpers.IsValidToken(rangeSpecifier))
{
throw new ArgumentException(SR.net_nottoken, nameof(rangeSpecifier));
}
if (!AddRange(rangeSpecifier, range.ToString(NumberFormatInfo.InvariantInfo), (range >= 0) ? "" : null))
{
throw new InvalidOperationException(SR.net_rangetype);
}
}
private bool AddRange(string rangeSpecifier, string from, string to)
{
string curRange = _webHeaderCollection[HttpKnownHeaderNames.Range];
if ((curRange == null) || (curRange.Length == 0))
{
curRange = rangeSpecifier + "=";
}
else
{
if (!string.Equals(curRange.Substring(0, curRange.IndexOf('=')), rangeSpecifier, StringComparison.OrdinalIgnoreCase))
{
return false;
}
curRange = string.Empty;
}
curRange += from.ToString();
if (to != null)
{
curRange += "-" + to;
}
_webHeaderCollection[HttpKnownHeaderNames.Range] = curRange;
return true;
}
private bool RequestSubmitted
{
get
{
return _sendRequestTask != null;
}
}
private void CheckAbort()
{
if (Volatile.Read(ref _abortCalled) == 1)
{
throw new WebException(SR.net_reqaborted, WebExceptionStatus.RequestCanceled);
}
}
private static readonly string[] s_wellKnownContentHeaders = {
HttpKnownHeaderNames.ContentDisposition,
HttpKnownHeaderNames.ContentEncoding,
HttpKnownHeaderNames.ContentLanguage,
HttpKnownHeaderNames.ContentLength,
HttpKnownHeaderNames.ContentLocation,
HttpKnownHeaderNames.ContentMD5,
HttpKnownHeaderNames.ContentRange,
HttpKnownHeaderNames.ContentType,
HttpKnownHeaderNames.Expires,
HttpKnownHeaderNames.LastModified
};
private bool IsWellKnownContentHeader(string header)
{
foreach (string contentHeaderName in s_wellKnownContentHeaders)
{
if (string.Equals(header, contentHeaderName, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
private DateTime GetDateHeaderHelper(string headerName)
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
string headerValue = _webHeaderCollection[headerName];
if (headerValue == null)
{
return DateTime.MinValue; // MinValue means header is not present
}
if (HttpDateParser.TryStringToDate(headerValue, out DateTimeOffset dateTimeOffset))
{
return dateTimeOffset.LocalDateTime;
}
else
{
throw new ProtocolViolationException(SR.net_baddate);
}
#if DEBUG
}
#endif
}
private void SetDateHeaderHelper(string headerName, DateTime dateTime)
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
if (dateTime == DateTime.MinValue)
SetSpecialHeaders(headerName, null); // remove header
else
SetSpecialHeaders(headerName, HttpDateParser.DateToString(dateTime.ToUniversalTime()));
#if DEBUG
}
#endif
}
private bool TryGetHostUri(string hostName, out Uri hostUri)
{
string s = Address.Scheme + "://" + hostName + Address.PathAndQuery;
return Uri.TryCreate(s, UriKind.Absolute, out hostUri);
}
}
}
| |
// Track BuildR
// Available on the Unity3D Asset Store
// Copyright (c) 2013 Jasper Stocker http://support.jasperstocker.com
// For support contact email@jasperstocker.com
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// A class dealing with dynamic mesh generataion. Attempts to keep memory use low.
/// Contains nextNormIndex variety of functions to help in the generation of meshes.
/// Uses generic lists to contain the mesh data allowing for the mesh to be of dynamic numberOfPoints
/// Creates nextNormIndex mesh that can support multiple materials
/// </summary>
public class DynamicMeshGenericMultiMaterial
{
public string name = "";
public Mesh mesh;
public List<Vector3> vertices;
public List<Vector2> uv;
public List<int> triangles;
private List<Vector2> _minWorldUVSize = new List<Vector2>();
private List<Vector2> _maxWorldUVSize = new List<Vector2>();
private int _subMeshes = 1;
private Dictionary<int, List<int>> subTriangles;
private Vector3[] tan1;
private Vector3[] tan2;
private Vector4[] tangents;
private bool _built;
private bool _hasTangents;
private bool _optimised;
public DynamicMeshGenericMultiMaterial()
{
mesh = new Mesh();
vertices = new List<Vector3>();
uv = new List<Vector2>();
triangles = new List<int>();
subTriangles = new Dictionary<int, List<int>>();
}
public void Build()
{
Build(false);
}
public void Build(bool calcTangents)
{
if (vertexCount > 65000)//Unity has an inbuilt limit of 65000 verticies. Use DynamicMeshGenericMultiMaterialMesh to handle more than 65000
{
Debug.LogWarning(name+ " is exceeding 65000 vertices - stop build");
_built = false;
return;
}
if(subMeshCount == 0)//USer needs to specify the amount of submeshes this mesh contains
{
Debug.LogWarning(name+ " has no submeshes - you need to define them pre build");
_built = false;
return;
}
mesh.Clear();
mesh.name = name;
mesh.vertices = vertices.ToArray();
mesh.uv = uv.ToArray();
mesh.uv2 = new Vector2[0];
mesh.subMeshCount = _subMeshes;
List<int> setTris = new List<int>();
foreach (KeyValuePair<int, List<int>> triData in subTriangles)
{
mesh.SetTriangles(triData.Value.ToArray(), triData.Key);
setTris.AddRange(triData.Value);
}
mesh.RecalculateBounds();
mesh.RecalculateNormals();
if (calcTangents)
{
SolveTangents();
}
else
{
_hasTangents = false;
Vector4[] emptyTangents = new Vector4[size];
mesh.tangents = emptyTangents;
}
optimised = false;
_built = true;
lightmapUvsCalculated = false;
}
/// <summary>
/// Clears the mesh data, ready for nextNormIndex new mesh build
/// </summary>
public void Clear()
{
mesh.Clear();
vertices.Clear();
uv.Clear();
triangles.Clear();
subTriangles.Clear();
_built = false;
_subMeshes = 0;
}
public int vertexCount
{
get
{
return vertices.Count;
}
}
public bool built
{
get { return _built; }
}
public int size
{
get { return vertices.Count; }
}
public int triangleCount
{
get { return triangles.Count; }
}
public int subMeshCount
{
get
{
return _subMeshes;
}
set
{
_subMeshes = value;
//reset the largest/smallest UZ numberOfPoints monitors
if(minWorldUvSize.Count > value)
minWorldUvSize.Clear();
if(maxWorldUvSize.Count > value)
maxWorldUvSize.Clear();
while (minWorldUvSize.Count <= value)
{
minWorldUvSize.Add(Vector2.zero);
maxWorldUvSize.Add(Vector2.one);
}
}
}
public bool hasTangents { get { return _hasTangents; } }
public bool lightmapUvsCalculated {get; set;}
public bool optimised {get {return _optimised;} set {_optimised = value;}}
public List<Vector2> minWorldUvSize {get {return _minWorldUVSize;}}
public List<Vector2> maxWorldUvSize {get {return _maxWorldUVSize;}}
/// <summary>
/// Generate the Mesh tangents.
/// These calculations are heavy and not idea for complex meshes at runtime
/// </summary>
public void SolveTangents()
{
tan1 = new Vector3[size];
tan2 = new Vector3[size];
tangents = new Vector4[size];
int triangleCount = triangles.Count / 3;
for (int a = 0; a < triangleCount; a += 3)
{
int i1 = triangles[a + 0];
int i2 = triangles[a + 1];
int i3 = triangles[a + 2];
Vector3 v1 = vertices[i1];
Vector3 v2 = vertices[i2];
Vector3 v3 = vertices[i3];
Vector2 w1 = uv[i1];
Vector2 w2 = uv[i2];
Vector2 w3 = uv[i3];
float x1 = v2.x - v1.x;
float x2 = v3.x - v1.x;
float y1 = v2.y - v1.y;
float y2 = v3.y - v1.y;
float z1 = v2.z - v1.z;
float z2 = v3.z - v1.z;
float s1 = w2.x - w1.x;
float s2 = w3.x - w1.x;
float t1 = w2.y - w1.y;
float t2 = w3.y - w1.y;
float r = 1.0f / (s1 * t2 - s2 * t1);
Vector3 sdir = new Vector3((t2 * x1 - t1 * x2) * r, (t2 * y1 - t1 * y2) * r, (t2 * z1 - t1 * z2) * r);
Vector3 tdir = new Vector3((s1 * x2 - s2 * x1) * r, (s1 * y2 - s2 * y1) * r, (s1 * z2 - s2 * z1) * r);
tan1[i1] += sdir;
tan1[i2] += sdir;
tan1[i3] += sdir;
tan2[i1] += tdir;
tan2[i2] += tdir;
tan2[i3] += tdir;
}
for (int a = 0; a < size; ++a)
{
Vector3 n = mesh.normals[a];
Vector3 t = tan1[a];
Vector3 tmp = (t - n * Vector3.Dot(n, t)).normalized;
tangents[a] = new Vector4(tmp.x, tmp.y, tmp.z);
tangents[a].w = (Vector3.Dot(Vector3.Cross(n, t), tan2[a]) < 0.0f) ? -1.0f : 1.0f;
}
mesh.tangents = tangents;
_hasTangents = true;
}
/// <summary>
/// Add new mesh data - all arrays are ordered together
/// </summary>
/// <param customName="verts">And array of verticies</param>
/// <param customName="uvs">And array of uvs</param>
/// <param customName="tris">And array of triangles</param>
/// <param customName="subMesh">The submesh to add the data into</param>
public void AddData(Vector3[] verts, Vector2[] uvs, int[] tris, int subMesh)
{
int indiceBase = vertices.Count;
vertices.AddRange(verts);
uv.AddRange(uvs);
if (!subTriangles.ContainsKey(subMesh))
subTriangles.Add(subMesh, new List<int>());
int newTriCount = tris.Length;
for (int t = 0; t < newTriCount; t++)
{
int newTri = (indiceBase + tris[t]);
triangles.Add(newTri);
subTriangles[subMesh].Add(newTri);
}
//calculate the bounds of the UV on the mesh
Vector2 minWorldUVSize = minWorldUvSize[subMesh];
Vector2 maxWorldUVSize = maxWorldUvSize[subMesh];
int vertCount = verts.Length;
for(int i = 0; i < vertCount-1; i++)
{
Vector2 thisuv = uvs[i];
if (thisuv.x < minWorldUVSize.x)
minWorldUVSize.x = thisuv.x;
if (thisuv.y < minWorldUVSize.y)
minWorldUVSize.y = thisuv.y;
if (thisuv.x > maxWorldUVSize.x)
maxWorldUVSize.x = thisuv.x;
if (thisuv.y > maxWorldUVSize.y)
maxWorldUVSize.y = thisuv.y;
}
minWorldUvSize[subMesh] = minWorldUVSize;
maxWorldUvSize[subMesh] = maxWorldUVSize;
}
/// <summary>
/// Add the new triangle to the mesh data
/// </summary>
/// <param customName="p0"></param>
/// <param customName="p1"></param>
/// <param customName="p2"></param>
/// <param customName="subMesh"></param>
public void AddTri(Vector3 p0, Vector3 p1, Vector3 p2, int subMesh)
{
int indiceBase = vertices.Count;
vertices.Add(p0);
vertices.Add(p1);
vertices.Add(p2);
uv.Add(new Vector2(0, 0));
uv.Add(new Vector2(1, 0));
uv.Add(new Vector2(0, 1));
if (!subTriangles.ContainsKey(subMesh))
subTriangles.Add(subMesh, new List<int>());
triangles.Add(indiceBase);
triangles.Add(indiceBase + 2);
triangles.Add(indiceBase + 1);
subTriangles[subMesh].Add(indiceBase);
subTriangles[subMesh].Add(indiceBase + 2);
subTriangles[subMesh].Add(indiceBase + 1);
}
/// <summary>
/// Adds the plane to the generic dynamic mesh without specifying UV coords.
/// </summary>
/// <param customName='p0,p1,p2,p3'>
/// 4 Verticies that define the plane
/// <param customName='subMesh'>
/// The sub mesh to attch this plan to - in order of Texture library indicies
/// </param>
public void AddPlane(Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3, int subMesh)
{
AddPlane(p0, p1, p2, p3, Vector2.zero, Vector2.one, subMesh);
}
/// <summary>
/// Adds the plane to the generic dynamic mesh by specifying min and max UV coords.
/// </summary>
/// <param customName='p0,p1,p2,p3'>
/// 4 Verticies that define the plane
/// </param>
/// <param customName='minUV'>
/// the minimum vertex UV coord.
/// </param>
/// </param>
/// <param customName='maxUV'>
/// the maximum vertex UV coord.
/// </param>
/// <param customName='subMesh'>
/// The sub mesh to attch this plan to - in order of Texture library indicies
/// </param>
public void AddPlane(Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3, Vector2 minUV, Vector2 maxUV, int subMesh)
{
Vector2 uv0 = new Vector2(minUV.x, minUV.y);
Vector2 uv1 = new Vector2(maxUV.x, minUV.y);
Vector2 uv2 = new Vector2(minUV.x, maxUV.y);
Vector2 uv3 = new Vector2(maxUV.x, maxUV.y);
AddPlane(p0, p1, p2, p3, uv0, uv1, uv2, uv3, subMesh);
}
/// <summary>
/// Adds the plane to the generic dynamic mesh.
/// </summary>
/// <param customName='p0,p1,p2,p3'>
/// 4 Verticies that define the plane
/// </param>
/// <param customName='uv0,uv1,uv2,uv3'>
/// the vertex UV coords.
/// </param>
/// <param customName='subMesh'>
/// The sub mesh to attch this plan to - in order of Texture library indicies
/// </param>
public void AddPlane(Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3, Vector2 uv0, Vector2 uv1, Vector2 uv2, Vector2 uv3, int subMesh)
{
int indiceBase = vertices.Count;
vertices.Add(p0);
vertices.Add(p1);
vertices.Add(p2);
vertices.Add(p3);
uv.Add(uv0);
uv.Add(uv1);
uv.Add(uv2);
uv.Add(uv3);
if (!subTriangles.ContainsKey(subMesh))
subTriangles.Add(subMesh, new List<int>());
subTriangles[subMesh].Add(indiceBase);
subTriangles[subMesh].Add(indiceBase + 2);
subTriangles[subMesh].Add(indiceBase + 1);
subTriangles[subMesh].Add(indiceBase + 1);
subTriangles[subMesh].Add(indiceBase + 2);
subTriangles[subMesh].Add(indiceBase + 3);
triangles.Add(indiceBase);
triangles.Add(indiceBase + 2);
triangles.Add(indiceBase + 1);
triangles.Add(indiceBase + 1);
triangles.Add(indiceBase + 2);
triangles.Add(indiceBase + 3);
Vector2 minWorldUVSize = minWorldUvSize[subMesh];
Vector2 maxWorldUVSize = maxWorldUvSize[subMesh];
int vertCount = 4;
Vector2[] uvs = new []{uv0,uv1,uv2,uv3};
for (int i = 0; i < vertCount - 1; i++)
{
Vector2 thisuv = uvs[i];
if (thisuv.x < minWorldUVSize.x)
minWorldUVSize.x = thisuv.x;
if (thisuv.y < minWorldUVSize.y)
minWorldUVSize.y = thisuv.y;
if (thisuv.x > maxWorldUVSize.x)
maxWorldUVSize.x = thisuv.x;
if (thisuv.y > maxWorldUVSize.y)
maxWorldUVSize.y = thisuv.y;
}
minWorldUvSize[subMesh] = minWorldUVSize;
maxWorldUvSize[subMesh] = maxWorldUVSize;
}
/// <summary>
/// Checks the Max UV values used in this model for each trackTexture.
/// </summary>
/// <param customName='data'>
/// BuildR Data.
/// </param>
public void CheckMaxTextureUVs(TrackBuildRTexture[] textures)
{
Vector2[] subMeshUVOffsets = new Vector2[subMeshCount];
int[] subMeshIDs = new List<int>(subTriangles.Keys).ToArray();
int numberOfSubmeshIDs = subMeshIDs.Length;
for (int sm = 0; sm < numberOfSubmeshIDs; sm++)
{
int subMeshID = subMeshIDs[sm];
if (subTriangles.ContainsKey(subMeshID))
{
int[] submeshIndices = subTriangles[subMeshID].ToArray();
subMeshUVOffsets[sm] = Vector2.zero;
foreach (int index in submeshIndices)
{
if (uv[index].x < subMeshUVOffsets[sm].x)
subMeshUVOffsets[sm].x = uv[index].x;
if (uv[index].y < subMeshUVOffsets[sm].y)
subMeshUVOffsets[sm].y = uv[index].y;
}
List<int> UVsOffset = new List<int>();
foreach (int uvindex in subTriangles[subMeshID])
{
if (!UVsOffset.Contains(uvindex))
{
uv[uvindex] += -subMeshUVOffsets[sm];//offset the UV to ensure it isn't negative
UVsOffset.Add(uvindex);
}
textures[subMeshID].CheckMaxUV(uv[uvindex]);
}
}
else
{
Debug.Log("Mesh does not contain key for trackTexture " + textures[subMeshID].customName);
}
}
}
/// <summary>
/// Atlas the entire mesh using newTextureCoords and textures.
/// </summary>
/// <param customName="newTextureCoords"></param>
/// <param customName="textures"></param>
public void Atlas(Rect[] newTextureCoords, TrackBuildRTexture[] textures)
{
List<int> keys = new List<int>(subTriangles.Keys);
Atlas(keys.ToArray(), newTextureCoords, textures);
}
/// <summary>
/// Atlas the specified modifySubmeshes using newTextureCoords and textures.
/// </summary>
/// <param customName='modifySubmeshes'>
/// Submeshes indicies to atlas.
/// </param>
/// <param customName='newTextureCoords'>
/// New trackTexture coords generated from Pack Textures.
/// </param>
/// <param customName='textures'>
/// BuildR Textures library reference.
/// </param>
public void Atlas(int[] modifySubmeshes, Rect[] newTextureCoords, TrackBuildRTexture[] textures)
{
if (modifySubmeshes.Length == 0)
{
Debug.Log("No submeshes to atlas!");
return;
}
List<int> atlasedSubmesh = new List<int>();
int numberOfSubmeshesToModify = modifySubmeshes.Length;
for (int s = 0; s < numberOfSubmeshesToModify; s++)
{
int submeshIndex = modifySubmeshes[s];
Rect textureRect = newTextureCoords[s];
if (!subTriangles.ContainsKey(submeshIndex))
continue;
int[] submeshIndices = subTriangles[submeshIndex].ToArray();
subTriangles.Remove(submeshIndex);
atlasedSubmesh.AddRange(submeshIndices);
TrackBuildRTexture bTexture = textures[submeshIndex];
List<int> ModifiedUVs = new List<int>();
foreach (int index in submeshIndices)
{
if (ModifiedUVs.Contains(index))
continue;//don't move the UV more than once
Vector2 uvCoords = uv[index];
float xUV = uvCoords.x / bTexture.maxUVTile.x;
float yUV = uvCoords.y / bTexture.maxUVTile.y;
if (xUV > 1)
{
bTexture.maxUVTile.x = uvCoords.x;
xUV = 1.0f;
}
if (yUV > 1)
{
bTexture.maxUVTile.y = uvCoords.y;
yUV = 1;
}
uvCoords.x = Mathf.Lerp(textureRect.xMin, textureRect.xMax, xUV);
uvCoords.y = Mathf.Lerp(textureRect.yMin, textureRect.yMax, yUV);
if (float.IsNaN(uvCoords.x))
{
uvCoords.x = 1;
}
if (float.IsNaN(uvCoords.y))
{
uvCoords.y = 1;
}
uv[index] = uvCoords;
ModifiedUVs.Add(index);//keep nextNormIndex record of moved UVs
}
}
subMeshCount = subMeshCount - modifySubmeshes.Length + 1;
subTriangles.Add(modifySubmeshes[0], atlasedSubmesh);
}
/// <summary>
/// Atlas the entire mesh, specifying specific submeshes that have been atlased
/// </summary>
/// <param customName="modifySubmeshes">Specified submeshes for the atlased coords</param>
/// <param customName="newTextureCoords">New trackTexture coords generated from Pack Textures.</param>
public void Atlas(int[] modifySubmeshes, Rect[] newTextureCoords)
{
if (modifySubmeshes.Length == 0)
{
Debug.Log("No submeshes to atlas!");
return;
}
List<int> atlasedSubmesh = new List<int>();
List<int> modifySubmeshList = new List<int>(modifySubmeshes);
for (int s = 0; s < subMeshCount; s++)
{
if (!subTriangles.ContainsKey(s))
continue;
int[] submeshIndices = subTriangles[s].ToArray();
subTriangles.Remove(s);
atlasedSubmesh.AddRange(submeshIndices);
if(modifySubmeshList.Contains(s))
{
Rect textureRect = newTextureCoords[s];
List<int> ModifiedUVs = new List<int>();
foreach (int index in submeshIndices)
{
if (ModifiedUVs.Contains(index))
continue;//don't move the UV more than once
Vector2 uvCoords = uv[index];
uvCoords.x = Mathf.Lerp(textureRect.xMin, textureRect.xMax, uvCoords.x);
uvCoords.y = Mathf.Lerp(textureRect.yMin, textureRect.yMax, uvCoords.y);
uv[index] = uvCoords;
ModifiedUVs.Add(index);//keep nextNormIndex record of moved UVs
}
}else
{
List<int> ModifiedUVs = new List<int>();
foreach (int index in submeshIndices)
{
if (ModifiedUVs.Contains(index))
continue;//don't move the UV more than once
uv[index] = Vector2.zero;
ModifiedUVs.Add(index);//keep nextNormIndex record of moved UVs
}
}
}
//subMeshCount = subMeshCount - modifySubmeshes.Length + 1;
subMeshCount = 1;
subTriangles.Add(modifySubmeshes[0], atlasedSubmesh);
}
/// <summary>
/// Collapse all the submeshes into nextNormIndex single submesh
/// </summary>
public void CollapseSubmeshes()
{
List<int> atlasedSubmesh = new List<int>();
int numberOfSubmeshesToModify = subMeshCount;
for (int s = 0; s < numberOfSubmeshesToModify; s++)
{
if (subTriangles.ContainsKey(s))
{
int[] submeshIndices = subTriangles[s].ToArray();
atlasedSubmesh.AddRange(submeshIndices);
}
}
subMeshCount = 1;
subTriangles.Clear();
subTriangles.Add(0, atlasedSubmesh);
}
public void RemoveRedundantVerticies()
{
List<Vector3> vertList = new List<Vector3>();
int vertIndex = 0;
int numberOfVerts = vertexCount;
for (int i = 0; i < numberOfVerts; i++)
{
Vector3 vert = vertices[i];
if (!vertList.Contains(vert))
{
//no redundancy - add
vertList.Add(vert);
}
else
{
//possible redundancy
int firstIndex = vertices.IndexOf(vert);
int secondIndex = vertIndex;
//check to see if these verticies are connected
if (uv[firstIndex] == uv[secondIndex])
{
//verticies are connected - merge them
int triIndex = 0;
while ((triIndex = triangles.IndexOf(secondIndex)) != -1)
triangles[triIndex] = firstIndex;
vertices.RemoveAt(secondIndex);
uv.RemoveAt(secondIndex);
numberOfVerts--;
i--;
}
else
{
vertList.Add(vert);
}
}
vertIndex++;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ServiceStack.MicrosoftGraph.ServiceModel.Entities;
using ServiceStack.MicrosoftGraph.ServiceModel.Interfaces;
using ServiceStack.MicrosoftGraph.ServiceModel.Requests;
using ServiceStack.Text;
namespace ServiceStack.Azure.Auth
{
public class MicrosoftGraphService : IAzureGraphService
{
#region Public/Internal
public string[] GetMemberGroups(string authToken)
{
var groups =
MsGraph.ActiveDirectory.MemberGroupsUrl.PostJsonToUrl("{securityEnabledOnly:false}",
requestFilter: req =>
{
req.AddBearerToken(authToken);
req.ContentType = "application/json";
req.Accept = "application/json";
});
return JsonSerializer.DeserializeFromString<string[]>(groups);
}
public AzureUserObject Me(string authToken)
{
var azureReq = MsGraph.MeUrl.GetStringFromUrl(
requestFilter: req => { req.AddBearerToken(authToken); });
var respData = JsonSerializer.DeserializeFromString<GraphResponse<AzureUserObject>>(azureReq);
return respData.Value;
// var meInfo = JsonObject.Parse(azureReq);
// var meInfoNvc = meInfo.ToNameValueCollection();
// var me = new Me
// {
// Email = meInfoNvc["mail"],
// FirstName = meInfoNvc["givenName"],
// LastName = meInfoNvc["surname"],
// Language = meInfoNvc["preferredLanguage"],
// PhoneNumber = meInfoNvc["mobilePhone"]
// };
//
// return me;
}
public async Task<AzureUserObject> MeAsync(string authToken)
{
var azureReq = await MsGraph.MeUrl.GetStringFromUrlAsync(
requestFilter: req => { req.AddBearerToken(authToken); });
var respData = JsonSerializer.DeserializeFromString<GraphResponse<AzureUserObject>>(azureReq);
return respData.Value;
}
public AzureUserObject[] Users(string authToken)
{
var azureResponse = MsGraph.DirectoryUsersUrl.GetStringFromUrl(
requestFilter: req => { req.AddBearerToken(authToken); });
var respData = JsonSerializer.DeserializeFromString<GraphResponse<AzureUserObject[]>>(azureResponse);
return respData.Value;
}
public async Task<AzureUserObject[]> UsersAsync(string authToken)
{
var azureResponse = await MsGraph.DirectoryUsersUrl.GetStringFromUrlAsync(
requestFilter: req => { req.AddBearerToken(authToken); });
var respData = JsonSerializer.DeserializeFromString<GraphResponse<AzureUserObject[]>>(azureResponse);
return respData.Value;
}
public async Task<AzureUserObject[]> UsersByGroupAsync(string authToken, string groupName)
{
var grp = await GetGroupByNameAsync(authToken, groupName);
if (grp == null)
return new AzureUserObject[0];
var data = await MsGraph.GetMembersByGroupUrl(grp.Id).GetStringFromUrlAsync(
requestFilter: req => { req.AddBearerToken(authToken); });
var usrs = GraphResponse<AzureUserObject[]>.Parse(data);
return usrs.Value;
}
public AzureUserObject[] UsersByGroup(string authToken, string groupName)
{
var grp = GetGroupByName(authToken, groupName);
if (grp == null)
return new AzureUserObject[0];
//var data = MsGraph.GetMembersByGroupUrl(grp.Id);
var usrs = ExecuteGet<AzureUserObject[]>(authToken, MsGraph.GetMembersByGroupUrl(grp.Id)); // GraphResponse<AzureUserObject[]>.Parse(data);
return usrs.Value;
}
public AzureGroupObject GetGroupByName(string authToken, string groupName)
{
var grp = ExecuteGet<AzureGroupObject[]>(authToken, MsGraph.GetGroupObjectByNameUrl(groupName));
return (grp.Value == null || grp.Value.Length == 0) ? null : grp.Value[0];
}
public async Task<AzureGroupObject> GetGroupByNameAsync(string authToken, string groupName)
{
var grp = await ExecuteGetAsync<AzureGroupObject[]>(authToken, MsGraph.GetGroupObjectByNameUrl(groupName));
return (grp.Value == null || grp.Value.Length == 0) ? null : grp.Value[0];
}
public AuthCodeRequestData RequestConsentCode(AuthCodeRequest codeRequest)
{
var state = Guid.NewGuid().ToString("N");
var reqUrl = MsGraph.GetConsentUrl(codeRequest.Upn, codeRequest.Registration.ClientId,
state, codeRequest.CallbackUrl.UrlEncode());
return new AuthCodeRequestData
{
AuthCodeRequestUrl = reqUrl,
State = state
};
}
public AuthCodeRequestData RequestAuthCode(AuthCodeRequest codeRequest)
{
var state = Guid.NewGuid().ToString("N");
var reqUrl =
$"{MsGraph.AuthorizationUrl}?client_id={codeRequest.Registration.ClientId}&response_type=code&redirect_uri={codeRequest.CallbackUrl.UrlEncode()}&domain_hint={codeRequest.UserName}&scope={BuildScopesFragment(codeRequest.Scopes)}&state={state}";
return new AuthCodeRequestData
{
AuthCodeRequestUrl = reqUrl,
State = state
};
}
public string GetLogoutUrl(string tenantId, string clientId, string redirectUrl)
{
if (string.IsNullOrWhiteSpace(clientId))
return null;
// See https://msdn.microsoft.com/en-us/office/office365/howto/authentication-v2-protocols
// var request = MsGraph.LogoutUrl + "?post_logout_redirect_uri={0}"
// .Fmt(redirectUrl);
// return authService.Redirect(LogoutUrlFilter(this, request));
return MsGraph.GetLogoutUrl(tenantId, clientId, redirectUrl);
}
public TokenResponse RequestAuthToken(AuthTokenRequest tokenRequest)
{
if (tokenRequest == null)
throw new ArgumentNullException(nameof(tokenRequest));
if (tokenRequest.Registration == null)
throw new ArgumentException("No directory registration specified.", nameof(tokenRequest.Registration));
if (string.IsNullOrWhiteSpace(tokenRequest.CallbackUrl))
throw new ArgumentException("No callback url specified.", nameof(tokenRequest.CallbackUrl));
if (string.IsNullOrWhiteSpace(tokenRequest.RequestCode))
throw new ArgumentException("No requests code specified", nameof(tokenRequest.RequestCode));
if (tokenRequest?.Scopes.Any() == false)
throw new ArgumentException("No scopes provided", nameof(tokenRequest.Scopes));
var postData =
$"grant_type=authorization_code&redirect_uri={tokenRequest.CallbackUrl.UrlEncode()}&code={tokenRequest.RequestCode}&client_id={tokenRequest.Registration.ClientId}&client_secret={tokenRequest.Registration.ClientSecret.UrlEncode()}&scope={BuildScopesFragment(tokenRequest.Scopes)}";
var result = MsGraph.TokenUrl.PostToUrl(postData);
var authInfo = JsonObject.Parse(result);
var authInfoNvc = authInfo.ToNameValueCollection();
if (MsGraph.RespondedWithError(authInfoNvc))
throw new AzureServiceException(MsGraph.TokenUrl, authInfoNvc);
return new TokenResponse
{
AuthData = authInfoNvc,
AccessToken = authInfo["access_token"],
RefreshToken = authInfo["refresh_token"],
IdToken = authInfo["id_token"],
TokenExpirationSeconds = authInfo["expires_in"]
};
}
#endregion
#region Private
private static GraphResponse<TReturn> ExecuteGet<TReturn>(string authToken, string reqUrl)
{
if (string.IsNullOrWhiteSpace(reqUrl))
return new GraphResponse<TReturn>
{
Value = default(TReturn)
};
var data = reqUrl.GetStringFromUrl(
requestFilter: req => { req.AddBearerToken(authToken); });
return GraphResponse<TReturn>.Parse(data);
}
private static async Task<GraphResponse<TReturn>> ExecuteGetAsync<TReturn>(string authToken, string reqUrl)
{
if (string.IsNullOrWhiteSpace(reqUrl))
return new GraphResponse<TReturn>
{
Value = default(TReturn)
};
var data = await reqUrl.GetStringFromUrlAsync(
requestFilter: req => { req.AddBearerToken(authToken); });
return GraphResponse<TReturn>.Parse(data);
}
private string BuildScopesFragment(string[] scopes)
{
return scopes.Select(
scope => $"{MsGraph.GraphUrl}/{scope} ").Join(" ").UrlEncode();
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Xunit;
namespace List_List_AsReadOnlyTests
{
public class VerifyReadOnlyIList<T>
{
public static void Verify(IList<T> list, T[] items, Func<T> generateItem)
{
VerifyIsReadOnly(list, items);
VerifyIndexOf(list, items);
VerifyContains(list, items);
VerifyItem_Get(list, items);
CopyTo_Tests(list, items, generateItem);
// IEnumerable<T> interface
MoveNext_Tests(list, items);
Current_Tests(list, items);
Reset_Tests(list, items);
}
public static void VerifyExceptions(IList<T> list, T[] items, Func<T> generateItem)
{
VerifyAdd(list, items);
VerifyClear(list, items);
VerifyInsert(list, items);
VerifyRemove(list, items);
VerifyRemoveAt(list, items);
VerifyItem_Set(list, items);
CopyTo_Tests_Negative(list, items, generateItem);
}
private static void VerifyAdd(IList<T> list, T[] items)
{
int origCount = list.Count;
//[]Try adding an item to the colleciton and verify Add throws NotSupportedException
Assert.Throws<NotSupportedException>(() => list.Add(default(T))); //"Err_27027ahbz!!! Not supported Exception should have been thrown when calling Add on a readonly collection"
Assert.Equal(origCount, list.Count); //string.Format("Err_7072habpo!!! Expected Count={0} actual={1} after calling Add on a readonly collection", origCount, list.Count)
}
private static void VerifyInsert(IList<T> list, T[] items)
{
int origCount = list.Count;
//[]Verify Insert throws NotSupportedException
Assert.Throws<NotSupportedException>(() => list.Insert(0, default(T))); //"Err_558449ahpba!!! Not supported Exception should have been thrown when calling Insert on a readonly collection"
Assert.Equal(origCount, list.Count); //string.Format("Err_7072habpo!!! Expected Count={0} actual={1} after calling Add on a readonly collection", origCount, list.Count)
}
private static void VerifyClear(IList<T> list, T[] items)
{
int origCount = list.Count;
//[]Verify Clear throws NotSupportedException
Assert.Throws<NotSupportedException>(() => list.Clear()); //"Err_7027qhpa!!! Not supported Exception should have been thrown when calling Clear on a readonly collection"
Assert.Equal(origCount, list.Count); //string.Format("Err_7072habpo!!! Expected Count={0} actual={1} after calling Add on a readonly collection", origCount, list.Count)
}
private static void VerifyRemove(IList<T> list, T[] items)
{
int origCount = list.Count;
//[]Verify Remove throws NotSupportedException
if (null != items && items.Length != 0)
{
Assert.Throws<NotSupportedException>(() => list.Remove(items[0])); //"Err_8207aahpb!!! Not supported Exception should have been thrown when calling Remove on a readonly collection"
}
else
{
Assert.Throws<NotSupportedException>(() => list.Remove(default(T))); //"Err_8207aahpb!!! Not supported Exception should have been thrown when calling Remove on a readonly collection"
}
Assert.Equal(origCount, list.Count); //string.Format("Err_7072habpo!!! Expected Count={0} actual={1} after calling Add on a readonly collection", origCount, list.Count)
}
private static void VerifyRemoveAt(IList<T> list, T[] items)
{
int origCount = list.Count;
//[]Verify RemoveAt throws NotSupportedException
Assert.Throws<NotSupportedException>(() => list.RemoveAt(0)); //"Err_77894ahpba!!! Not supported Exception should have been thrown when calling RemoveAt on a readonly collection"
Assert.Equal(origCount, list.Count); //string.Format("Err_7072habpo!!! Expected Count={0} actual={1} after calling Add on a readonly collection", origCount, list.Count)
}
private static void VerifyItem_Set(IList<T> list, T[] items)
{
//[]Verify Item_Set throws NotSupportedException
Assert.Throws<NotSupportedException>(() => list[0] = default(T)); //"Err_77894ahpba!!! Not supported Exception should have been thrown when calling Item_Set on a readonly collection"
}
private static void VerifyIsReadOnly(IList<T> list, T[] items)
{
Assert.True(list.IsReadOnly); //"Err_44894phkni!!! Expected IsReadOnly to be false"
}
private static void VerifyIndexOf(IList<T> list, T[] items)
{
int index;
for (int i = 0; i < items.Length; ++i)
{
Assert.True(i == (index = list.IndexOf(items[i])) || items[i].Equals(items[index]),
string.Format("Err_331697ahpba Expect IndexOf to return an index to item equal to={0} actual={1} IndexReturned={2} items Index={3}",
items[i], items[index], index, i));
}
}
private static void VerifyContains(IList<T> list, T[] items)
{
for (int i = 0; i < items.Length; ++i)
{
Assert.True(list.Contains(items[i]),
string.Format("Err_1568ahpa Expected Contains to return true with item={0} items index={1}",
items[i], i));
}
}
private static void VerifyItem_Get(IList<T> list, T[] items)
{
Assert.Equal(items.Length, list.Count); //"Should have the same number of items in each list."
for (int i = 0; i < items.Length; ++i)
{
Assert.Equal(items[i], list[i]); //string.Format("Err_70717ahbpa Expected list[{0}]={1} actual={2}", i, items[i], list[i])
}
}
private static void Verify_IndexOf(IList<T> collection, T[] items)
{
Assert.Equal(items.Length, collection.Count); //"Err_669713ahzp Verifying IndexOf the count of the collection"
for (int i = 0; i < items.Length; i++)
{
int indexOfRetVal = collection.IndexOf(items[i]);
Assert.NotEqual(-1, indexOfRetVal); //"Err_1634pnyan Verifying IndexOf and expected item: " + items[i] + " to be in the colleciton. Index:" + i
Assert.Equal(items[indexOfRetVal], items[i]); //string.Format("Err_88489apps Verifying IndexOf and the index returned is wrong expected to find {0} at {1} actually found {2} at {3}", items[i], i, items[indexOfRetVal], indexOfRetVal)
Assert.Equal(items[i], collection[indexOfRetVal]); //string.Format("Err_32198ahps Verifying IndexOf and the index returned is wrong expected to find {0} at {1} actually found {2} at {3}", items[i], i, items[indexOfRetVal], indexOfRetVal)
}
}
/// <summary>
/// Runs all of the tests on CopyTo(Array).
/// </summary>
private static void CopyTo_Tests(IList<T> collection, T[] items, Func<T> generateItem)
{
T[] itemArray = null, tempItemsArray = null;
// [] CopyTo with index=0 and the array is the same size as the collection
itemArray = GenerateArray(items.Length, generateItem);
collection.CopyTo(itemArray, 0);
VerifyItem_Get(itemArray, items);
// [] CopyTo with index=0 and the array is 4 items larger then size as the collection
itemArray = GenerateArray(items.Length + 4, generateItem);
tempItemsArray = new T[items.Length + 4];
Array.Copy(itemArray, tempItemsArray, itemArray.Length);
Array.Copy(items, 0, tempItemsArray, 0, items.Length);
collection.CopyTo(itemArray, 0);
VerifyItem_Get(itemArray, tempItemsArray);
// [] CopyTo with index=4 and the array is 4 items larger then size as the collection
itemArray = GenerateArray(items.Length + 4, generateItem);
tempItemsArray = new T[items.Length + 4];
Array.Copy(itemArray, tempItemsArray, itemArray.Length);
Array.Copy(items, 0, tempItemsArray, 4, items.Length);
collection.CopyTo(itemArray, 4);
VerifyItem_Get(itemArray, tempItemsArray);
// [] CopyTo with index=4 and the array is 8 items larger then size as the collection
itemArray = GenerateArray(items.Length + 8, generateItem);
tempItemsArray = new T[items.Length + 8];
Array.Copy(itemArray, tempItemsArray, itemArray.Length);
Array.Copy(items, 0, tempItemsArray, 4, items.Length);
collection.CopyTo(itemArray, 4);
VerifyItem_Get(itemArray, tempItemsArray);
}
private static void CopyTo_Tests_Negative(IList<T> collection, T[] items, Func<T> generateItem)
{
T[] itemArray = null, tempItemsArray = null;
//[] Verify CopyTo with null array
Assert.Throws<ArgumentNullException>(() => collection.CopyTo(null, 0)); //"Err_2470zsou: Exception not thrown with null array"
// [] Verify CopyTo with index=Int32.MinValue
itemArray = GenerateArray(items.Length, generateItem);
tempItemsArray = (T[])itemArray.Clone();
Assert.Throws<ArgumentOutOfRangeException>(
() => collection.CopyTo(new T[collection.Count], Int32.MinValue)); //"Err_68971aehps: Exception not thrown with index=Int32.MinValue"
//Verify that the array was not mutated
VerifyItem_Get(itemArray, tempItemsArray);
// [] Verify CopyTo with index=-1
itemArray = GenerateArray(items.Length, generateItem);
tempItemsArray = (T[])itemArray.Clone();
Assert.Throws<ArgumentOutOfRangeException>(
() => collection.CopyTo(new T[collection.Count], -1)); //"Err_3771zsiap: Exception not thrown with index=-1"
//Verify that the array was not mutated
VerifyItem_Get(itemArray, tempItemsArray);
// [] Verify CopyTo with index=Int32.MaxValue
itemArray = GenerateArray(items.Length, generateItem);
tempItemsArray = (T[])itemArray.Clone();
Assert.Throws<ArgumentException>(() => collection.CopyTo(new T[collection.Count], Int32.MaxValue)); //"Err_39744ahps: Exception not thrown with index=Int32.MaxValue"
//Verify that the array was not mutated
VerifyItem_Get(itemArray, tempItemsArray);
if (items.Length > 0)
{
// [] Verify CopyTo with index=array.length
itemArray = GenerateArray(items.Length, generateItem);
tempItemsArray = (T[])itemArray.Clone();
T[] output = new T[collection.Count];
Assert.Throws<ArgumentException>(
() => collection.CopyTo(output, collection.Count)); //"Err_2078auoz: Exception not thow with index=array.Length"
//Verify that the array was not mutated
VerifyItem_Get(itemArray, tempItemsArray);
// [] Verify CopyTo with collection.Count > array.length - index
itemArray = GenerateArray(items.Length + 1, generateItem);
tempItemsArray = (T[])itemArray.Clone();
Assert.Throws<ArgumentException>(() => collection.CopyTo(new T[items.Length + 1], 2)); //"Err_1734nmzb: Correct exception not thrown with collection.Count > array.length - index"
//Verify that the array was not mutated
VerifyItem_Get(itemArray, tempItemsArray);
}
}
/// <summary>
/// Runs all of the tests on MoveNext().
/// </summary>
private static void MoveNext_Tests(IList<T> collection, T[] items)
{
int iterations = 0;
IEnumerator<T> enumerator = collection.GetEnumerator();
//[] Call MoveNext() untill the end of the collection has been reached
while (enumerator.MoveNext())
iterations++;
Assert.Equal(items.Length, iterations); //"Err_64897adhs Number of items to iterate through"
//[] Call MoveNext() several times after the end of the collection has been reached
for (int j = 0; j < 3; j++)
{
try
{
T tempCurrent = enumerator.Current;
}
catch (InvalidOperationException) { }//Behavior of Current here is undefined
Assert.False(enumerator.MoveNext(),
"Err_1081adohs Expected MoveNext() to return false on the " + (j + 1) + " after the end of the collection has been reached\n");
}
}
/// <summary>
/// Runs all of the tests on Current.
/// </summary>
private static void Current_Tests(IList<T> collection, T[] items)
{
IEnumerator<T> enumerator = collection.GetEnumerator();
//[] Call MoveNext() untill the end of the collection has been reached
VerifyEnumerator(enumerator, items, 0, items.Length);
//[] Enumerate only part of the collection
enumerator = collection.GetEnumerator();
VerifyEnumerator(enumerator, items, 0, items.Length / 2);
}
/// <summary>
/// Runs all of the tests on Reset().
/// </summary>
private static void Reset_Tests(IList<T> collection, T[] items)
{
IEnumerator<T> enumerator = collection.GetEnumerator();
//[] Call Reset() several times on a new Enumerator then enumerate the collection
VerifyEnumerator(enumerator, items, 0, items.Length);
enumerator.Reset();
//[] Enumerate part of the collection then call Reset() several times
VerifyEnumerator(enumerator, items, 0, items.Length / 2);
enumerator.Reset();
enumerator.Reset();
enumerator.Reset();
//[] After Enumerating only part of the collection and Reset() was called several times and enumerate through the entire collection
VerifyEnumerator(enumerator, items, 0, items.Length);
enumerator.Reset();
//[] Enumerate the entire collection then call Reset() several times
VerifyEnumerator(enumerator, items, 0, items.Length);
enumerator.Reset();
enumerator.Reset();
enumerator.Reset();
//[] After Enumerating the entire collection and Reset() was called several times and enumerate through the entire collection
VerifyEnumerator(enumerator, items, 0, items.Length);
enumerator.Reset();
}
private static void VerifyEnumerator(IEnumerator<T> enumerator, T[] expectedItems, int startIndex, int count)
{
int iterations = 0;
//[] Verify non deterministic behavior of current every time it is called before a call to MoveNext() has been made
for (int i = 0; i < 3; i++)
{
try
{
T tempCurrent = enumerator.Current;
}
catch (InvalidOperationException) { }
}
while ((iterations < count) && enumerator.MoveNext())
{
T currentItem = enumerator.Current;
T tempItem;
//[] Verify we have not gotten more items then we expected
Assert.True(iterations < count, "Err_9844awpa More items have been returned fromt the enumerator(" + iterations
+ " items) then are " + "in the expectedElements(" + count + " items)");
//[] Verify Current returned the correct value
Assert.Equal(expectedItems[startIndex + iterations], currentItem); //"Err_1432pauy Current returned unexpected value"
//[] Verify Current always returns the same value every time it is called
for (int i = 0; i < 3; i++)
{
tempItem = enumerator.Current;
Assert.Equal(currentItem, tempItem); //"Err_8776phaw Current is returning inconsistant results Current."
}
iterations++;
}
Assert.Equal(count, iterations); //"Err_658805eauz Number of items to iterate through"
if (expectedItems.Length == (count - startIndex))
{
//[] Verify non deterministic behavior of current every time it is called after the enumerator is positioned after the last item
for (int i = 0; i < 3; i++)
{
try
{
T tempCurrent = enumerator.Current;
}
catch (InvalidOperationException) { }
Assert.False(enumerator.MoveNext()); //"Err_2929ahiea Expected MoveNext to return false after" + iterations + " iterations"
}
}
}
private static T[] GenerateArray(int length, Func<T> generateItem)
{
T[] items = new T[length];
if (null != generateItem)
{
for (int i = 0; i < items.Length; i++)
{
items[i] = generateItem();
}
}
return items;
}
}
public class Driver<T>
{
public void CheckType()
{
// VSWhidbey #378658
List<T> list = new List<T>();
ReadOnlyCollection<T> readOnlyList = new ReadOnlyCollection<T>(list);
Assert.Equal(typeof(ReadOnlyCollection<T>), readOnlyList.GetType()); //"Err_1703r38abhpx Read Only Collection Type Test FAILED"
}
public void EmptyCollection(Func<T> generateItem, bool testExceptions)
{
List<T> list = new List<T>();
if (testExceptions)
VerifyReadOnlyIList<T>.VerifyExceptions(new ReadOnlyCollection<T>(list), new T[0], generateItem);
else
VerifyReadOnlyIList<T>.Verify(new ReadOnlyCollection<T>(list), new T[0], generateItem);
}
public void NonEmptyCollectionIEnumerableCtor(T[] items, Func<T> generateItem, bool testExceptions)
{
List<T> list = new List<T>(new TestCollection<T>(items));
if (testExceptions)
VerifyReadOnlyIList<T>.VerifyExceptions(new ReadOnlyCollection<T>(list), items, generateItem);
else
VerifyReadOnlyIList<T>.Verify(new ReadOnlyCollection<T>(list), items, generateItem);
//, "Err_884964ahbz NON Empty Collection using the IEnumerable constructor to populate the list Test FAILED");
}
public void NonEmptyCollectionAdd(T[] items, Func<T> generateItem, bool testExceptions)
{
List<T> list = new List<T>();
for (int i = 0; i < items.Length; ++i)
list.Add(items[i]);
if (testExceptions)
VerifyReadOnlyIList<T>.VerifyExceptions(new ReadOnlyCollection<T>(list), items, generateItem);
else
VerifyReadOnlyIList<T>.Verify(new ReadOnlyCollection<T>(list), items, generateItem);
}
public void AddRemoveSome(T[] items, T[] itemsToAdd, T[] itemsToRemove, Func<T> generateItem, bool testExceptions)
{
List<T> list = new List<T>();
for (int i = 0; i < itemsToAdd.Length; ++i)
list.Add(itemsToAdd[i]);
for (int i = 0; i < itemsToRemove.Length; ++i)
list.Remove(itemsToRemove[i]);
if (testExceptions)
VerifyReadOnlyIList<T>.VerifyExceptions(new ReadOnlyCollection<T>(list), items, generateItem);
else
VerifyReadOnlyIList<T>.Verify(new ReadOnlyCollection<T>(list), items, generateItem);
}
public void AddRemoveAll(T[] items, Func<T> generateItem, bool testExceptions)
{
List<T> list = new List<T>();
for (int i = 0; i < items.Length; ++i)
list.Add(items[i]);
for (int i = 0; i < items.Length; ++i)
list.RemoveAt(0);
if (testExceptions)
VerifyReadOnlyIList<T>.VerifyExceptions(new ReadOnlyCollection<T>(list), new T[0], generateItem);
else
VerifyReadOnlyIList<T>.Verify(new ReadOnlyCollection<T>(list), new T[0], generateItem);
}
public void AddClear(T[] items, Func<T> generateItem, bool testExceptions)
{
List<T> list = new List<T>();
for (int i = 0; i < items.Length; ++i)
list.Add(items[i]);
list.Clear();
if (testExceptions)
VerifyReadOnlyIList<T>.VerifyExceptions(new ReadOnlyCollection<T>(list), new T[0], generateItem);
else
VerifyReadOnlyIList<T>.Verify(new ReadOnlyCollection<T>(list), new T[0], generateItem);
}
}
public class List_AsReadOnlyTests
{
[Fact]
public static void CheckType()
{
Driver<RefX1<int>> IntDriver = new Driver<RefX1<int>>();
Driver<ValX1<string>> stringDriver = new Driver<ValX1<string>>();
IntDriver.CheckType();
stringDriver.CheckType();
}
[Fact]
public static void EmptyCollection()
{
Driver<RefX1<int>> IntDriver = new Driver<RefX1<int>>();
RefX1IntGenerator refX1IntGenerator = new RefX1IntGenerator();
Driver<ValX1<string>> stringDriver = new Driver<ValX1<string>>();
ValX1stringGenerator valX1stringGenerator = new ValX1stringGenerator();
IntDriver.EmptyCollection(refX1IntGenerator.NextValue, false);
stringDriver.EmptyCollection(valX1stringGenerator.NextValue, false);
}
[Fact]
public static void EmptyCollection_Negative()
{
Driver<RefX1<int>> IntDriver = new Driver<RefX1<int>>();
RefX1IntGenerator refX1IntGenerator = new RefX1IntGenerator();
Driver<ValX1<string>> stringDriver = new Driver<ValX1<string>>();
ValX1stringGenerator valX1stringGenerator = new ValX1stringGenerator();
IntDriver.EmptyCollection(refX1IntGenerator.NextValue, true);
stringDriver.EmptyCollection(valX1stringGenerator.NextValue, true);
}
[Fact]
public static void NonEmptyCollectionIEnumerableCtor()
{
Driver<RefX1<int>> IntDriver = new Driver<RefX1<int>>();
RefX1IntGenerator refX1IntGenerator = new RefX1IntGenerator();
RefX1<int>[] intArrToRemove, intArrAfterRemove;
RefX1<int>[] intArr = PrepTests(refX1IntGenerator, 100, out intArrToRemove, out intArrAfterRemove);
Driver<ValX1<string>> stringDriver = new Driver<ValX1<string>>();
ValX1stringGenerator valX1stringGenerator = new ValX1stringGenerator();
ValX1<string>[] stringArrToRemove, stringArrAfterRemove;
ValX1<string>[] stringArr = PrepTests(valX1stringGenerator, 100, out stringArrToRemove, out stringArrAfterRemove);
IntDriver.NonEmptyCollectionIEnumerableCtor(intArr, refX1IntGenerator.NextValue, false);
stringDriver.NonEmptyCollectionIEnumerableCtor(stringArr, valX1stringGenerator.NextValue, false);
}
[Fact]
public static void NonEmptyCollectionIEnumerableCtor_Negative()
{
Driver<RefX1<int>> IntDriver = new Driver<RefX1<int>>();
RefX1IntGenerator refX1IntGenerator = new RefX1IntGenerator();
RefX1<int>[] intArrToRemove, intArrAfterRemove;
RefX1<int>[] intArr = PrepTests(refX1IntGenerator, 100, out intArrToRemove, out intArrAfterRemove);
Driver<ValX1<string>> stringDriver = new Driver<ValX1<string>>();
ValX1stringGenerator valX1stringGenerator = new ValX1stringGenerator();
ValX1<string>[] stringArrToRemove, stringArrAfterRemove;
ValX1<string>[] stringArr = PrepTests(valX1stringGenerator, 100, out stringArrToRemove, out stringArrAfterRemove);
IntDriver.NonEmptyCollectionIEnumerableCtor(intArr, refX1IntGenerator.NextValue, true);
stringDriver.NonEmptyCollectionIEnumerableCtor(stringArr, valX1stringGenerator.NextValue, true);
}
[Fact]
public static void NonEmptyCollectionAdd()
{
Driver<RefX1<int>> IntDriver = new Driver<RefX1<int>>();
RefX1IntGenerator refX1IntGenerator = new RefX1IntGenerator();
RefX1<int>[] intArrToRemove, intArrAfterRemove;
RefX1<int>[] intArr = PrepTests(refX1IntGenerator, 100, out intArrToRemove, out intArrAfterRemove);
Driver<ValX1<string>> stringDriver = new Driver<ValX1<string>>();
ValX1stringGenerator valX1stringGenerator = new ValX1stringGenerator();
ValX1<string>[] stringArrToRemove, stringArrAfterRemove;
ValX1<string>[] stringArr = PrepTests(valX1stringGenerator, 100, out stringArrToRemove, out stringArrAfterRemove);
IntDriver.NonEmptyCollectionAdd(intArr, refX1IntGenerator.NextValue, false);
stringDriver.NonEmptyCollectionAdd(stringArr, valX1stringGenerator.NextValue, false);
}
[Fact]
public static void NonEmptyCollectionAdd_Negative()
{
Driver<RefX1<int>> IntDriver = new Driver<RefX1<int>>();
RefX1IntGenerator refX1IntGenerator = new RefX1IntGenerator();
RefX1<int>[] intArrToRemove, intArrAfterRemove;
RefX1<int>[] intArr = PrepTests(refX1IntGenerator, 100, out intArrToRemove, out intArrAfterRemove);
Driver<ValX1<string>> stringDriver = new Driver<ValX1<string>>();
ValX1stringGenerator valX1stringGenerator = new ValX1stringGenerator();
ValX1<string>[] stringArrToRemove, stringArrAfterRemove;
ValX1<string>[] stringArr = PrepTests(valX1stringGenerator, 100, out stringArrToRemove, out stringArrAfterRemove);
IntDriver.NonEmptyCollectionAdd(intArr, refX1IntGenerator.NextValue, true);
stringDriver.NonEmptyCollectionAdd(stringArr, valX1stringGenerator.NextValue, true);
}
[Fact]
public static void AddRemoveSome()
{
Driver<RefX1<int>> IntDriver = new Driver<RefX1<int>>();
RefX1IntGenerator refX1IntGenerator = new RefX1IntGenerator();
RefX1<int>[] intArrToRemove, intArrAfterRemove;
RefX1<int>[] intArr = PrepTests(refX1IntGenerator, 100, out intArrToRemove, out intArrAfterRemove);
Driver<ValX1<string>> stringDriver = new Driver<ValX1<string>>();
ValX1stringGenerator valX1stringGenerator = new ValX1stringGenerator();
ValX1<string>[] stringArrToRemove, stringArrAfterRemove;
ValX1<string>[] stringArr = PrepTests(valX1stringGenerator, 100, out stringArrToRemove, out stringArrAfterRemove);
IntDriver.AddRemoveSome(intArrAfterRemove, intArr, intArrToRemove, refX1IntGenerator.NextValue, false);
stringDriver.AddRemoveSome(stringArrAfterRemove, stringArr, stringArrToRemove, valX1stringGenerator.NextValue, false);
}
[Fact]
public static void AddRemoveSome_Negative()
{
Driver<RefX1<int>> IntDriver = new Driver<RefX1<int>>();
RefX1IntGenerator refX1IntGenerator = new RefX1IntGenerator();
RefX1<int>[] intArrToRemove, intArrAfterRemove;
RefX1<int>[] intArr = PrepTests(refX1IntGenerator, 100, out intArrToRemove, out intArrAfterRemove);
Driver<ValX1<string>> stringDriver = new Driver<ValX1<string>>();
ValX1stringGenerator valX1stringGenerator = new ValX1stringGenerator();
ValX1<string>[] stringArrToRemove, stringArrAfterRemove;
ValX1<string>[] stringArr = PrepTests(valX1stringGenerator, 100, out stringArrToRemove, out stringArrAfterRemove);
IntDriver.AddRemoveSome(intArrAfterRemove, intArr, intArrToRemove, refX1IntGenerator.NextValue, true);
stringDriver.AddRemoveSome(stringArrAfterRemove, stringArr, stringArrToRemove, valX1stringGenerator.NextValue, true);
}
[Fact]
public static void AddRemoveAll()
{
Driver<RefX1<int>> IntDriver = new Driver<RefX1<int>>();
RefX1IntGenerator refX1IntGenerator = new RefX1IntGenerator();
RefX1<int>[] intArrToRemove, intArrAfterRemove;
RefX1<int>[] intArr = PrepTests(refX1IntGenerator, 100, out intArrToRemove, out intArrAfterRemove);
Driver<ValX1<string>> stringDriver = new Driver<ValX1<string>>();
ValX1stringGenerator valX1stringGenerator = new ValX1stringGenerator();
ValX1<string>[] stringArrToRemove, stringArrAfterRemove;
ValX1<string>[] stringArr = PrepTests(valX1stringGenerator, 100, out stringArrToRemove, out stringArrAfterRemove);
IntDriver.AddRemoveAll(intArr, refX1IntGenerator.NextValue, false);
stringDriver.AddRemoveAll(stringArr, valX1stringGenerator.NextValue, false);
}
[Fact]
public static void AddRemoveAll_Negative()
{
Driver<RefX1<int>> IntDriver = new Driver<RefX1<int>>();
RefX1IntGenerator refX1IntGenerator = new RefX1IntGenerator();
RefX1<int>[] intArrToRemove, intArrAfterRemove;
RefX1<int>[] intArr = PrepTests(refX1IntGenerator, 100, out intArrToRemove, out intArrAfterRemove);
Driver<ValX1<string>> stringDriver = new Driver<ValX1<string>>();
ValX1stringGenerator valX1stringGenerator = new ValX1stringGenerator();
ValX1<string>[] stringArrToRemove, stringArrAfterRemove;
ValX1<string>[] stringArr = PrepTests(valX1stringGenerator, 100, out stringArrToRemove, out stringArrAfterRemove);
IntDriver.AddRemoveAll(intArr, refX1IntGenerator.NextValue, true);
stringDriver.AddRemoveAll(stringArr, valX1stringGenerator.NextValue, true);
}
[Fact]
public static void AddClear()
{
Driver<RefX1<int>> IntDriver = new Driver<RefX1<int>>();
RefX1IntGenerator refX1IntGenerator = new RefX1IntGenerator();
RefX1<int>[] intArrToRemove, intArrAfterRemove;
RefX1<int>[] intArr = PrepTests(refX1IntGenerator, 100, out intArrToRemove, out intArrAfterRemove);
Driver<ValX1<string>> stringDriver = new Driver<ValX1<string>>();
ValX1stringGenerator valX1stringGenerator = new ValX1stringGenerator();
ValX1<string>[] stringArrToRemove, stringArrAfterRemove;
ValX1<string>[] stringArr = PrepTests(valX1stringGenerator, 100, out stringArrToRemove, out stringArrAfterRemove);
IntDriver.AddClear(intArr, refX1IntGenerator.NextValue, false);
stringDriver.AddClear(stringArr, valX1stringGenerator.NextValue, false);
}
[Fact]
public static void AddClear_Negative()
{
Driver<RefX1<int>> IntDriver = new Driver<RefX1<int>>();
RefX1IntGenerator refX1IntGenerator = new RefX1IntGenerator();
RefX1<int>[] intArrToRemove, intArrAfterRemove;
RefX1<int>[] intArr = PrepTests(refX1IntGenerator, 100, out intArrToRemove, out intArrAfterRemove);
Driver<ValX1<string>> stringDriver = new Driver<ValX1<string>>();
ValX1stringGenerator valX1stringGenerator = new ValX1stringGenerator();
ValX1<string>[] stringArrToRemove, stringArrAfterRemove;
ValX1<string>[] stringArr = PrepTests(valX1stringGenerator, 100, out stringArrToRemove, out stringArrAfterRemove);
IntDriver.AddClear(intArr, refX1IntGenerator.NextValue, true);
stringDriver.AddClear(stringArr, valX1stringGenerator.NextValue, true);
}
private static ValX1<string>[] PrepTests(ValX1stringGenerator generator, int count,
out ValX1<string>[] toRemove, out ValX1<string>[] afterRemove)
{
ValX1<string>[] entireArray = new ValX1<string>[count];
toRemove = new ValX1<string>[count / 2];
afterRemove = new ValX1<string>[count / 2];
for (int i = 0; i < 100; i++)
{
entireArray[i] = generator.NextValue();
if ((i & 1) != 0)
toRemove[i / 2] = entireArray[i];
else
afterRemove[i / 2] = entireArray[i];
}
return entireArray;
}
private static RefX1<int>[] PrepTests(RefX1IntGenerator generator, int count,
out RefX1<int>[] toRemove, out RefX1<int>[] afterRemove)
{
RefX1<int>[] entireArray = new RefX1<int>[count];
toRemove = new RefX1<int>[count / 2];
afterRemove = new RefX1<int>[count / 2];
for (int i = 0; i < 100; i++)
{
entireArray[i] = generator.NextValue();
if ((i & 1) != 0)
toRemove[i / 2] = entireArray[i];
else
afterRemove[i / 2] = entireArray[i];
}
return entireArray;
}
}
#region Helper Classes
/// <summary>
/// Helps tests reference types.
/// </summary>
public class RefX1<T> : IComparable<RefX1<T>> where T : IComparable
{
private T _val;
public T Val
{
get { return _val; }
set { _val = value; }
}
public RefX1(T t) { _val = t; }
public int CompareTo(RefX1<T> obj)
{
if (null == obj)
return 1;
if (null == _val)
if (null == obj.Val)
return 0;
else
return -1;
return _val.CompareTo(obj.Val);
}
public override bool Equals(object obj)
{
if (obj is RefX1<T>)
{
RefX1<T> v = (RefX1<T>)obj;
return (CompareTo(v) == 0);
}
return false;
}
public override int GetHashCode() { return base.GetHashCode(); }
public bool Equals(RefX1<T> x)
{
return 0 == CompareTo(x);
}
}
public class RefX1IntGenerator
{
private int _index;
public RefX1IntGenerator()
{
_index = 1;
}
public RefX1<int> NextValue()
{
return new RefX1<int>(_index++);
}
}
/// <summary>
/// Helps test value types.
/// </summary>
public struct ValX1<T> : IComparable<ValX1<T>> where T : IComparable
{
private T _val;
public T Val
{
get { return _val; }
set { _val = value; }
}
public ValX1(T t) { _val = t; }
public int CompareTo(ValX1<T> obj)
{
if (Object.ReferenceEquals(_val, obj._val)) return 0;
if (null == _val)
return -1;
return _val.CompareTo(obj.Val);
}
public override bool Equals(object obj)
{
if (obj is ValX1<T>)
{
ValX1<T> v = (ValX1<T>)obj;
return (CompareTo(v) == 0);
}
return false;
}
public override int GetHashCode() { return ((object)this).GetHashCode(); }
public bool Equals(ValX1<T> x)
{
return 0 == CompareTo(x);
}
}
public class ValX1stringGenerator
{
private int _index;
public ValX1stringGenerator()
{
_index = 1;
}
public ValX1<string> NextValue()
{
return new ValX1<string>((_index++).ToString());
}
}
/// <summary>
/// Helper class that implements ICollection.
/// </summary>
public class TestCollection<T> : ICollection<T>
{
/// <summary>
/// Expose the Items in Array to give more test flexibility...
/// </summary>
public readonly T[] m_items;
public TestCollection(T[] items)
{
m_items = items;
}
public void CopyTo(T[] array, int index)
{
Array.Copy(m_items, 0, array, index, m_items.Length);
}
public int Count
{
get
{
if (m_items == null)
return 0;
else
return m_items.Length;
}
}
public Object SyncRoot { get { return this; } }
public bool IsSynchronized { get { return false; } }
public IEnumerator<T> GetEnumerator()
{
return new TestCollectionEnumerator<T>(this);
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return new TestCollectionEnumerator<T>(this);
}
private class TestCollectionEnumerator<T1> : IEnumerator<T1>
{
private TestCollection<T1> _col;
private int _index;
public void Dispose() { }
public TestCollectionEnumerator(TestCollection<T1> col)
{
_col = col;
_index = -1;
}
public bool MoveNext()
{
return (++_index < _col.m_items.Length);
}
public T1 Current
{
get { return _col.m_items[_index]; }
}
Object System.Collections.IEnumerator.Current
{
get { return _col.m_items[_index]; }
}
public void Reset()
{
_index = -1;
}
}
#region Non Implemented methods
public void Add(T item) { throw new NotSupportedException(); }
public void Clear() { throw new NotSupportedException(); }
public bool Contains(T item) { throw new NotSupportedException(); }
public bool Remove(T item) { throw new NotSupportedException(); }
public bool IsReadOnly { get { throw new NotSupportedException(); } }
#endregion
}
#endregion
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Reactive.Linq;
using Avalonia.Media;
using Avalonia.Styling;
using Avalonia.Threading;
using Avalonia.VisualTree;
namespace Avalonia.Controls.Presenters
{
public class TextPresenter : TextBlock
{
public static readonly DirectProperty<TextPresenter, int> CaretIndexProperty =
TextBox.CaretIndexProperty.AddOwner<TextPresenter>(
o => o.CaretIndex,
(o, v) => o.CaretIndex = v);
public static readonly DirectProperty<TextPresenter, int> SelectionStartProperty =
TextBox.SelectionStartProperty.AddOwner<TextPresenter>(
o => o.SelectionStart,
(o, v) => o.SelectionStart = v);
public static readonly DirectProperty<TextPresenter, int> SelectionEndProperty =
TextBox.SelectionEndProperty.AddOwner<TextPresenter>(
o => o.SelectionEnd,
(o, v) => o.SelectionEnd = v);
private readonly DispatcherTimer _caretTimer;
private int _caretIndex;
private int _selectionStart;
private int _selectionEnd;
private bool _caretBlink;
private IBrush _highlightBrush;
public TextPresenter()
{
_caretTimer = new DispatcherTimer();
_caretTimer.Interval = TimeSpan.FromMilliseconds(500);
_caretTimer.Tick += CaretTimerTick;
Observable.Merge(
this.GetObservable(SelectionStartProperty),
this.GetObservable(SelectionEndProperty))
.Subscribe(_ => InvalidateFormattedText());
this.GetObservable(CaretIndexProperty)
.Subscribe(CaretIndexChanged);
}
public int CaretIndex
{
get
{
return _caretIndex;
}
set
{
value = CoerceCaretIndex(value);
SetAndRaise(CaretIndexProperty, ref _caretIndex, value);
}
}
public int SelectionStart
{
get
{
return _selectionStart;
}
set
{
value = CoerceCaretIndex(value);
SetAndRaise(SelectionStartProperty, ref _selectionStart, value);
}
}
public int SelectionEnd
{
get
{
return _selectionEnd;
}
set
{
value = CoerceCaretIndex(value);
SetAndRaise(SelectionEndProperty, ref _selectionEnd, value);
}
}
public int GetCaretIndex(Point point)
{
var hit = FormattedText.HitTestPoint(point);
return hit.TextPosition + (hit.IsTrailing ? 1 : 0);
}
public override void Render(DrawingContext context)
{
var selectionStart = SelectionStart;
var selectionEnd = SelectionEnd;
if (selectionStart != selectionEnd)
{
var start = Math.Min(selectionStart, selectionEnd);
var length = Math.Max(selectionStart, selectionEnd) - start;
// issue #600: set constaint before any FormattedText manipulation
// see base.Render(...) implementation
FormattedText.Constraint = Bounds.Size;
var rects = FormattedText.HitTestTextRange(start, length);
if (_highlightBrush == null)
{
_highlightBrush = (IBrush)this.FindStyleResource("HighlightBrush");
}
foreach (var rect in rects)
{
context.FillRectangle(_highlightBrush, rect);
}
}
base.Render(context);
if (selectionStart == selectionEnd)
{
var backgroundColor = (((Control)TemplatedParent).GetValue(BackgroundProperty) as SolidColorBrush)?.Color;
var caretBrush = Brushes.Black;
if (backgroundColor.HasValue)
{
byte red = (byte)~(backgroundColor.Value.R);
byte green = (byte)~(backgroundColor.Value.G);
byte blue = (byte)~(backgroundColor.Value.B);
caretBrush = new SolidColorBrush(Color.FromRgb(red, green, blue));
}
if (_caretBlink)
{
var charPos = FormattedText.HitTestTextPosition(CaretIndex);
var x = Math.Floor(charPos.X) + 0.5;
var y = Math.Floor(charPos.Y) + 0.5;
var b = Math.Ceiling(charPos.Bottom) - 0.5;
context.DrawLine(
new Pen(caretBrush, 1),
new Point(x, y),
new Point(x, b));
}
}
}
public void ShowCaret()
{
_caretBlink = true;
_caretTimer.Start();
InvalidateVisual();
}
public void HideCaret()
{
_caretBlink = false;
_caretTimer.Stop();
InvalidateVisual();
}
internal void CaretIndexChanged(int caretIndex)
{
if (this.GetVisualParent() != null)
{
if (_caretTimer.IsEnabled)
{
_caretBlink = true;
_caretTimer.Stop();
_caretTimer.Start();
InvalidateVisual();
}
if (IsMeasureValid)
{
var rect = FormattedText.HitTestTextPosition(caretIndex);
this.BringIntoView(rect);
}
else
{
// The measure is currently invalid so there's no point trying to bring the
// current char into view until a measure has been carried out as the scroll
// viewer extents may not be up-to-date.
Dispatcher.UIThread.InvokeAsync(
() =>
{
var rect = FormattedText.HitTestTextPosition(caretIndex);
this.BringIntoView(rect);
},
DispatcherPriority.Normal);
}
}
}
protected override FormattedText CreateFormattedText(Size constraint)
{
var result = base.CreateFormattedText(constraint);
var selectionStart = SelectionStart;
var selectionEnd = SelectionEnd;
var start = Math.Min(selectionStart, selectionEnd);
var length = Math.Max(selectionStart, selectionEnd) - start;
if (length > 0)
{
result.Spans = new[]
{
new FormattedTextStyleSpan(start, length, foregroundBrush: Brushes.White),
};
}
return result;
}
protected override Size MeasureOverride(Size availableSize)
{
var text = Text;
if (!string.IsNullOrEmpty(text))
{
return base.MeasureOverride(availableSize);
}
else
{
return new FormattedText
{
Text = "X",
Typeface = new Typeface(FontFamily, FontSize, FontStyle, FontWeight),
TextAlignment = TextAlignment,
Constraint = availableSize,
}.Measure();
}
}
private int CoerceCaretIndex(int value)
{
var text = Text;
var length = text?.Length ?? 0;
return Math.Max(0, Math.Min(length, value));
}
private void CaretTimerTick(object sender, EventArgs e)
{
_caretBlink = !_caretBlink;
InvalidateVisual();
}
}
}
| |
using System;
using FarseerGames.FarseerPhysics.Mathematics;
#if (XNA)
using Microsoft.Xna.Framework;
#endif
namespace FarseerGames.FarseerPhysics.Dynamics.Joints
{
/// <summary>
/// Slider joint is just like pin joint, but the distance between the bodies are not fixed.
/// The bodies can move towards or away from each other within limits.
/// </summary>
public class SliderJoint : Joint
{
public event JointDelegate JointUpdated;
private float _accumulatedImpulse;
private Vector2 _anchor;
private Vector2 _anchor1;
private Vector2 _anchor2;
private Body _body1;
private Body _body2;
private float _effectiveMass;
private bool _lowerLimitViolated;
private float _max;
private float _min;
private Vector2 _r1;
private Vector2 _r2;
private float _slop = .01f;
private bool _upperLimitViolated;
private float _velocityBias;
private Vector2 _worldAnchor1;
private Vector2 _worldAnchor2;
private Vector2 _worldAnchorDifferenceNormalized;
public SliderJoint()
{
}
public SliderJoint(Body body1, Vector2 anchor1, Body body2, Vector2 anchor2, float min, float max)
{
_body1 = body1;
_body2 = body2;
_anchor1 = anchor1;
_anchor2 = anchor2;
_min = min;
_max = max;
//initialize the world anchors (only needed to give valid values to the WorldAnchor properties)
Anchor1 = anchor1;
Anchor2 = anchor2;
}
/// <summary>
/// Gets or sets the first body.
/// </summary>
/// <Value>The body1.</Value>
public Body Body1
{
get { return _body1; }
set { _body1 = value; }
}
/// <summary>
/// Gets or sets the second body.
/// </summary>
/// <Value>The body2.</Value>
public Body Body2
{
get { return _body2; }
set { _body2 = value; }
}
/// <summary>
/// Gets or sets the slop.
/// </summary>
/// <Value>The slop.</Value>
public float Slop
{
get { return _slop; }
set { _slop = value; }
}
/// <summary>
/// Gets or sets the min.
/// </summary>
/// <Value>The min.</Value>
public float Min
{
get { return _min; }
set { _min = value; }
}
/// <summary>
/// Gets or sets the max.
/// </summary>
/// <Value>The max.</Value>
public float Max
{
get { return _max; }
set { _max = value; }
}
/// <summary>
/// Gets or sets the first anchor.
/// </summary>
/// <Value>The anchor1.</Value>
public Vector2 Anchor1
{
get { return _anchor1; }
set
{
_anchor1 = value;
_body1.GetBodyMatrix(out _body1MatrixTemp);
Vector2.TransformNormal(ref _anchor1, ref _body1MatrixTemp, out _r1);
Vector2.Add(ref _body1.position, ref _r1, out _worldAnchor1);
}
}
/// <summary>
/// Gets or sets the second anchor.
/// </summary>
/// <Value>The anchor2.</Value>
public Vector2 Anchor2
{
get { return _anchor2; }
set
{
_anchor2 = value;
_body2.GetBodyMatrix(out _body2MatrixTemp);
Vector2.TransformNormal(ref _anchor2, ref _body2MatrixTemp, out _r2);
Vector2.Add(ref _body2.position, ref _r2, out _worldAnchor2);
}
}
/// <summary>
/// Gets the first world anchor.
/// </summary>
/// <Value>The world anchor1.</Value>
public Vector2 WorldAnchor1
{
get { return _worldAnchor1; }
}
/// <summary>
/// Gets the second world anchor.
/// </summary>
/// <Value>The world anchor2.</Value>
public Vector2 WorldAnchor2
{
get { return _worldAnchor2; }
}
/// <summary>
/// Gets the current anchor position.
/// </summary>
/// <Value>The current anchor position.</Value>
public Vector2 CurrentAnchorPosition
{
get
{
Vector2.Add(ref _body1.position, ref _r1, out _anchor); //_anchor moves once simulator starts
return _anchor;
}
}
public override void Validate()
{
if (_body1.IsDisposed || _body2.IsDisposed)
{
Dispose();
}
}
public override void PreStep(float inverseDt)
{
if (_body1.isStatic && _body2.isStatic)
return;
if (!_body1.Enabled && !_body2.Enabled)
return;
//calc _r1 and _r2 from the anchors
_body1.GetBodyMatrix(out _body1MatrixTemp);
_body2.GetBodyMatrix(out _body2MatrixTemp);
Vector2.TransformNormal(ref _anchor1, ref _body1MatrixTemp, out _r1);
Vector2.TransformNormal(ref _anchor2, ref _body2MatrixTemp, out _r2);
//calc the diff between _anchor positions
Vector2.Add(ref _body1.position, ref _r1, out _worldAnchor1);
Vector2.Add(ref _body2.position, ref _r2, out _worldAnchor2);
Vector2.Subtract(ref _worldAnchor2, ref _worldAnchor1, out _worldAnchorDifference);
_distance = _worldAnchorDifference.Length();
JointError = 0;
if (_distance > _max)
{
if (_lowerLimitViolated)
{
_accumulatedImpulse = 0;
_lowerLimitViolated = false;
}
_upperLimitViolated = true;
if (_distance < _max + _slop)
{
JointError = 0; //allow some _slop
}
else
{
JointError = _distance - _max;
}
}
else if (_distance < _min)
{
if (_upperLimitViolated)
{
_accumulatedImpulse = 0;
_upperLimitViolated = false;
}
_lowerLimitViolated = true;
if (_distance > _min - _slop)
{
JointError = 0;
}
else
{
JointError = _distance - _min;
}
}
else
{
_upperLimitViolated = false;
_lowerLimitViolated = false;
JointError = 0;
_accumulatedImpulse = 0;
}
//normalize the difference vector
Vector2.Multiply(ref _worldAnchorDifference, 1 / (_distance != 0 ? _distance : float.PositiveInfinity),
out _worldAnchorDifferenceNormalized); //_distance = 0 --> error (fix)
//calc velocity bias
_velocityBias = BiasFactor * inverseDt * (JointError);
//calc mass normal (effective mass in relation to constraint)
Calculator.Cross(ref _r1, ref _worldAnchorDifferenceNormalized, out _r1cn);
Calculator.Cross(ref _r2, ref _worldAnchorDifferenceNormalized, out _r2cn);
_kNormal = _body1.inverseMass + _body2.inverseMass + _body1.inverseMomentOfInertia * _r1cn * _r1cn +
_body2.inverseMomentOfInertia * _r2cn * _r2cn;
_effectiveMass = (1) / (_kNormal + Softness);
//convert scalar accumulated _impulse to vector
Vector2.Multiply(ref _worldAnchorDifferenceNormalized, _accumulatedImpulse, out _accumulatedImpulseVector);
//apply accumulated impulses (warm starting)
_body2.ApplyImmediateImpulse(ref _accumulatedImpulseVector);
Calculator.Cross(ref _r2, ref _accumulatedImpulseVector, out _angularImpulse);
_body2.ApplyAngularImpulse(_angularImpulse);
Vector2.Multiply(ref _accumulatedImpulseVector, -1, out _accumulatedImpulseVector);
_body1.ApplyImmediateImpulse(ref _accumulatedImpulseVector);
Calculator.Cross(ref _r1, ref _accumulatedImpulseVector, out _angularImpulse);
_body1.ApplyAngularImpulse(_angularImpulse);
}
public override void Update()
{
base.Update();
if (_body1.isStatic && _body2.isStatic)
return;
if (!_body1.Enabled && !_body2.Enabled)
return;
if (!_upperLimitViolated && !_lowerLimitViolated)
return;
//calc velocity anchor points (angular component + linear)
Calculator.Cross(ref _body1.AngularVelocity, ref _r1, out _angularVelocityComponent1);
Vector2.Add(ref _body1.LinearVelocity, ref _angularVelocityComponent1, out _velocity1);
Calculator.Cross(ref _body2.AngularVelocity, ref _r2, out _angularVelocityComponent2);
Vector2.Add(ref _body2.LinearVelocity, ref _angularVelocityComponent2, out _velocity2);
//calc velocity difference
Vector2.Subtract(ref _velocity2, ref _velocity1, out _dv);
//map the velocity difference into constraint space
Vector2.Dot(ref _dv, ref _worldAnchorDifferenceNormalized, out _dvNormal);
//calc the impulse magnitude
_impulseMagnitude = (-_velocityBias - _dvNormal - Softness * _accumulatedImpulse) * _effectiveMass;
//Note: softness not implemented correctly yet
float oldAccumulatedImpulse = _accumulatedImpulse;
if (_upperLimitViolated)
{
_accumulatedImpulse = Math.Min(oldAccumulatedImpulse + _impulseMagnitude, 0);
}
else if (_lowerLimitViolated)
{
_accumulatedImpulse = Math.Max(oldAccumulatedImpulse + _impulseMagnitude, 0);
}
_impulseMagnitude = _accumulatedImpulse - oldAccumulatedImpulse;
//convert scalar impulse to vector
Vector2.Multiply(ref _worldAnchorDifferenceNormalized, _impulseMagnitude, out _impulse);
if (_impulse != Vector2.Zero)
{
//apply impulse
_body2.ApplyImmediateImpulse(ref _impulse);
Calculator.Cross(ref _r2, ref _impulse, out _angularImpulse);
_body2.ApplyAngularImpulse(_angularImpulse);
Vector2.Multiply(ref _impulse, -1, out _impulse);
_body1.ApplyImmediateImpulse(ref _impulse);
Calculator.Cross(ref _r1, ref _impulse, out _angularImpulse);
_body1.ApplyAngularImpulse(_angularImpulse);
if (JointUpdated != null)
JointUpdated(this, _body1, _body2);
}
}
#region Update variables
private Vector2 _angularVelocityComponent1;
private Vector2 _angularVelocityComponent2;
private Vector2 _dv;
private float _dvNormal;
private Vector2 _impulse;
private float _impulseMagnitude;
private Vector2 _velocity1;
private Vector2 _velocity2;
#endregion
#region PreStep variables
private Vector2 _accumulatedImpulseVector;
private float _angularImpulse;
private Matrix _body1MatrixTemp;
private Matrix _body2MatrixTemp;
private float _distance;
private float _kNormal;
private float _r1cn;
private float _r2cn;
private Vector2 _worldAnchorDifference;
#endregion
}
}
| |
using System;
using System.Linq.Expressions;
using StructureMap.Building.Interception;
using StructureMap.Graph;
using StructureMap.Pipeline;
namespace StructureMap.Configuration.DSL.Expressions
{
/// <summary>
/// Expression Builder that has grammars for defining policies at the
/// PluginType level. This expression is used for registering
/// open generic types
/// </summary>
public class GenericFamilyExpression
{
private readonly Type _pluginType;
private readonly Registry _registry;
public GenericFamilyExpression(Type pluginType, ILifecycle scope, Registry registry)
{
_pluginType = pluginType;
_registry = registry;
alterAndContinue(f => { });
if (scope != null)
{
alterAndContinue(family => family.SetLifecycleTo(scope));
}
}
private GenericFamilyExpression alterAndContinue(Action<PluginFamily> action)
{
_registry.alter = graph => {
var family = graph.FindExistingOrCreateFamily(_pluginType);
action(family);
};
return this;
}
/// <summary>
/// Use this configured Instance as is
/// </summary>
/// <param name="instance"></param>
public void Use(Instance instance)
{
alterAndContinue(family => family.SetDefault(instance));
}
/// <summary>
/// Convenience method that sets the default concrete type of the PluginType. The "concreteType"
/// can only accept types that do not have any primitive constructor arguments.
/// StructureMap has to know how to construct all of the constructor argument types.
/// </summary>
/// <param name="concreteType"></param>
/// <returns></returns>
public ConfiguredInstance Use(Type concreteType)
{
var instance = new ConfiguredInstance(concreteType);
Use(instance);
return instance;
}
/// <summary>
/// Specify the "on missing named instance" configuration for this
/// PluginType
/// </summary>
/// <param name="instance"></param>
/// <returns></returns>
public GenericFamilyExpression MissingNamedInstanceIs(Instance instance)
{
alterAndContinue(family => family.MissingInstance = instance);
return this;
}
/// <summary>
/// Register an Instance constructed by a Lambda Expression using IContext
/// </summary>
/// <param name="func"></param>
/// <returns></returns>
public LambdaInstance<object> Use(Expression<Func<IContext, object>> func)
{
var instance = new LambdaInstance<object>(func);
Use(instance);
return instance;
}
/// <summary>
/// Register an Instance constructed by a Func that uses IContex
/// </summary>
/// <param name="description">User friendly diagnostic description</param>
/// <param name="func"></param>
/// <returns></returns>
public LambdaInstance<object> Use(string description, Func<IContext, object> func)
{
var instance = new LambdaInstance<object>(description, func);
Use(instance);
return instance;
}
/// <summary>
/// Adds an additional Instance constructed by a Lambda Expression using IContext
/// </summary>
/// <param name="func"></param>
/// <returns></returns>
public LambdaInstance<object> Add(Expression<Func<IContext, object>> func)
{
var instance = new LambdaInstance<object>(func);
Add(instance);
return instance;
}
/// <summary>
/// Adds an additional Instance constructed by a Func using IContext
/// </summary>
/// <param name="description">User friendly description for diagnostic purposes</param>
/// <param name="func"></param>
/// <returns></returns>
public LambdaInstance<object> Add(string description, Func<IContext, object> func)
{
var instance = new LambdaInstance<object>(description, func);
Add(instance);
return instance;
}
/// <summary>
/// Shortcut to add a value by type
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public ObjectInstance Use(object value)
{
var instance = new ObjectInstance(value);
Use(instance);
return instance;
}
/// <summary>
/// Makes a previously registered Instance with the name 'instanceKey'
/// the default Instance for this PluginType
/// </summary>
/// <param name="instanceKey"></param>
/// <returns></returns>
public ReferencedInstance Use(string instanceKey)
{
var instance = new ReferencedInstance(instanceKey);
Use(instance);
return instance;
}
/// <summary>
/// Shortcut method to add an additional Instance to this Plugin Type
/// as just a Concrete Type. This will only work if the Concrete Type
/// has no primitive constructor or mandatory Setter arguments.
/// </summary>
/// <param name="concreteType"></param>
/// <returns></returns>
public ConfiguredInstance Add(Type concreteType)
{
var instance = new ConfiguredInstance(concreteType);
alterAndContinue(family => family.AddInstance(instance));
return instance;
}
/// <summary>
/// Adds an additional Instance against this PluginType
/// </summary>
/// <param name="instance"></param>
/// <returns></returns>
public GenericFamilyExpression Add(Instance instance)
{
return alterAndContinue(family => family.AddInstance(instance));
}
/// <summary>
/// Configure this type as the supplied value
/// </summary>
/// <returns></returns>
public ObjectInstance Add(object @object)
{
var instance = new ObjectInstance(@object);
Add(instance);
return instance;
}
/// <summary>
/// Registers an IBuildInterceptor for this Plugin Type that executes before
/// any object of this PluginType is created. IBuildInterceptor's can be
/// used to create a custom scope
/// </summary>
/// <param name="lifecycle"></param>
/// <returns></returns>
public GenericFamilyExpression LifecycleIs(ILifecycle lifecycle)
{
return alterAndContinue(family => family.SetLifecycleTo(lifecycle));
}
/// <summary>
/// Convenience method to mark a PluginFamily as a Singleton
/// </summary>
/// <returns></returns>
public GenericFamilyExpression Singleton()
{
return LifecycleIs(Lifecycles.Singleton);
}
/// <summary>
/// Applies a decorator type to all Instances that return a type that can be cast to this PluginType
/// </summary>
/// <param name="decoratorType"></param>
/// <param name="filter"></param>
/// <returns></returns>
public ConfiguredInstance DecorateAllWith(Type decoratorType, Func<Instance, bool> filter = null)
{
var instance = new ConfiguredInstance(decoratorType);
var policy = new DecoratorPolicy(_pluginType, instance, filter);
_registry.alter = graph => graph.Policies.Interceptors.Add(policy);
return instance;
}
}
}
| |
#region Apache License
//
// 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.
//
#endregion
// MONO 1.0 has no support for Win32 Error APIs
#if !MONO
// SSCLI 1.0 has no support for Win32 Error APIs
#if !SSCLI
// We don't want framework or platform specific code in the CLI version of Ctrip
#if !CLI_1_0
using System;
using System.Globalization;
using System.Runtime.InteropServices;
namespace Ctrip.Util
{
/// <summary>
/// Represents a native error code and message.
/// </summary>
/// <remarks>
/// <para>
/// Represents a Win32 platform native error.
/// </para>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
public sealed class NativeError
{
#region Protected Instance Constructors
/// <summary>
/// Create an instance of the <see cref="NativeError" /> class with the specified
/// error number and message.
/// </summary>
/// <param name="number">The number of the native error.</param>
/// <param name="message">The message of the native error.</param>
/// <remarks>
/// <para>
/// Create an instance of the <see cref="NativeError" /> class with the specified
/// error number and message.
/// </para>
/// </remarks>
private NativeError(int number, string message)
{
m_number = number;
m_message = message;
}
#endregion // Protected Instance Constructors
#region Public Instance Properties
/// <summary>
/// Gets the number of the native error.
/// </summary>
/// <value>
/// The number of the native error.
/// </value>
/// <remarks>
/// <para>
/// Gets the number of the native error.
/// </para>
/// </remarks>
public int Number
{
get { return m_number; }
}
/// <summary>
/// Gets the message of the native error.
/// </summary>
/// <value>
/// The message of the native error.
/// </value>
/// <remarks>
/// <para>
/// </para>
/// Gets the message of the native error.
/// </remarks>
public string Message
{
get { return m_message; }
}
#endregion // Public Instance Properties
#region Public Static Methods
/// <summary>
/// Create a new instance of the <see cref="NativeError" /> class for the last Windows error.
/// </summary>
/// <returns>
/// An instance of the <see cref="NativeError" /> class for the last windows error.
/// </returns>
/// <remarks>
/// <para>
/// The message for the <see cref="Marshal.GetLastWin32Error"/> error number is lookup up using the
/// native Win32 <c>FormatMessage</c> function.
/// </para>
/// </remarks>
#if NET_4_0
[System.Security.SecuritySafeCritical]
#elif !NETCF
[System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode=true)]
#endif
public static NativeError GetLastError()
{
int number = Marshal.GetLastWin32Error();
return new NativeError(number, NativeError.GetErrorMessage(number));
}
/// <summary>
/// Create a new instance of the <see cref="NativeError" /> class.
/// </summary>
/// <param name="number">the error number for the native error</param>
/// <returns>
/// An instance of the <see cref="NativeError" /> class for the specified
/// error number.
/// </returns>
/// <remarks>
/// <para>
/// The message for the specified error number is lookup up using the
/// native Win32 <c>FormatMessage</c> function.
/// </para>
/// </remarks>
public static NativeError GetError(int number)
{
return new NativeError(number, NativeError.GetErrorMessage(number));
}
/// <summary>
/// Retrieves the message corresponding with a Win32 message identifier.
/// </summary>
/// <param name="messageId">Message identifier for the requested message.</param>
/// <returns>
/// The message corresponding with the specified message identifier.
/// </returns>
/// <remarks>
/// <para>
/// The message will be searched for in system message-table resource(s)
/// using the native <c>FormatMessage</c> function.
/// </para>
/// </remarks>
#if NET_4_0
[System.Security.SecuritySafeCritical]
#elif !NETCF
[System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode = true)]
#endif
public static string GetErrorMessage(int messageId)
{
// Win32 constants
int FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100; // The function should allocates a buffer large enough to hold the formatted message
int FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200; // Insert sequences in the message definition are to be ignored
int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000; // The function should search the system message-table resource(s) for the requested message
string msgBuf = ""; // buffer that will receive the message
IntPtr sourcePtr = new IntPtr(); // Location of the message definition, will be ignored
IntPtr argumentsPtr = new IntPtr(); // Pointer to array of values to insert, not supported as it requires unsafe code
if (messageId != 0)
{
// If the function succeeds, the return value is the number of TCHARs stored in the output buffer, excluding the terminating null character
int messageSize = FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
ref sourcePtr,
messageId,
0,
ref msgBuf,
255,
argumentsPtr);
if (messageSize > 0)
{
// Remove trailing null-terminating characters (\r\n) from the message
msgBuf = msgBuf.TrimEnd(new char[] {'\r', '\n'});
}
else
{
// A message could not be located.
msgBuf = null;
}
}
else
{
msgBuf = null;
}
return msgBuf;
}
#endregion // Public Static Methods
#region Override Object Implementation
/// <summary>
/// Return error information string
/// </summary>
/// <returns>error information string</returns>
/// <remarks>
/// <para>
/// Return error information string
/// </para>
/// </remarks>
public override string ToString()
{
return string.Format(CultureInfo.InvariantCulture, "0x{0:x8}", this.Number) + (this.Message != null ? ": " + this.Message : "");
}
#endregion // Override Object Implementation
#region Stubs For Native Function Calls
/// <summary>
/// Formats a message string.
/// </summary>
/// <param name="dwFlags">Formatting options, and how to interpret the <paramref name="lpSource" /> parameter.</param>
/// <param name="lpSource">Location of the message definition.</param>
/// <param name="dwMessageId">Message identifier for the requested message.</param>
/// <param name="dwLanguageId">Language identifier for the requested message.</param>
/// <param name="lpBuffer">If <paramref name="dwFlags" /> includes FORMAT_MESSAGE_ALLOCATE_BUFFER, the function allocates a buffer using the <c>LocalAlloc</c> function, and places the pointer to the buffer at the address specified in <paramref name="lpBuffer" />.</param>
/// <param name="nSize">If the FORMAT_MESSAGE_ALLOCATE_BUFFER flag is not set, this parameter specifies the maximum number of TCHARs that can be stored in the output buffer. If FORMAT_MESSAGE_ALLOCATE_BUFFER is set, this parameter specifies the minimum number of TCHARs to allocate for an output buffer.</param>
/// <param name="Arguments">Pointer to an array of values that are used as insert values in the formatted message.</param>
/// <remarks>
/// <para>
/// The function requires a message definition as input. The message definition can come from a
/// buffer passed into the function. It can come from a message table resource in an
/// already-loaded module. Or the caller can ask the function to search the system's message
/// table resource(s) for the message definition. The function finds the message definition
/// in a message table resource based on a message identifier and a language identifier.
/// The function copies the formatted message text to an output buffer, processing any embedded
/// insert sequences if requested.
/// </para>
/// <para>
/// To prevent the usage of unsafe code, this stub does not support inserting values in the formatted message.
/// </para>
/// </remarks>
/// <returns>
/// <para>
/// If the function succeeds, the return value is the number of TCHARs stored in the output
/// buffer, excluding the terminating null character.
/// </para>
/// <para>
/// If the function fails, the return value is zero. To get extended error information,
/// call <see cref="M:Marshal.GetLastWin32Error()" />.
/// </para>
/// </returns>
#if NETCF
[DllImport("CoreDll.dll", SetLastError=true, CharSet=CharSet.Unicode)]
#else
[DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)]
#endif
private static extern int FormatMessage(
int dwFlags,
ref IntPtr lpSource,
int dwMessageId,
int dwLanguageId,
ref String lpBuffer,
int nSize,
IntPtr Arguments);
#endregion // Stubs For Native Function Calls
#region Private Instance Fields
private int m_number;
private string m_message;
#endregion
}
}
#endif // !CLI_1_0
#endif // !SSCLI
#endif // !MONO
| |
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Collections;
namespace Hydra.Framework.Geometric
{
public class Handle
{
#region Private members of the Graphic handles
private int handlesize = 8;
private Color normalcolor = Color.White;
private Color disabledcolor=Color.Gray;
private MapObjectArgs c1=null;
private Label[] lbl;
private int startl;
private int startt;
private int startw;
private int starth;
private int startx;
private int starty;
private bool dragging;
#endregion
#region Constructors for graphic handles
public Handle()
{
}
#endregion
#region Methods of graphic handles
//
// Connect a Click event handler to the passed Control
// that attaches a graphic handle to the graphic item when
// it is clicked
//
public void GetHandles(IMapviewObject g)
{
// PointF[] v=new PointF(g.Vertices.Length);
// for (int i=0; i<g.Vertices.Length; i++)
// {
// v[i]=new PointF(g.Vertices[i].X,g.Vertices[i].Y);
// }
// int cnt=v.Length;
// Label[] lbl = new Label[cnt];
// for (int i = 0; i<cnt; i++)
// {
// lbl[i] = new System.Windows.Forms.Label();
// lbl[i].TabIndex = i;
// lbl[i].FlatStyle = 0 ;
// lbl[i].BorderStyle = BorderStyle.FixedSingle;
// lbl[i].BackColor = normalcolor;
// lbl[i].Left=200-i; //; (int)v[i].X-handlesize/2;
// lbl[i].Top=200 + i; //(int)v[i].Y-handlesize/2;
// lbl[i].Text = "";
// lbl[i].BringToFront();
// lbl[i].Visible=true;
// // lbl[i].MouseDown += new MouseEventHandler(this.lbl_MouseDown);
// // lbl[i].MouseMove += new MouseEventHandler(this.lbl_MouseMove);
// // lbl[i].MouseUp += new MouseEventHandler(this.lbl_MouseUp);
// }
// //Position sizing handles around Control
// MoveHandles();
//
// //Display sizing handles
// ShowHandles();
//o.GraphicSelected+= new GraphicEvents(this.CreateHandles);
}
//
// Attaches a graphic handle to the selected graphic item
//
private void CreateHandles(IMapviewObject g)
{
PointF[] v=g.Vertices;
for (int i = 0; i<v.Length; i++)
{
lbl[i] = new Label();
lbl[i].TabIndex = i;
lbl[i].FlatStyle = 0 ;
lbl[i].BorderStyle = BorderStyle.FixedSingle;
lbl[i].BackColor = normalcolor;
lbl[i].Left=(int)v[i].X-handlesize/2;
lbl[i].Top=(int)v[i].Y-handlesize/2;
lbl[i].Text = "";
lbl[i].BringToFront();
lbl[i].Visible=true;
// lbl[i].MouseDown += new MouseEventHandler(this.lbl_MouseDown);
// lbl[i].MouseMove += new MouseEventHandler(this.lbl_MouseMove);
// lbl[i].MouseUp += new MouseEventHandler(this.lbl_MouseUp);
}
//Position sizing handles around Control
MoveHandles();
//Display sizing handles
ShowHandles();
}
public void Remove()
{
HideHandles();
// m_control.Cursor = oldCursor;
}
public void MoveHandles()
{
}
private void ShowHandles()
{
if (c1!=null)
{
for (int i = 0; i<8; i++)
{
lbl[i].Visible = true;
}
}
}
private void HideHandles()
{
for (int i = 0; i<8; i++)
{
lbl[i].Visible = false;
}
}
/////////////////////////////////////////////////////////////////
// MOUSE EVENTS THAT IMPLEMENT SIZING OF THE PICKED CONTROL
/////////////////////////////////////////////////////////////////
//
// Store control position and size when mouse button pushed over
// any sizing handle
//
private void lbl_MouseDown(object sender, MouseEventArgs e)
{
dragging = true;
// startl = m_control.Left;
// startt = m_control.Top;
// startw = m_control.Width;
// starth = m_control.Height;
HideHandles();
}
//
// Size the picked control in accordance with sizing handle being dragged
// 0 1 2
// 7 3
// 6 5 4
//
private void lbl_MouseMove(object sender, MouseEventArgs e)
{
// int l = m_control.Left;
// int w = m_control.Width;
// int t = m_control.Top;
// int h = m_control.Height;
// if (dragging)
// {
// switch (((Label)sender).TabIndex)
// {
// case 0: // Dragging top-left sizing box
// l = startl + e.X < startl + startw - MIN_SIZE ? startl + e.X : startl + startw - MIN_SIZE;
// t = startt + e.Y < startt + starth - MIN_SIZE ? startt + e.Y : startt + starth - MIN_SIZE;
// w = startl + startw - m_control.Left;
// h = startt + starth - m_control.Top;
// break;
// case 1: // Dragging top-center sizing box
// t = startt + e.Y < startt + starth - MIN_SIZE ? startt + e.Y : startt + starth - MIN_SIZE;
// h = startt + starth - m_control.Top;
// break;
// case 2: // Dragging top-right sizing box
// w = startw + e.X > MIN_SIZE ? startw + e.X : MIN_SIZE;
// t = startt + e.Y < startt + starth - MIN_SIZE ? startt + e.Y : startt + starth - MIN_SIZE;
// h = startt + starth - m_control.Top;
// break;
// case 3: // Dragging right-middle sizing box
// w = startw + e.X > MIN_SIZE ? startw + e.X : MIN_SIZE;
// break;
// case 4: // Dragging right-bottom sizing box
// w = startw + e.X > MIN_SIZE ? startw + e.X : MIN_SIZE;
// h = starth + e.Y > MIN_SIZE ? starth + e.Y : MIN_SIZE;
// break;
// case 5: // Dragging center-bottom sizing box
// h = starth + e.Y > MIN_SIZE ? starth + e.Y : MIN_SIZE;
// break;
// case 6: // Dragging left-bottom sizing box
// l = startl + e.X < startl + startw - MIN_SIZE ? startl + e.X : startl + startw - MIN_SIZE;
// w = startl + startw - m_control.Left;
// h = starth + e.Y > MIN_SIZE ? starth + e.Y : MIN_SIZE;
// break;
// case 7: // Dragging left-middle sizing box
// l = startl + e.X < startl + startw - MIN_SIZE ? startl + e.X : startl + startw - MIN_SIZE;
// w = startl + startw - m_control.Left;
// break;
// }
// l =(l<0)?0:l;
// t =(t<0)?0:t;
// m_control.SetBounds(l,t,w,h);
// }
}
//
// Display sizing handles around picked control once sizing has completed
//
private void lbl_MouseUp(object sender, MouseEventArgs e)
{
dragging = false;
MoveHandles();
ShowHandles();
}
#endregion
}
}
| |
using Lucene.Net.Util;
using System;
using System.Text;
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 Analyzer = Lucene.Net.Analysis.Analyzer;
using Codec = Lucene.Net.Codecs.Codec;
using IndexingChain = Lucene.Net.Index.DocumentsWriterPerThread.IndexingChain;
using IndexReaderWarmer = Lucene.Net.Index.IndexWriter.IndexReaderWarmer;
using IndexSearcher = Lucene.Net.Search.IndexSearcher;
using InfoStream = Lucene.Net.Util.InfoStream;
using Similarity = Lucene.Net.Search.Similarities.Similarity;
/// <summary>
/// Holds all the configuration used by <see cref="IndexWriter"/> with few setters for
/// settings that can be changed on an <see cref="IndexWriter"/> instance "live".
///
/// @since 4.0
/// </summary>
#if FEATURE_SERIALIZABLE
[Serializable]
#endif
public class LiveIndexWriterConfig
{
private readonly Analyzer analyzer;
private volatile int maxBufferedDocs;
private double ramBufferSizeMB;
private volatile int maxBufferedDeleteTerms;
private volatile int readerTermsIndexDivisor;
private volatile IndexReaderWarmer mergedSegmentWarmer;
private volatile int termIndexInterval; // TODO: this should be private to the codec, not settable here
// LUCENENET specific: Volatile fields are not CLS compliant,
// so we are making them internal. This class cannot be inherited
// from outside of the assembly anyway, since it has no public
// constructors, so protected members are moot.
// modified by IndexWriterConfig
/// <summary>
/// <see cref="Index.IndexDeletionPolicy"/> controlling when commit
/// points are deleted.
/// </summary>
internal volatile IndexDeletionPolicy delPolicy;
/// <summary>
/// <see cref="Index.IndexCommit"/> that <see cref="IndexWriter"/> is
/// opened on.
/// </summary>
internal volatile IndexCommit commit;
/// <summary>
/// <see cref="Index.OpenMode"/> that <see cref="IndexWriter"/> is opened
/// with.
/// </summary>
internal volatile OpenMode openMode;
/// <summary>
/// <see cref="Search.Similarities.Similarity"/> to use when encoding norms. </summary>
internal volatile Similarity similarity;
/// <summary>
/// <see cref="IMergeScheduler"/> to use for running merges. </summary>
internal volatile IMergeScheduler mergeScheduler;
/// <summary>
/// Timeout when trying to obtain the write lock on init. </summary>
internal long writeLockTimeout;
/// <summary>
/// <see cref="DocumentsWriterPerThread.IndexingChain"/> that determines how documents are
/// indexed.
/// </summary>
internal volatile IndexingChain indexingChain; // LUCENENET specific - made internal because IndexingChain is internal
/// <summary>
/// <see cref="Codecs.Codec"/> used to write new segments. </summary>
internal volatile Codec codec;
/// <summary>
/// <see cref="Util.InfoStream"/> for debugging messages. </summary>
internal volatile InfoStream infoStream;
/// <summary>
/// <see cref="Index.MergePolicy"/> for selecting merges. </summary>
internal volatile MergePolicy mergePolicy;
/// <summary>
/// <see cref="DocumentsWriterPerThreadPool"/> to control how
/// threads are allocated to <see cref="DocumentsWriterPerThread"/>.
/// </summary>
internal volatile DocumentsWriterPerThreadPool indexerThreadPool; // LUCENENET specific - made internal because DocumentsWriterPerThreadPool is internal
/// <summary>
/// True if readers should be pooled. </summary>
internal volatile bool readerPooling;
/// <summary>
/// <see cref="Index.FlushPolicy"/> to control when segments are
/// flushed.
/// </summary>
internal volatile FlushPolicy flushPolicy; // LUCENENET specific - made internal because FlushPolicy is internal
/// <summary>
/// Sets the hard upper bound on RAM usage for a single
/// segment, after which the segment is forced to flush.
/// </summary>
internal volatile int perThreadHardLimitMB;
/// <summary>
/// <see cref="LuceneVersion"/> that <see cref="IndexWriter"/> should emulate. </summary>
internal readonly LuceneVersion matchVersion;
/// <summary>
/// True if segment flushes should use compound file format </summary>
internal volatile bool useCompoundFile = IndexWriterConfig.DEFAULT_USE_COMPOUND_FILE_SYSTEM;
/// <summary>
/// True if merging should check integrity of segments before merge </summary>
internal volatile bool checkIntegrityAtMerge = IndexWriterConfig.DEFAULT_CHECK_INTEGRITY_AT_MERGE;
// used by IndexWriterConfig
internal LiveIndexWriterConfig(Analyzer analyzer, LuceneVersion matchVersion)
{
this.analyzer = analyzer;
this.matchVersion = matchVersion;
ramBufferSizeMB = IndexWriterConfig.DEFAULT_RAM_BUFFER_SIZE_MB;
maxBufferedDocs = IndexWriterConfig.DEFAULT_MAX_BUFFERED_DOCS;
maxBufferedDeleteTerms = IndexWriterConfig.DEFAULT_MAX_BUFFERED_DELETE_TERMS;
readerTermsIndexDivisor = IndexWriterConfig.DEFAULT_READER_TERMS_INDEX_DIVISOR;
mergedSegmentWarmer = null;
termIndexInterval = IndexWriterConfig.DEFAULT_TERM_INDEX_INTERVAL; // TODO: this should be private to the codec, not settable here
delPolicy = new KeepOnlyLastCommitDeletionPolicy();
commit = null;
useCompoundFile = IndexWriterConfig.DEFAULT_USE_COMPOUND_FILE_SYSTEM;
openMode = Index.OpenMode.CREATE_OR_APPEND;
similarity = IndexSearcher.DefaultSimilarity;
#if !FEATURE_CONCURRENTMERGESCHEDULER
mergeScheduler = new TaskMergeScheduler();
#else
mergeScheduler = new ConcurrentMergeScheduler();
#endif
writeLockTimeout = IndexWriterConfig.WRITE_LOCK_TIMEOUT;
indexingChain = DocumentsWriterPerThread.DefaultIndexingChain;
codec = Codec.Default;
if (codec == null)
{
throw new System.NullReferenceException();
}
infoStream = Util.InfoStream.Default;
mergePolicy = new TieredMergePolicy();
flushPolicy = new FlushByRamOrCountsPolicy();
readerPooling = IndexWriterConfig.DEFAULT_READER_POOLING;
indexerThreadPool = new ThreadAffinityDocumentsWriterThreadPool(IndexWriterConfig.DEFAULT_MAX_THREAD_STATES);
perThreadHardLimitMB = IndexWriterConfig.DEFAULT_RAM_PER_THREAD_HARD_LIMIT_MB;
}
/// <summary>
/// Creates a new config that that handles the live <see cref="IndexWriter"/>
/// settings.
/// </summary>
internal LiveIndexWriterConfig(IndexWriterConfig config)
{
maxBufferedDeleteTerms = config.MaxBufferedDeleteTerms;
maxBufferedDocs = config.MaxBufferedDocs;
mergedSegmentWarmer = config.MergedSegmentWarmer;
ramBufferSizeMB = config.RAMBufferSizeMB;
readerTermsIndexDivisor = config.ReaderTermsIndexDivisor;
termIndexInterval = config.TermIndexInterval;
matchVersion = config.matchVersion;
analyzer = config.Analyzer;
delPolicy = config.IndexDeletionPolicy;
commit = config.IndexCommit;
openMode = config.OpenMode;
similarity = config.Similarity;
mergeScheduler = config.MergeScheduler;
writeLockTimeout = config.WriteLockTimeout;
indexingChain = config.IndexingChain;
codec = config.Codec;
infoStream = config.InfoStream;
mergePolicy = config.MergePolicy;
indexerThreadPool = config.IndexerThreadPool;
readerPooling = config.UseReaderPooling;
flushPolicy = config.FlushPolicy;
perThreadHardLimitMB = config.RAMPerThreadHardLimitMB;
useCompoundFile = config.UseCompoundFile;
checkIntegrityAtMerge = config.CheckIntegrityAtMerge;
}
/// <summary>
/// Gets the default analyzer to use for indexing documents. </summary>
public virtual Analyzer Analyzer
{
get
{
return analyzer;
}
}
/// <summary>
/// Expert: Gets or sets the interval between indexed terms. Large values cause less
/// memory to be used by <see cref="IndexReader"/>, but slow random-access to terms. Small
/// values cause more memory to be used by an <see cref="IndexReader"/>, and speed
/// random-access to terms.
/// <para/>
/// This parameter determines the amount of computation required per query
/// term, regardless of the number of documents that contain that term. In
/// particular, it is the maximum number of other terms that must be scanned
/// before a term is located and its frequency and position information may be
/// processed. In a large index with user-entered query terms, query processing
/// time is likely to be dominated not by term lookup but rather by the
/// processing of frequency and positional data. In a small index or when many
/// uncommon query terms are generated (e.g., by wildcard queries) term lookup
/// may become a dominant cost.
/// <para/>
/// In particular, <c>numUniqueTerms/interval</c> terms are read into
/// memory by an <see cref="IndexReader"/>, and, on average, <c>interval/2</c> terms
/// must be scanned for each random term access.
///
/// <para/>
/// Takes effect immediately, but only applies to newly flushed/merged
/// segments.
///
/// <para/>
/// <b>NOTE:</b> this parameter does not apply to all <see cref="Codecs.PostingsFormat"/> implementations,
/// including the default one in this release. It only makes sense for term indexes
/// that are implemented as a fixed gap between terms. For example,
/// <see cref="Codecs.Lucene41.Lucene41PostingsFormat"/> implements the term index instead based upon how
/// terms share prefixes. To configure its parameters (the minimum and maximum size
/// for a block), you would instead use <see cref="Codecs.Lucene41.Lucene41PostingsFormat.Lucene41PostingsFormat(int, int)"/>.
/// which can also be configured on a per-field basis:
/// <code>
/// public class MyLucene45Codec : Lucene45Codec
/// {
/// //customize Lucene41PostingsFormat, passing minBlockSize=50, maxBlockSize=100
/// private readonly PostingsFormat tweakedPostings = new Lucene41PostingsFormat(50, 100);
///
/// public override PostingsFormat GetPostingsFormatForField(string field)
/// {
/// if (field.Equals("fieldWithTonsOfTerms", StringComparison.Ordinal))
/// return tweakedPostings;
/// else
/// return base.GetPostingsFormatForField(field);
/// }
/// }
/// ...
///
/// iwc.Codec = new MyLucene45Codec();
/// </code>
/// Note that other implementations may have their own parameters, or no parameters at all.
/// </summary>
/// <seealso cref="IndexWriterConfig.DEFAULT_TERM_INDEX_INTERVAL"/>
public virtual int TermIndexInterval
{
get
{
return termIndexInterval;
}
set // TODO: this should be private to the codec, not settable here
{
this.termIndexInterval = value;
}
}
/// <summary>
/// Gets or sets a value that determines the maximum number of delete-by-term operations that will be
/// buffered before both the buffered in-memory delete terms and queries are
/// applied and flushed.
/// <para/>
/// Disabled by default (writer flushes by RAM usage).
/// <para/>
/// NOTE: this setting won't trigger a segment flush.
///
/// <para/>
/// Takes effect immediately, but only the next time a document is added,
/// updated or deleted. Also, if you only delete-by-query, this setting has no
/// effect, i.e. delete queries are buffered until the next segment is flushed.
/// </summary>
/// <exception cref="ArgumentException">
/// if maxBufferedDeleteTerms is enabled but smaller than 1
/// </exception>
/// <seealso cref="RAMBufferSizeMB"/>
public virtual int MaxBufferedDeleteTerms
{
get
{
return maxBufferedDeleteTerms;
}
set
{
if (value != IndexWriterConfig.DISABLE_AUTO_FLUSH && value < 1)
{
throw new System.ArgumentException("maxBufferedDeleteTerms must at least be 1 when enabled");
}
this.maxBufferedDeleteTerms = value;
}
}
/// <summary>
/// Gets or sets a value that determines the amount of RAM that may be used for buffering added documents
/// and deletions before they are flushed to the <see cref="Store.Directory"/>. Generally for
/// faster indexing performance it's best to flush by RAM usage instead of
/// document count and use as large a RAM buffer as you can.
/// <para/>
/// When this is set, the writer will flush whenever buffered documents and
/// deletions use this much RAM. Pass in
/// <see cref="IndexWriterConfig.DISABLE_AUTO_FLUSH"/> to prevent triggering a flush
/// due to RAM usage. Note that if flushing by document count is also enabled,
/// then the flush will be triggered by whichever comes first.
/// <para/>
/// The maximum RAM limit is inherently determined by the runtime's available
/// memory. Yet, an <see cref="IndexWriter"/> session can consume a significantly
/// larger amount of memory than the given RAM limit since this limit is just
/// an indicator when to flush memory resident documents to the <see cref="Store.Directory"/>.
/// Flushes are likely happen concurrently while other threads adding documents
/// to the writer. For application stability the available memory in the runtime
/// should be significantly larger than the RAM buffer used for indexing.
/// <para/>
/// <b>NOTE</b>: the account of RAM usage for pending deletions is only
/// approximate. Specifically, if you delete by <see cref="Search.Query"/>, Lucene currently has no
/// way to measure the RAM usage of individual Queries so the accounting will
/// under-estimate and you should compensate by either calling <see cref="IndexWriter.Commit()"/>
/// periodically yourself, or by setting <see cref="MaxBufferedDeleteTerms"/>
/// to flush and apply buffered deletes by count instead of RAM usage (for each
/// buffered delete <see cref="Search.Query"/> a constant number of bytes is used to estimate RAM
/// usage). Note that enabling <see cref="MaxBufferedDeleteTerms"/> will not
/// trigger any segment flushes.
/// <para/>
/// <b>NOTE</b>: It's not guaranteed that all memory resident documents are
/// flushed once this limit is exceeded. Depending on the configured
/// <seealso cref="FlushPolicy"/> only a subset of the buffered documents are flushed and
/// therefore only parts of the RAM buffer is released.
/// <para/>
///
/// The default value is <see cref="IndexWriterConfig.DEFAULT_RAM_BUFFER_SIZE_MB"/>.
///
/// <para/>
/// Takes effect immediately, but only the next time a document is added,
/// updated or deleted.
/// </summary>
/// <seealso cref="IndexWriterConfig.RAMPerThreadHardLimitMB"/>
/// <exception cref="ArgumentException">
/// if ramBufferSizeMB is enabled but non-positive, or it disables
/// ramBufferSizeMB when maxBufferedDocs is already disabled </exception>
public virtual double RAMBufferSizeMB
{
get
{
return ramBufferSizeMB;
}
set
{
if (value != IndexWriterConfig.DISABLE_AUTO_FLUSH && value <= 0.0)
{
throw new System.ArgumentException("ramBufferSizeMB should be > 0.0 MB when enabled");
}
if (value == IndexWriterConfig.DISABLE_AUTO_FLUSH && maxBufferedDocs == IndexWriterConfig.DISABLE_AUTO_FLUSH)
{
throw new System.ArgumentException("at least one of ramBufferSizeMB and maxBufferedDocs must be enabled");
}
this.ramBufferSizeMB = value;
}
}
/// <summary>
/// Gets or sets a value that determines the minimal number of documents required before the buffered
/// in-memory documents are flushed as a new Segment. Large values generally
/// give faster indexing.
///
/// <para/>
/// When this is set, the writer will flush every maxBufferedDocs added
/// documents. Pass in <see cref="IndexWriterConfig.DISABLE_AUTO_FLUSH"/> to prevent
/// triggering a flush due to number of buffered documents. Note that if
/// flushing by RAM usage is also enabled, then the flush will be triggered by
/// whichever comes first.
///
/// <para/>
/// Disabled by default (writer flushes by RAM usage).
///
/// <para/>
/// Takes effect immediately, but only the next time a document is added,
/// updated or deleted.
/// </summary>
/// <seealso cref="RAMBufferSizeMB"/>
/// <exception cref="ArgumentException">
/// if maxBufferedDocs is enabled but smaller than 2, or it disables
/// maxBufferedDocs when ramBufferSizeMB is already disabled </exception>
public virtual int MaxBufferedDocs
{
get
{
return maxBufferedDocs;
}
set
{
if (value != IndexWriterConfig.DISABLE_AUTO_FLUSH && value < 2)
{
throw new System.ArgumentException("maxBufferedDocs must at least be 2 when enabled");
}
if (value == IndexWriterConfig.DISABLE_AUTO_FLUSH && ramBufferSizeMB == IndexWriterConfig.DISABLE_AUTO_FLUSH)
{
throw new System.ArgumentException("at least one of ramBufferSizeMB and maxBufferedDocs must be enabled");
}
this.maxBufferedDocs = value;
}
}
/// <summary>
/// Gets or sets the merged segment warmer. See <see cref="IndexReaderWarmer"/>.
/// <para/>
/// Takes effect on the next merge.
/// </summary>
public virtual IndexReaderWarmer MergedSegmentWarmer
{
get
{
return mergedSegmentWarmer;
}
set
{
this.mergedSegmentWarmer = value;
}
}
/// <summary>
/// Gets or sets the termsIndexDivisor passed to any readers that <see cref="IndexWriter"/> opens,
/// for example when applying deletes or creating a near-real-time reader in
/// <see cref="DirectoryReader.Open(IndexWriter, bool)"/>. If you pass -1, the
/// terms index won't be loaded by the readers. This is only useful in advanced
/// situations when you will only .Next() through all terms; attempts to seek
/// will hit an exception.
///
/// <para/>
/// Takes effect immediately, but only applies to readers opened after this
/// call
/// <para/>
/// <b>NOTE:</b> divisor settings > 1 do not apply to all <see cref="Codecs.PostingsFormat"/>
/// implementations, including the default one in this release. It only makes
/// sense for terms indexes that can efficiently re-sample terms at load time.
/// </summary>
public virtual int ReaderTermsIndexDivisor
{
get
{
return readerTermsIndexDivisor;
}
set
{
if (value <= 0 && value != -1)
{
throw new System.ArgumentException("divisor must be >= 1, or -1 (got " + value + ")");
}
readerTermsIndexDivisor = value;
}
}
/// <summary>
/// Gets the <see cref="Index.OpenMode"/> set by <see cref="IndexWriterConfig.OpenMode"/> setter. </summary>
public virtual OpenMode OpenMode
{
get
{
return openMode;
}
}
/// <summary>
/// Gets the <see cref="Index.IndexDeletionPolicy"/> specified in
/// <see cref="IndexWriterConfig.IndexDeletionPolicy"/> setter or
/// the default <see cref="KeepOnlyLastCommitDeletionPolicy"/>
/// </summary>
public virtual IndexDeletionPolicy IndexDeletionPolicy
{
get
{
return delPolicy;
}
}
/// <summary>
/// Gets the <see cref="IndexCommit"/> as specified in
/// <see cref="IndexWriterConfig.IndexCommit"/> setter or the default,
/// <c>null</c> which specifies to open the latest index commit point.
/// </summary>
public virtual IndexCommit IndexCommit
{
get
{
return commit;
}
}
/// <summary>
/// Expert: returns the <see cref="Search.Similarities.Similarity"/> implementation used by this
/// <see cref="IndexWriter"/>.
/// </summary>
public virtual Similarity Similarity
{
get
{
return similarity;
}
}
/// <summary>
/// Returns the <see cref="IMergeScheduler"/> that was set by
/// <see cref="IndexWriterConfig.MergeScheduler"/> setter.
/// </summary>
public virtual IMergeScheduler MergeScheduler
{
get
{
return mergeScheduler;
}
}
/// <summary>
/// Returns allowed timeout when acquiring the write lock.
/// </summary>
/// <seealso cref="IndexWriterConfig.WriteLockTimeout"/>
public virtual long WriteLockTimeout
{
get
{
return writeLockTimeout;
}
}
/// <summary>
/// Returns the current <see cref="Codecs.Codec"/>. </summary>
public virtual Codec Codec
{
get
{
return codec;
}
}
/// <summary>
/// Returns the current <see cref="Index.MergePolicy"/> in use by this writer.
/// </summary>
/// <seealso cref="IndexWriterConfig.MergePolicy"/>
public virtual MergePolicy MergePolicy
{
get
{
return mergePolicy;
}
}
/// <summary>
/// Returns the configured <see cref="DocumentsWriterPerThreadPool"/> instance.
/// </summary>
/// <seealso cref="IndexWriterConfig.IndexerThreadPool"/>
internal virtual DocumentsWriterPerThreadPool IndexerThreadPool
{
get
{
return indexerThreadPool;
}
}
/// <summary>
/// Returns the max number of simultaneous threads that may be indexing
/// documents at once in <see cref="IndexWriter"/>.
/// </summary>
public virtual int MaxThreadStates
{
get
{
try
{
return ((ThreadAffinityDocumentsWriterThreadPool)indexerThreadPool).MaxThreadStates;
}
catch (System.InvalidCastException cce)
{
throw new InvalidOperationException(cce.Message, cce);
}
}
}
/// <summary>
/// Returns <c>true</c> if <see cref="IndexWriter"/> should pool readers even if
/// <see cref="DirectoryReader.Open(IndexWriter, bool)"/> has not been called.
/// </summary>
public virtual bool UseReaderPooling
{
get
{
return readerPooling;
}
}
/// <summary>
/// Returns the indexing chain set on
/// <see cref="IndexWriterConfig.IndexingChain"/>.
/// </summary>
internal virtual IndexingChain IndexingChain
{
get
{
return indexingChain;
}
}
/// <summary>
/// Returns the max amount of memory each <see cref="DocumentsWriterPerThread"/> can
/// consume until forcefully flushed.
/// </summary>
/// <seealso cref="IndexWriterConfig.RAMPerThreadHardLimitMB"/>
public virtual int RAMPerThreadHardLimitMB
{
get
{
return perThreadHardLimitMB;
}
}
/// <seealso cref="IndexWriterConfig.FlushPolicy"/>
internal virtual FlushPolicy FlushPolicy
{
get
{
return flushPolicy;
}
}
/// <summary>
/// Returns <see cref="Util.InfoStream"/> used for debugging.
/// </summary>
/// <seealso cref="IndexWriterConfig.SetInfoStream(InfoStream)"/>
public virtual InfoStream InfoStream
{
get
{
return infoStream;
}
}
/// <summary>
/// Gets or sets if the <see cref="IndexWriter"/> should pack newly written segments in a
/// compound file. Default is <c>true</c>.
/// <para>
/// Use <c>false</c> for batch indexing with very large RAM buffer
/// settings.
/// </para>
/// <para>
/// <b>Note: To control compound file usage during segment merges see
/// <seealso cref="MergePolicy.NoCFSRatio"/> and
/// <seealso cref="MergePolicy.MaxCFSSegmentSizeMB"/>. This setting only
/// applies to newly created segments.</b>
/// </para>
/// </summary>
public virtual bool UseCompoundFile
{
get
{
return useCompoundFile;
}
set
{
this.useCompoundFile = value;
}
}
/// <summary>
/// Gets or sets if <see cref="IndexWriter"/> should call <see cref="AtomicReader.CheckIntegrity()"/>
/// on existing segments before merging them into a new one.
/// <para>
/// Use <c>true</c> to enable this safety check, which can help
/// reduce the risk of propagating index corruption from older segments
/// into new ones, at the expense of slower merging.
/// </para>
/// </summary>
public virtual bool CheckIntegrityAtMerge
{
get
{
return checkIntegrityAtMerge;
}
set
{
this.checkIntegrityAtMerge = value;
}
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("matchVersion=").Append(matchVersion).Append("\n");
sb.Append("analyzer=").Append(analyzer == null ? "null" : analyzer.GetType().Name).Append("\n");
sb.Append("ramBufferSizeMB=").Append(RAMBufferSizeMB).Append("\n");
sb.Append("maxBufferedDocs=").Append(MaxBufferedDocs).Append("\n");
sb.Append("maxBufferedDeleteTerms=").Append(MaxBufferedDeleteTerms).Append("\n");
sb.Append("mergedSegmentWarmer=").Append(MergedSegmentWarmer).Append("\n");
sb.Append("readerTermsIndexDivisor=").Append(ReaderTermsIndexDivisor).Append("\n");
sb.Append("termIndexInterval=").Append(TermIndexInterval).Append("\n"); // TODO: this should be private to the codec, not settable here
sb.Append("delPolicy=").Append(IndexDeletionPolicy.GetType().Name).Append("\n");
IndexCommit commit = IndexCommit;
sb.Append("commit=").Append(commit == null ? "null" : commit.ToString()).Append("\n");
sb.Append("openMode=").Append(OpenMode).Append("\n");
sb.Append("similarity=").Append(Similarity.GetType().Name).Append("\n");
sb.Append("mergeScheduler=").Append(MergeScheduler).Append("\n");
sb.Append("default WRITE_LOCK_TIMEOUT=").Append(IndexWriterConfig.WRITE_LOCK_TIMEOUT).Append("\n");
sb.Append("writeLockTimeout=").Append(WriteLockTimeout).Append("\n");
sb.Append("codec=").Append(Codec).Append("\n");
sb.Append("infoStream=").Append(InfoStream.GetType().Name).Append("\n");
sb.Append("mergePolicy=").Append(MergePolicy).Append("\n");
sb.Append("indexerThreadPool=").Append(IndexerThreadPool).Append("\n");
sb.Append("readerPooling=").Append(UseReaderPooling).Append("\n");
sb.Append("perThreadHardLimitMB=").Append(RAMPerThreadHardLimitMB).Append("\n");
sb.Append("useCompoundFile=").Append(UseCompoundFile).Append("\n");
sb.Append("checkIntegrityAtMerge=").Append(CheckIntegrityAtMerge).Append("\n");
return sb.ToString();
}
}
}
| |
using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace CslaGenerator.Metadata
{
public class GenerationParameters : INotifyPropertyChanged
{
#region State Fields
private bool _ackSilverlightPublicPropertyInfo;
private bool _saveBeforeGenerate = true;
private TargetFramework _targetFramework = TargetFramework.CSLA40;
private bool _writeTodo = true;
private bool _backupOldSource;
private bool _retryOnFileBusy = true;
private bool _separateNamespaces = true;
private bool _separateBaseClasses;
private bool _activeObjects;
private bool _useDotDesignerFileNameConvention = true;
private bool _updateOnlyDirtyChildren = true;
private bool _nullableSupport;
private CodeLanguage _outputLanguage = CodeLanguage.CSharp;
private CslaPropertyMode _propertyMode = CslaPropertyMode.Default;
private AuthorizationLevel _generateAuthorization = AuthorizationLevel.FullSupport;
private HeaderVerbosity _headerVerbosity = HeaderVerbosity.Full;
private bool _useBypassPropertyChecks;
private bool _useSingleCriteria;
private bool _usePublicPropertyInfo = true;
private bool _useChildFactory;
private bool _forceReadOnlyProperties;
private string _baseFilenameSuffix = string.Empty;
private string _extendedFilenameSuffix = string.Empty;
private string _classCommentFilenameSuffix = string.Empty;
private bool _separateClassComment;
private string _baseNamespace = String.Empty;
private string _utilitiesNamespace = String.Empty;
private string _utilitiesFolder = String.Empty;
private string _dalInterfaceNamespace = "DataAccess";
private string _dalObjectNamespace = "DataAccess.Sql";
private bool _generateSprocs = true;
private bool _oneSpFilePerObject = true;
private bool _generateInlineQueries;
private bool _generateQueriesWithSchema = true;
private bool _generateDatabaseClass = true;
private string _dalName = string.Empty;
private bool _usesCslaAuthorizationProvider = true;
private bool _generateWinForms = true;
private bool _generateWPF;
private bool _generateSilverlight;
private bool _silverlightUsingServices;
private string _databaseConnection;
private bool _generateDTO;
private bool _generateDalInterface = true;
private bool _generateDalObject = true;
private bool _generateSynchronous = true;
private bool _generateAsynchronous;
#endregion
#region Properties
public bool AckSilverlightPublicPropertyInfo
{
get { return _ackSilverlightPublicPropertyInfo; }
set
{
if (_ackSilverlightPublicPropertyInfo == value)
return;
_ackSilverlightPublicPropertyInfo = value;
OnPropertyChanged("");
}
}
public bool SaveBeforeGenerate
{
get { return _saveBeforeGenerate; }
set
{
if (_saveBeforeGenerate == value)
return;
_saveBeforeGenerate = value;
OnPropertyChanged("");
}
}
public TargetFramework TargetFramework
{
get { return _targetFramework; }
set
{
if (_targetFramework == value)
return;
_targetFramework = value;
OnPropertyChanged("TargetFramework");
}
}
public bool WriteTodo
{
get { return _writeTodo; }
set
{
if (_writeTodo == value)
return;
_writeTodo = value;
OnPropertyChanged("");
}
}
public bool BackupOldSource
{
get { return _backupOldSource; }
set
{
if (_backupOldSource == value)
return;
_backupOldSource = value;
OnPropertyChanged("");
}
}
public bool RetryOnFileBusy
{
get { return _retryOnFileBusy; }
set
{
if (_retryOnFileBusy == value)
return;
_retryOnFileBusy = value;
OnPropertyChanged("");
}
}
public bool SeparateNamespaces
{
get { return _separateNamespaces; }
set
{
if (_separateNamespaces == value)
return;
_separateNamespaces = value;
OnPropertyChanged("");
}
}
public bool SeparateBaseClasses
{
get { return _separateBaseClasses; }
set
{
if (_separateBaseClasses == value)
return;
_separateBaseClasses = value;
OnPropertyChanged("");
}
}
public bool ActiveObjects
{
get { return _activeObjects; }
set
{
if (_activeObjects == value)
return;
_activeObjects = value;
OnPropertyChanged("");
}
}
public bool UseDotDesignerFileNameConvention
{
get { return BaseFilenameSuffix == ".Designer"; }
set
{
if (value)
BaseFilenameSuffix = ".Designer";
if (_useDotDesignerFileNameConvention == value)
return;
_useDotDesignerFileNameConvention = value;
OnPropertyChanged("");
}
}
public CodeLanguage OutputLanguage
{
get { return _outputLanguage; }
set
{
if (_outputLanguage == value)
return;
_outputLanguage = value;
OnPropertyChanged("");
}
}
public bool UpdateOnlyDirtyChildren
{
get { return _updateOnlyDirtyChildren; }
set
{
if (_updateOnlyDirtyChildren == value)
return;
_updateOnlyDirtyChildren = value;
OnPropertyChanged("");
}
}
public bool NullableSupport
{
get { return _nullableSupport; }
set
{
if (_nullableSupport == value)
return;
_nullableSupport = value;
OnPropertyChanged("");
}
}
public CslaPropertyMode PropertyMode
{
get { return _propertyMode; }
set
{
if (_propertyMode == value)
return;
_propertyMode = value;
OnPropertyChanged("");
}
}
public AuthorizationLevel GenerateAuthorization
{
get { return _generateAuthorization; }
set
{
if (_generateAuthorization == value)
return;
_generateAuthorization = value;
OnPropertyChanged("GenerateAuthorization");
}
}
public HeaderVerbosity HeaderVerbosity
{
get { return _headerVerbosity; }
set
{
if (_headerVerbosity == value)
return;
_headerVerbosity = value;
OnPropertyChanged("");
}
}
public bool UseBypassPropertyChecks
{
get { return _useBypassPropertyChecks; }
set
{
if (_useBypassPropertyChecks == value)
return;
_useBypassPropertyChecks = value;
OnPropertyChanged("");
}
}
public bool UseSingleCriteria
{
get { return _useSingleCriteria; }
set
{
if (_useSingleCriteria == value)
return;
_useSingleCriteria = value;
OnPropertyChanged("");
}
}
public bool UsePublicPropertyInfo
{
get { return _usePublicPropertyInfo; }
set
{
if (_usePublicPropertyInfo == value)
return;
_usePublicPropertyInfo = value;
OnPropertyChanged("UsePublicPropertyInfo");
}
}
public bool UseChildFactory
{
get { return _useChildFactory; }
set
{
if (_useChildFactory == value)
return;
_useChildFactory = value;
OnPropertyChanged("");
}
}
public bool ForceReadOnlyProperties
{
get { return _forceReadOnlyProperties; }
set
{
if (_forceReadOnlyProperties == value)
return;
_forceReadOnlyProperties = value;
OnPropertyChanged("");
}
}
public string BaseFilenameSuffix
{
get { return _baseFilenameSuffix; }
set
{
value = PropertyHelper.TidyFilename(value);
if (_baseFilenameSuffix == value)
return;
_baseFilenameSuffix = value;
OnPropertyChanged("");
}
}
public string ExtendedFilenameSuffix
{
get { return _extendedFilenameSuffix; }
set
{
value = PropertyHelper.TidyFilename(value);
if (_extendedFilenameSuffix == value)
return;
_extendedFilenameSuffix = value;
OnPropertyChanged("");
}
}
public string ClassCommentFilenameSuffix
{
get { return _classCommentFilenameSuffix; }
set
{
value = PropertyHelper.TidyFilename(value);
if (_classCommentFilenameSuffix == value)
return;
_classCommentFilenameSuffix = value;
OnPropertyChanged("");
}
}
/// <summary>
/// Separate class comments in a folder.
/// </summary>
/// <value>
/// <c>true</c> if Separate class comments in a folder; otherwise, <c>false</c>.
/// </value>
public bool SeparateClassComment
{
get { return _separateClassComment; }
set
{
if (_separateClassComment == value)
return;
_separateClassComment = value;
OnPropertyChanged("");
}
}
public string BaseNamespace
{
get { return _baseNamespace; }
set
{
value = PropertyHelper.TidyFilename(value);
if (_baseNamespace == value)
return;
_baseNamespace = value;
OnPropertyChanged("");
}
}
public string UtilitiesNamespace
{
get { return _utilitiesNamespace; }
set
{
value = PropertyHelper.TidyFilename(value);
if (_utilitiesNamespace == value)
return;
_utilitiesNamespace = value;
OnPropertyChanged("");
}
}
public string UtilitiesFolder
{
get { return _utilitiesFolder; }
set
{
value = PropertyHelper.TidyFilename(value);
if (_utilitiesFolder == value)
return;
_utilitiesFolder = value;
OnPropertyChanged("");
}
}
public string DalInterfaceNamespace
{
get { return _dalInterfaceNamespace; }
set
{
value = PropertyHelper.TidyFilename(value);
if (_dalInterfaceNamespace == value)
return;
_dalInterfaceNamespace = value;
OnPropertyChanged("");
}
}
public string DalObjectNamespace
{
get { return _dalObjectNamespace; }
set
{
value = PropertyHelper.TidyFilename(value);
if (_dalObjectNamespace == value)
return;
_dalObjectNamespace = value;
OnPropertyChanged("");
}
}
public bool GenerateSprocs
{
get { return _generateSprocs; }
set
{
if (_generateSprocs == value)
return;
_generateSprocs = value;
OnPropertyChanged("GenerateSprocs");
}
}
public bool OneSpFilePerObject
{
get { return _oneSpFilePerObject; }
set
{
if (_oneSpFilePerObject == value)
return;
_oneSpFilePerObject = value;
OnPropertyChanged("");
}
}
public bool GenerateInlineQueries
{
get { return _generateInlineQueries; }
set
{
if (_generateInlineQueries == value)
return;
_generateInlineQueries = value;
OnPropertyChanged("");
}
}
public bool GenerateQueriesWithSchema
{
get { return _generateQueriesWithSchema; }
set
{
if (_generateQueriesWithSchema == value)
return;
_generateQueriesWithSchema = value;
OnPropertyChanged("");
}
}
public bool GenerateDatabaseClass
{
get { return _generateDatabaseClass; }
set
{
if (_generateDatabaseClass == value)
return;
_generateDatabaseClass = value;
OnPropertyChanged("");
}
}
public string DalName
{
get { return _dalName; }
set
{
value = PropertyHelper.Tidy(value);
if (_dalName == value)
return;
_dalName = value;
OnPropertyChanged("");
}
}
public bool UsesCslaAuthorizationProvider
{
get { return _usesCslaAuthorizationProvider; }
set
{
if (_usesCslaAuthorizationProvider == value)
return;
_usesCslaAuthorizationProvider = value;
OnPropertyChanged("");
}
}
public bool GenerateWinForms
{
get { return _generateWinForms; }
set
{
if (_generateWinForms == value)
return;
_generateWinForms = value;
OnPropertyChanged("GenerateWinForms");
}
}
public bool GenerateWPF
{
get { return _generateWPF; }
set
{
if (_generateWPF == value)
return;
_generateWPF = value;
OnPropertyChanged("GenerateWPF");
}
}
public bool GenerateSilverlight4
{
get { return _generateSilverlight; }
set
{
if (_generateSilverlight == value)
return;
_generateSilverlight = value;
OnPropertyChanged("GenerateSilverlight4");
}
}
public bool SilverlightUsingServices
{
get { return _silverlightUsingServices; }
set
{
if (_silverlightUsingServices == value)
return;
_silverlightUsingServices = value;
OnPropertyChanged("SilverlightUsingServices");
}
}
public string DatabaseConnection
{
get
{
if (string.IsNullOrEmpty(_databaseConnection))
if (GeneratorController.Current.CurrentUnit.Params != null)
return GeneratorController.Current.CurrentUnit.Params.DefaultDataBase;
return _databaseConnection;
}
set
{
value = PropertyHelper.Tidy(value);
if (_databaseConnection == value)
return;
_databaseConnection = value;
GeneratorController.Current.CurrentUnit.Params.DefaultDataBase = value;
OnPropertyChanged("");
}
}
public bool GenerateDTO
{
get { return _generateDTO; }
set
{
if (_generateDTO == value)
return;
_generateDTO = value;
OnPropertyChanged("GenerateDTO");
}
}
public bool GenerateDalInterface
{
get { return _generateDalInterface; }
set
{
if (_generateDalInterface == value)
return;
_generateDalInterface = value;
OnPropertyChanged("");
}
}
public bool GenerateDalObject
{
get { return _generateDalObject; }
set
{
if (_generateDalObject == value)
return;
_generateDalObject = value;
OnPropertyChanged("");
}
}
public bool GenerateSynchronous
{
get { return _generateSynchronous; }
set
{
if (_generateSynchronous == value)
return;
_generateSynchronous = value;
OnPropertyChanged("GenerateSynchronous");
}
}
public bool GenerateAsynchronous
{
get { return _generateAsynchronous; }
set
{
if (_generateAsynchronous == value)
return;
_generateAsynchronous = value;
OnPropertyChanged("GenerateAsynchronous");
}
}
[Browsable(false)]
public bool DualListInheritance
{
get { return GenerateWinForms && (GenerateWPF || GenerateSilverlight4); }
}
[Browsable(false)]
public bool TargetIsCsla4All
{
get { return TargetIsCsla4 || TargetIsCsla4DAL; }
}
[Browsable(false)]
public bool TargetIsCsla4
{
get
{
return
_targetFramework == TargetFramework.CSLA40/* ||
_targetFramework == TargetFramework.CSLA45*/;
}
}
[Browsable(false)]
public bool TargetIsCsla4DAL
{
get
{
return
_targetFramework == TargetFramework.CSLA40DAL/* ||
_targetFramework == TargetFramework.CSLA45DAL*/;
}
}
#endregion
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (!string.IsNullOrEmpty(propertyName))
{
if (propertyName == "UsePublicPropertyInfo")
{
if (!_usePublicPropertyInfo)
UsePublicPropertyInfoAlert();
}
if (propertyName == "TargetFramework")
SetCsla4Options();
if (propertyName == "GenerateWinForms")
SetServerInvocationOptions();
if (propertyName == "GenerateWPF")
SetServerInvocationOptions();
if (propertyName == "GenerateSilverlight4")
{
if (_generateSilverlight)
{
_silverlightUsingServices = false;
UsePublicPropertyInfoAlert();
}
SetServerInvocationOptions();
}
if (propertyName == "SilverlightUsingServices")
{
if (_silverlightUsingServices)
{
_generateSilverlight = false;
UsePublicPropertyInfoAlert();
}
SetServerInvocationOptions();
}
if (propertyName == "GenerateSynchronous")
SetServerInvocationOptions();
if (propertyName == "GenerateAsynchronous")
SetServerInvocationOptions();
if (propertyName == "GenerateAuthorization")
{
if (_generateAuthorization == AuthorizationLevel.None ||
_generateAuthorization == AuthorizationLevel.Custom)
_usesCslaAuthorizationProvider = false;
}
}
Dirty = true;
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
internal void ResetAckSilverlightPublicPropertyInfo()
{
if (AckSilverlightPublicPropertyInfo)
{
if (!_generateSilverlight && !_silverlightUsingServices)
{
AckSilverlightPublicPropertyInfo = false;
}
}
}
private void UsePublicPropertyInfoAlert()
{
if (AckSilverlightPublicPropertyInfo)
return;
if (!_usePublicPropertyInfo && (_generateSilverlight || _silverlightUsingServices))
{
DialogResult alert = MessageBox.Show("Silverlight 4 targets need a public PropertyInfo declaration.\r\n" +
"Do you want to check the \"Use public PropertyInfo\" option?",
"Silverlight Alert", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
AckSilverlightPublicPropertyInfo = true;
if (alert == DialogResult.Yes)
UsePublicPropertyInfo = true;
}
}
private void SetCsla4Options()
{
UseCsla4 = false;
UseDal = false;
_generateDalInterface = false;
_generateDalObject = false;
if (TargetIsCsla4All)
{
UseCsla4 = true;
_activeObjects = false;
_useSingleCriteria = false;
}
else
{
_generateQueriesWithSchema = true;
_useBypassPropertyChecks = false;
_usePublicPropertyInfo = false;
_useChildFactory = true;
_usesCslaAuthorizationProvider = true;
_generateAuthorization = AuthorizationLevel.ObjectLevel;
_usesCslaAuthorizationProvider = true;
}
if (TargetIsCsla4DAL)
{
UseDal = true;
_generateDalInterface = true;
_generateDalObject = true;
_silverlightUsingServices = false;
_generateDatabaseClass = false;
}
}
private void SetServerInvocationOptions()
{
ForceSync = false;
ForceAsync = false;
if (_generateSilverlight && (_generateWinForms || _generateWPF))
{
_generateAsynchronous = true;
ForceAsync = true;
}
if (_silverlightUsingServices && !(_generateWinForms || _generateWPF))
{
_generateSynchronous = false;
_generateAsynchronous = false;
ForceSync = true;
ForceAsync = true;
}
}
[Browsable(false)]
internal bool UseCsla4 { get; private set; }
[Browsable(false)]
internal bool UseDal { get; private set; }
[Browsable(false)]
internal bool ForceSync { get; private set; }
[Browsable(false)]
internal bool ForceAsync { get; private set; }
[Browsable(false)]
internal bool Dirty { get; set; }
#endregion
internal GenerationParameters Clone()
{
GenerationParameters obj = null;
try
{
obj = (GenerationParameters)Util.ObjectCloner.CloneShallow(this);
obj.Dirty = false;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return obj;
}
public GenerationParameters()
{
OnPropertyChanged("TargetFramework");
OnPropertyChanged("GenerateWinForms");
OnPropertyChanged("GenerateWPF");
OnPropertyChanged("GenerateSilverlight4");
OnPropertyChanged("GenerateSynchronous");
OnPropertyChanged("GenerateAsynchronous");
OnPropertyChanged("GenerateAuthorization");
OnPropertyChanged("GenerateDTO");
OnPropertyChanged("GenerateSprocs");
}
}
}
| |
using System;
using System.Linq;
using System.ComponentModel;
using System.Net;
using System.Runtime.CompilerServices;
using System.ServiceModel.Syndication;
using System.Text.RegularExpressions;
using System.Xml.Linq;
namespace WPAppStudio.Entities.Base
{
/// <summary>
/// Representation of the results in a RSS search.
/// </summary>
public class RssSearchResult : BindableBase
{
private string _author;
/// <summary>
/// Gets/Sets the author of the RSS.
/// </summary>
public string Author
{
get
{
return _author;
}
set
{
SetProperty(ref _author, value);
}
}
private DateTime _publishDate;
/// <summary>
/// Gets/Sets the publish date of the RSS.
/// </summary>
public DateTime PublishDate
{
get
{ return _publishDate; }
set
{
SetProperty(ref _publishDate, value);
}
}
private string _id;
/// <summary>
/// Gets/Sets the identifier of the RSS.
/// </summary>
public string Id
{
get { return _id; }
set
{
SetProperty(ref _id, value);
}
}
private string _title;
/// <summary>
/// Gets/Sets the title of the RSS.
/// </summary>
public string Title
{
get { return _title; }
set
{
SetProperty(ref _title, value);
}
}
private string _summary;
/// <summary>
/// Gets/Sets the summary of the RSS.
/// </summary>
public string Summary
{
get { return _summary; }
set
{
SetProperty(ref _summary, value);
}
}
private string _content;
/// <summary>
/// Gets/Sets the summary of the RSS.
/// </summary>
public string Content
{
get { return _content; }
set
{
SetProperty(ref _content, value);
}
}
private string _imageUrl;
/// <summary>
/// Gets/Sets the image URL of the RSS.
/// </summary>
public string ImageUrl
{
get { return _imageUrl; }
set
{
SetProperty(ref _imageUrl, value);
}
}
private string _extraImageUrl;
/// <summary>
/// Gets/Sets the extra image URL of the RSS.
/// </summary>
public string ExtraImageUrl
{
get { return _extraImageUrl; }
set
{
SetProperty(ref _extraImageUrl, value);
}
}
private string _mediaUrl;
/// <summary>
/// Gets/Sets the video URL of the RSS.
/// </summary>
public string MediaUrl
{
get { return _mediaUrl; }
set
{
SetProperty(ref _mediaUrl, value);
}
}
private string _feedUrl;
/// <summary>
/// Gets/Sets the RSS item feed URL.
/// </summary>
public string FeedUrl
{
get { return _feedUrl; }
set
{
SetProperty(ref _feedUrl, value);
}
}
/// <summary>
/// Initializes a new instance of <see cref="RssSearchResult" /> class.
/// </summary>
public RssSearchResult() { }
/// <summary>
/// Initializes a new instance of <see cref="RssSearchResult" /> class.
/// </summary>
/// <param name="item">A valid SyndicationItem.</param>
/// <param name="feedImage">Source feed image</param>
public RssSearchResult(SyndicationItem item, string feedImage)
: this()
{
Author = item.Authors.Count > 0 ? item.Authors[0].Name : string.Empty;
if (string.IsNullOrEmpty(Author))
{
if (item.ElementExtensions.Count(p => p.OuterName == "creator") != 0)
{
var creator = item.ElementExtensions.FirstOrDefault(p => p.OuterName == "creator");
if (creator != null)
Author = creator.GetObject<XElement>().Value;
}
}
Id = item.Id;
Title = item.Title != null ? HttpUtility.HtmlDecode(item.Title.Text) : string.Empty;
Content = HttpUtility.HtmlDecode(RssUtil.SanitizeHtml(RssUtil.GetSummary(item)));
Summary = RssUtil.SanitizeHtml(string.IsNullOrEmpty(Content) ? string.Empty : Content);
if (Summary.Length > 140)
Summary = HtmlUtil.TruncateHtml(Summary, 137, "...");
PublishDate = item.PublishDate.DateTime;
ImageUrl = RssUtil.GetImage(item, true);
ExtraImageUrl = RssUtil.GetExtraImage(item);
if (string.IsNullOrEmpty(ImageUrl) && !string.IsNullOrEmpty(ExtraImageUrl))
ImageUrl = ExtraImageUrl;
if (string.IsNullOrEmpty(ImageUrl))
ImageUrl = feedImage;
if (String.IsNullOrEmpty(ImageUrl))
{
var encoded = item.ElementExtensions.FirstOrDefault(p => p.OuterName == "encoded");
string encodedText = string.Empty;
if (encoded != null)
encodedText = encoded.GetObject<XElement>().Value;
var imageUrl =
Regex.Match(encodedText, "<img.+?src=[\"'](.+?)[\"'].+?>", RegexOptions.IgnoreCase).Groups[1].Value;
ImageUrl = !string.IsNullOrEmpty(imageUrl) ? imageUrl : string.Empty;
}
MediaUrl = RssUtil.GetMediaVideoURL(item);
FeedUrl = RssUtil.GetItemFeedLink(item);
}
public override bool Equals(object obj)
{
var cmp = obj as RssSearchResult;
if(cmp == null) return false;
if (Title != null)
return Title.Equals(cmp.Title);
if (Id != null)
return Id.Equals(cmp.Id);
return this==obj;
}
public override int GetHashCode()
{
if (Title != null)
return Title.GetHashCode();
if (Id != null)
return Id.GetHashCode();
return base.GetHashCode();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Text;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.IO
{
// This abstract base class represents a reader that can read a sequential
// stream of characters. This is not intended for reading bytes -
// there are methods on the Stream class to read bytes.
// A subclass must minimally implement the Peek() and Read() methods.
//
// This class is intended for character input, not bytes.
// There are methods on the Stream class for reading bytes.
public abstract class TextReader : IDisposable
{
public static readonly TextReader Null = new NullTextReader();
protected TextReader() { }
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
}
// Returns the next available character without actually reading it from
// the input stream. The current position of the TextReader is not changed by
// this operation. The returned value is -1 if no further characters are
// available.
//
// This default method simply returns -1.
//
[Pure]
public virtual int Peek()
{
return -1;
}
// Reads the next character from the input stream. The returned value is
// -1 if no further characters are available.
//
// This default method simply returns -1.
//
public virtual int Read()
{
return -1;
}
// Reads a block of characters. This method will read up to
// count characters from this TextReader into the
// buffer character array starting at position
// index. Returns the actual number of characters read.
//
public virtual int Read(char[] buffer, int index, int count)
{
if (buffer == null)
{
throw new ArgumentNullException("buffer", SR.ArgumentNull_Buffer);
}
if (index < 0)
{
throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - index < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
int n = 0;
do
{
int ch = Read();
if (ch == -1)
{
break;
}
buffer[index + n++] = (char)ch;
} while (n < count);
return n;
}
// Reads all characters from the current position to the end of the
// TextReader, and returns them as one string.
public virtual string ReadToEnd()
{
char[] chars = new char[4096];
int len;
StringBuilder sb = new StringBuilder(4096);
while ((len = Read(chars, 0, chars.Length)) != 0)
{
sb.Append(chars, 0, len);
}
return sb.ToString();
}
// Blocking version of read. Returns only when count
// characters have been read or the end of the file was reached.
//
public virtual int ReadBlock(char[] buffer, int index, int count)
{
int i, n = 0;
do
{
n += (i = Read(buffer, index + n, count - n));
} while (i > 0 && n < count);
return n;
}
// Reads a line. A line is defined as a sequence of characters followed by
// a carriage return ('\r'), a line feed ('\n'), or a carriage return
// immediately followed by a line feed. The resulting string does not
// contain the terminating carriage return and/or line feed. The returned
// value is null if the end of the input stream has been reached.
//
public virtual string ReadLine()
{
StringBuilder sb = new StringBuilder();
while (true)
{
int ch = Read();
if (ch == -1) break;
if (ch == '\r' || ch == '\n')
{
if (ch == '\r' && Peek() == '\n')
{
Read();
}
return sb.ToString();
}
sb.Append((char)ch);
}
if (sb.Length > 0)
{
return sb.ToString();
}
return null;
}
#region Task based Async APIs
public virtual Task<string> ReadLineAsync()
{
return Task<String>.Factory.StartNew(state =>
{
return ((TextReader)state).ReadLine();
},
this, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
public async virtual Task<string> ReadToEndAsync()
{
char[] chars = new char[4096];
int len;
StringBuilder sb = new StringBuilder(4096);
while ((len = await ReadAsyncInternal(chars, 0, chars.Length).ConfigureAwait(false)) != 0)
{
sb.Append(chars, 0, len);
}
return sb.ToString();
}
public virtual Task<int> ReadAsync(char[] buffer, int index, int count)
{
if (buffer == null)
{
throw new ArgumentNullException("buffer", SR.ArgumentNull_Buffer);
}
if (index < 0 || count < 0)
{
throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - index < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
return ReadAsyncInternal(buffer, index, count);
}
internal virtual Task<int> ReadAsyncInternal(char[] buffer, int index, int count)
{
Debug.Assert(buffer != null);
Debug.Assert(index >= 0);
Debug.Assert(count >= 0);
Debug.Assert(buffer.Length - index >= count);
var tuple = new Tuple<TextReader, char[], int, int>(this, buffer, index, count);
return Task<int>.Factory.StartNew(state =>
{
var t = (Tuple<TextReader, char[], int, int>)state;
return t.Item1.Read(t.Item2, t.Item3, t.Item4);
},
tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
public virtual Task<int> ReadBlockAsync(char[] buffer, int index, int count)
{
if (buffer == null)
{
throw new ArgumentNullException("buffer", SR.ArgumentNull_Buffer);
}
if (index < 0 || count < 0)
{
throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - index < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
return ReadBlockAsyncInternal(buffer, index, count);
}
private async Task<int> ReadBlockAsyncInternal(char[] buffer, int index, int count)
{
Debug.Assert(buffer != null);
Debug.Assert(index >= 0);
Debug.Assert(count >= 0);
Debug.Assert(buffer.Length - index >= count);
int i, n = 0;
do
{
i = await ReadAsyncInternal(buffer, index + n, count - n).ConfigureAwait(false);
n += i;
} while (i > 0 && n < count);
return n;
}
#endregion
private sealed class NullTextReader : TextReader
{
public NullTextReader() { }
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
public override int Read(char[] buffer, int index, int count)
{
return 0;
}
public override string ReadLine()
{
return null;
}
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
//==========================================================================
// File: ChunkedMemoryStream.cs
//
// Summary: Memory stream that doesn't need to be resized.
//
//==========================================================================
using System;
using System.IO;
using System.Runtime.Remoting.Channels;
namespace System.Runtime.Remoting.Channels
{
internal class ChunkedMemoryStream : Stream
{
private class MemoryChunk
{
public byte[] Buffer = null;
public MemoryChunk Next = null;
}
// state
private MemoryChunk _chunks = null; // data
private IByteBufferPool _bufferPool = null; // pool of byte buffers to use
private bool _bClosed = false; // has the stream been closed.
private MemoryChunk _writeChunk = null; // current chunk to write to
private int _writeOffset = 0; // offset into chunk to write to
private MemoryChunk _readChunk = null; // current chunk to read from
private int _readOffset = 0; // offset into chunk to read from
public ChunkedMemoryStream(IByteBufferPool bufferPool)
{
_bufferPool = bufferPool;
} // ChunkedMemoryStream
public override bool CanRead { get { return true; } }
public override bool CanSeek { get { return true; } }
public override bool CanWrite { get { return true; } }
public override long Length
{
get
{
if (_bClosed)
{
throw new RemotingException(
CoreChannel.GetResourceString("Remoting_Stream_StreamIsClosed"));
}
int length = 0;
MemoryChunk chunk = _chunks;
while (chunk != null)
{
MemoryChunk next = chunk.Next;
if (next != null)
length += chunk.Buffer.Length;
else
length += _writeOffset;
chunk = next;
}
return (long)length;
}
} // Length
public override long Position
{
get
{
if (_bClosed)
{
throw new RemotingException(
CoreChannel.GetResourceString("Remoting_Stream_StreamIsClosed"));
}
if (_readChunk == null)
return 0;
int pos = 0;
MemoryChunk chunk = _chunks;
while (chunk != _readChunk)
{
pos += chunk.Buffer.Length;
chunk = chunk.Next;
}
pos += _readOffset;
return (long)pos;
}
set
{
if (_bClosed)
{
throw new RemotingException(
CoreChannel.GetResourceString("Remoting_Stream_StreamIsClosed"));
}
if (value < 0)
throw new ArgumentOutOfRangeException("value");
// back up current position in case new position is out of range
MemoryChunk backupReadChunk = _readChunk;
int backupReadOffset = _readOffset;
_readChunk = null;
_readOffset = 0;
int leftUntilAtPos = (int)value;
MemoryChunk chunk = _chunks;
while (chunk != null)
{
if ((leftUntilAtPos < chunk.Buffer.Length) ||
((leftUntilAtPos == chunk.Buffer.Length) &&
(chunk.Next == null)))
{
// the desired position is in this chunk
_readChunk = chunk;
_readOffset = leftUntilAtPos;
break;
}
leftUntilAtPos -= chunk.Buffer.Length;
chunk = chunk.Next;
}
if (_readChunk == null)
{
// position is out of range
_readChunk = backupReadChunk;
_readOffset = backupReadOffset;
throw new ArgumentOutOfRangeException("value");
}
}
} // Position
public override long Seek(long offset, SeekOrigin origin)
{
if (_bClosed)
{
throw new RemotingException(
CoreChannel.GetResourceString("Remoting_Stream_StreamIsClosed"));
}
switch(origin)
{
case SeekOrigin.Begin:
Position = offset;
break;
case SeekOrigin.Current:
Position = Position + offset;
break;
case SeekOrigin.End:
Position = Length + offset;
break;
}
return Position;
} // Seek
public override void SetLength(long value) { throw new NotSupportedException(); }
protected override void Dispose(bool disposing)
{
try {
_bClosed = true;
if (disposing)
ReleaseMemoryChunks(_chunks);
_chunks = null;
_writeChunk = null;
_readChunk = null;
}
finally {
base.Dispose(disposing);
}
} // Close
public override void Flush()
{
} // Flush
public override int Read(byte[] buffer, int offset, int count)
{
if (_bClosed)
{
throw new RemotingException(
CoreChannel.GetResourceString("Remoting_Stream_StreamIsClosed"));
}
if (_readChunk == null)
{
if (_chunks == null)
return 0;
_readChunk = _chunks;
_readOffset = 0;
}
byte[] chunkBuffer = _readChunk.Buffer;
int chunkSize = chunkBuffer.Length;
if (_readChunk.Next == null)
chunkSize = _writeOffset;
int bytesRead = 0;
while (count > 0)
{
if (_readOffset == chunkSize)
{
// exit if no more chunks are currently available
if (_readChunk.Next == null)
break;
_readChunk = _readChunk.Next;
_readOffset = 0;
chunkBuffer = _readChunk.Buffer;
chunkSize = chunkBuffer.Length;
if (_readChunk.Next == null)
chunkSize = _writeOffset;
}
int readCount = Math.Min(count, chunkSize - _readOffset);
Buffer.BlockCopy(chunkBuffer, _readOffset, buffer, offset, readCount);
offset += readCount;
count -= readCount;
_readOffset += readCount;
bytesRead += readCount;
}
return bytesRead;
} // Read
public override int ReadByte()
{
if (_bClosed)
{
throw new RemotingException(
CoreChannel.GetResourceString("Remoting_Stream_StreamIsClosed"));
}
if (_readChunk == null)
{
if (_chunks == null)
return 0;
_readChunk = _chunks;
_readOffset = 0;
}
byte[] chunkBuffer = _readChunk.Buffer;
int chunkSize = chunkBuffer.Length;
if (_readChunk.Next == null)
chunkSize = _writeOffset;
if (_readOffset == chunkSize)
{
// exit if no more chunks are currently available
if (_readChunk.Next == null)
return -1;
_readChunk = _readChunk.Next;
_readOffset = 0;
chunkBuffer = _readChunk.Buffer;
chunkSize = chunkBuffer.Length;
if (_readChunk.Next == null)
chunkSize = _writeOffset;
}
return chunkBuffer[_readOffset++];
} // ReadByte
public override void Write(byte[] buffer, int offset, int count)
{
if (_bClosed)
{
throw new RemotingException(
CoreChannel.GetResourceString("Remoting_Stream_StreamIsClosed"));
}
if (_chunks == null)
{
_chunks = AllocateMemoryChunk();
_writeChunk = _chunks;
_writeOffset = 0;
}
byte[] chunkBuffer = _writeChunk.Buffer;
int chunkSize = chunkBuffer.Length;
while (count > 0)
{
if (_writeOffset == chunkSize)
{
// allocate a new chunk if the current one is full
_writeChunk.Next = AllocateMemoryChunk();
_writeChunk = _writeChunk.Next;
_writeOffset = 0;
chunkBuffer = _writeChunk.Buffer;
chunkSize = chunkBuffer.Length;
}
int copyCount = Math.Min(count, chunkSize - _writeOffset);
Buffer.BlockCopy(buffer, offset, chunkBuffer, _writeOffset, copyCount);
offset += copyCount;
count -= copyCount;
_writeOffset += copyCount;
}
} // Write
public override void WriteByte(byte value)
{
if (_bClosed)
{
throw new RemotingException(
CoreChannel.GetResourceString("Remoting_Stream_StreamIsClosed"));
}
if (_chunks == null)
{
_chunks = AllocateMemoryChunk();
_writeChunk = _chunks;
_writeOffset = 0;
}
byte[] chunkBuffer = _writeChunk.Buffer;
int chunkSize = chunkBuffer.Length;
if (_writeOffset == chunkSize)
{
// allocate a new chunk if the current one is full
_writeChunk.Next = AllocateMemoryChunk();
_writeChunk = _writeChunk.Next;
_writeOffset = 0;
chunkBuffer = _writeChunk.Buffer;
chunkSize = chunkBuffer.Length;
}
chunkBuffer[_writeOffset++] = value;
} // WriteByte
// copy entire buffer into an array
public virtual byte[] ToArray()
{
int length = (int)Length; // this will throw if stream is closed
byte[] copy = new byte[Length];
MemoryChunk backupReadChunk = _readChunk;
int backupReadOffset = _readOffset;
_readChunk = _chunks;
_readOffset = 0;
Read(copy, 0, length);
_readChunk = backupReadChunk;
_readOffset = backupReadOffset;
return copy;
} // ToArray
// write remainder of this stream to another stream
public virtual void WriteTo(Stream stream)
{
if (_bClosed)
{
throw new RemotingException(
CoreChannel.GetResourceString("Remoting_Stream_StreamIsClosed"));
}
if (stream == null)
throw new ArgumentNullException("stream");
if (_readChunk == null)
{
if (_chunks == null)
return;
_readChunk = _chunks;
_readOffset = 0;
}
byte[] chunkBuffer = _readChunk.Buffer;
int chunkSize = chunkBuffer.Length;
if (_readChunk.Next == null)
chunkSize = _writeOffset;
// following code mirrors Read() logic (_readChunk/_readOffset should
// point just past last byte of last chunk when done)
for (;;) // loop until end of chunks is found
{
if (_readOffset == chunkSize)
{
// exit if no more chunks are currently available
if (_readChunk.Next == null)
break;
_readChunk = _readChunk.Next;
_readOffset = 0;
chunkBuffer = _readChunk.Buffer;
chunkSize = chunkBuffer.Length;
if (_readChunk.Next == null)
chunkSize = _writeOffset;
}
int writeCount = chunkSize - _readOffset;
stream.Write(chunkBuffer, _readOffset, writeCount);
_readOffset = chunkSize;
}
} // WriteTo
private MemoryChunk AllocateMemoryChunk()
{
MemoryChunk chunk = new MemoryChunk();
chunk.Buffer = _bufferPool.GetBuffer();
chunk.Next = null;
return chunk;
} // AllocateMemoryChunk
private void ReleaseMemoryChunks(MemoryChunk chunk)
{
// If the buffer pool always allocates a new buffer,
// there's no point to trying to return all of the buffers.
if (_bufferPool is ByteBufferAllocator)
return;
while (chunk != null)
{
_bufferPool.ReturnBuffer(chunk.Buffer);
chunk = chunk.Next;
}
} // FreeMemoryChunk
} // ChunkedMemoryStream
} // namespace System.IO
| |
/************************************************************************************
Copyright : Copyright (c) Facebook Technologies, LLC and its affiliates. All rights reserved.
Licensed under the Oculus SDK License Version 3.4.1 (the "License");
you may not use the Oculus SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
https://developer.oculus.com/licenses/sdk-3.4.1
Unless required by applicable law or agreed to in writing, the Oculus SDK
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 UnityEngine;
using System.Collections;
using UnityEngine.UI;
//-------------------------------------------------------------------------------------
/// <summary>
/// Shows debug information on a heads-up display.
/// </summary>
public class OVRDebugInfo : MonoBehaviour
{
#region GameObjects for Debug Information UIs
GameObject debugUIManager;
GameObject debugUIObject;
GameObject riftPresent;
GameObject fps;
GameObject ipd;
GameObject fov;
GameObject height;
GameObject depth;
GameObject resolutionEyeTexture;
GameObject latencies;
GameObject texts;
#endregion
#region Debug strings
string strRiftPresent = null; // "VR DISABLED"
string strFPS = null; // "FPS: 0";
string strIPD = null; // "IPD: 0.000";
string strFOV = null; // "FOV: 0.0f";
string strHeight = null; // "Height: 0.0f";
string strDepth = null; // "Depth: 0.0f";
string strResolutionEyeTexture = null; // "Resolution : {0} x {1}"
string strLatencies = null; // "R: {0:F3} TW: {1:F3} PP: {2:F3} RE: {3:F3} TWE: {4:F3}"
#endregion
/// <summary>
/// Variables for FPS
/// </summary>
float updateInterval = 0.5f;
float accum = 0.0f;
int frames = 0;
float timeLeft = 0.0f;
/// <summary>
/// Managing for UI initialization
/// </summary>
bool initUIComponent = false;
bool isInited = false;
/// <summary>
/// UIs Y offset
/// </summary>
float offsetY = 55.0f;
/// <summary>
/// Managing for rift detection UI
/// </summary>
float riftPresentTimeout = 0.0f;
/// <summary>
/// Turn on / off VR variables
/// </summary>
bool showVRVars = false;
#region MonoBehaviour handler
/// <summary>
/// Initialization
/// </summary>
void Awake()
{
// Create canvas for using new GUI
debugUIManager = new GameObject();
debugUIManager.name = "DebugUIManager";
debugUIManager.transform.parent = GameObject.Find("LeftEyeAnchor").transform;
RectTransform rectTransform = debugUIManager.AddComponent<RectTransform>();
rectTransform.sizeDelta = new Vector2(100f, 100f);
rectTransform.localScale = new Vector3(0.001f, 0.001f, 0.001f);
rectTransform.localPosition = new Vector3(0.01f, 0.17f, 0.53f);
rectTransform.localEulerAngles = Vector3.zero;
Canvas canvas = debugUIManager.AddComponent<Canvas>();
canvas.renderMode = RenderMode.WorldSpace;
canvas.pixelPerfect = false;
}
/// <summary>
/// Updating VR variables and managing UI present
/// </summary>
void Update()
{
if (initUIComponent && !isInited)
{
InitUIComponents();
}
if (Input.GetKeyDown(KeyCode.Space) && riftPresentTimeout < 0.0f)
{
initUIComponent = true;
showVRVars ^= true;
}
UpdateDeviceDetection();
// Presenting VR variables
if (showVRVars)
{
debugUIManager.SetActive(true);
UpdateVariable();
UpdateStrings();
}
else
{
debugUIManager.SetActive(false);
}
}
/// <summary>
/// Initialize isInited value on OnDestroy
/// </summary>
void OnDestroy()
{
isInited = false;
}
#endregion
#region Private Functions
/// <summary>
/// Initialize UI GameObjects
/// </summary>
void InitUIComponents()
{
float posY = 0.0f;
int fontSize = 20;
debugUIObject = new GameObject();
debugUIObject.name = "DebugInfo";
debugUIObject.transform.parent = GameObject.Find("DebugUIManager").transform;
debugUIObject.transform.localPosition = new Vector3(0.0f, 100.0f, 0.0f);
debugUIObject.transform.localEulerAngles = Vector3.zero;
debugUIObject.transform.localScale = new Vector3(1.0f, 1.0f, 1.0f);
// Print out for FPS
if (!string.IsNullOrEmpty(strFPS))
{
fps = VariableObjectManager(fps, "FPS", posY -= offsetY, strFPS, fontSize);
}
// Print out for IPD
if (!string.IsNullOrEmpty(strIPD))
{
ipd = VariableObjectManager(ipd, "IPD", posY -= offsetY, strIPD, fontSize);
}
// Print out for FOV
if (!string.IsNullOrEmpty(strFOV))
{
fov = VariableObjectManager(fov, "FOV", posY -= offsetY, strFOV, fontSize);
}
// Print out for Height
if (!string.IsNullOrEmpty(strHeight))
{
height = VariableObjectManager(height, "Height", posY -= offsetY, strHeight, fontSize);
}
// Print out for Depth
if (!string.IsNullOrEmpty(strDepth))
{
depth = VariableObjectManager(depth, "Depth", posY -= offsetY, strDepth, fontSize);
}
// Print out for Resoulution of Eye Texture
if (!string.IsNullOrEmpty(strResolutionEyeTexture))
{
resolutionEyeTexture = VariableObjectManager(resolutionEyeTexture, "Resolution", posY -= offsetY, strResolutionEyeTexture, fontSize);
}
// Print out for Latency
if (!string.IsNullOrEmpty(strLatencies))
{
latencies = VariableObjectManager(latencies, "Latency", posY -= offsetY, strLatencies, 17);
posY = 0.0f;
}
initUIComponent = false;
isInited = true;
}
/// <summary>
/// Update VR Variables
/// </summary>
void UpdateVariable()
{
UpdateIPD();
UpdateEyeHeightOffset();
UpdateEyeDepthOffset();
UpdateFOV();
UpdateResolutionEyeTexture();
UpdateLatencyValues();
UpdateFPS();
}
/// <summary>
/// Update Strings
/// </summary>
void UpdateStrings()
{
if (debugUIObject == null)
return;
if (!string.IsNullOrEmpty(strFPS))
fps.GetComponentInChildren<Text>().text = strFPS;
if (!string.IsNullOrEmpty(strIPD))
ipd.GetComponentInChildren<Text>().text = strIPD;
if (!string.IsNullOrEmpty(strFOV))
fov.GetComponentInChildren<Text>().text = strFOV;
if (!string.IsNullOrEmpty(strResolutionEyeTexture))
resolutionEyeTexture.GetComponentInChildren<Text>().text = strResolutionEyeTexture;
if (!string.IsNullOrEmpty(strLatencies))
{
latencies.GetComponentInChildren<Text>().text = strLatencies;
latencies.GetComponentInChildren<Text>().fontSize = 14;
}
if (!string.IsNullOrEmpty(strHeight))
height.GetComponentInChildren<Text>().text = strHeight;
if (!string.IsNullOrEmpty(strDepth))
depth.GetComponentInChildren<Text>().text = strDepth;
}
/// <summary>
/// It's for rift present GUI
/// </summary>
void RiftPresentGUI(GameObject guiMainOBj)
{
riftPresent = ComponentComposition(riftPresent);
riftPresent.transform.SetParent(guiMainOBj.transform);
riftPresent.name = "RiftPresent";
RectTransform rectTransform = riftPresent.GetComponent<RectTransform>();
rectTransform.localPosition = new Vector3(0.0f, 0.0f, 0.0f);
rectTransform.localScale = new Vector3(1.0f, 1.0f, 1.0f);
rectTransform.localEulerAngles = Vector3.zero;
Text text = riftPresent.GetComponentInChildren<Text>();
text.text = strRiftPresent;
text.fontSize = 20;
}
/// <summary>
/// Updates the device detection.
/// </summary>
void UpdateDeviceDetection()
{
if (riftPresentTimeout >= 0.0f)
{
riftPresentTimeout -= Time.deltaTime;
}
}
/// <summary>
/// Object Manager for Variables
/// </summary>
/// <returns> gameobject for each Variable </returns>
GameObject VariableObjectManager(GameObject gameObject, string name, float posY, string str, int fontSize)
{
gameObject = ComponentComposition(gameObject);
gameObject.name = name;
gameObject.transform.SetParent(debugUIObject.transform);
RectTransform rectTransform = gameObject.GetComponent<RectTransform>();
rectTransform.localPosition = new Vector3(0.0f, posY -= offsetY, 0.0f);
Text text = gameObject.GetComponentInChildren<Text>();
text.text = str;
text.fontSize = fontSize;
gameObject.transform.localEulerAngles = Vector3.zero;
rectTransform.localScale = new Vector3(1.0f, 1.0f, 1.0f);
return gameObject;
}
/// <summary>
/// Component composition
/// </summary>
/// <returns> Composed gameobject. </returns>
GameObject ComponentComposition(GameObject GO)
{
GO = new GameObject();
GO.AddComponent<RectTransform>();
GO.AddComponent<CanvasRenderer>();
GO.AddComponent<Image>();
GO.GetComponent<RectTransform>().sizeDelta = new Vector2(350f, 50f);
GO.GetComponent<Image>().color = new Color(7f / 255f, 45f / 255f, 71f / 255f, 200f / 255f);
texts = new GameObject();
texts.AddComponent<RectTransform>();
texts.AddComponent<CanvasRenderer>();
texts.AddComponent<Text>();
texts.GetComponent<RectTransform>().sizeDelta = new Vector2(350f, 50f);
texts.GetComponent<Text>().font = Resources.GetBuiltinResource(typeof(Font), "Arial.ttf") as Font;
texts.GetComponent<Text>().alignment = TextAnchor.MiddleCenter;
texts.transform.SetParent(GO.transform);
texts.name = "TextBox";
return GO;
}
#endregion
#region Debugging variables handler
/// <summary>
/// Updates the IPD.
/// </summary>
void UpdateIPD()
{
strIPD = System.String.Format("IPD (mm): {0:F4}", OVRManager.profile.ipd * 1000.0f);
}
/// <summary>
/// Updates the eye height offset.
/// </summary>
void UpdateEyeHeightOffset()
{
float eyeHeight = OVRManager.profile.eyeHeight;
strHeight = System.String.Format("Eye Height (m): {0:F3}", eyeHeight);
}
/// <summary>
/// Updates the eye depth offset.
/// </summary>
void UpdateEyeDepthOffset()
{
float eyeDepth = OVRManager.profile.eyeDepth;
strDepth = System.String.Format("Eye Depth (m): {0:F3}", eyeDepth);
}
/// <summary>
/// Updates the FOV.
/// </summary>
void UpdateFOV()
{
#if UNITY_2017_2_OR_NEWER
OVRDisplay.EyeRenderDesc eyeDesc = OVRManager.display.GetEyeRenderDesc(UnityEngine.XR.XRNode.LeftEye);
#else
OVRDisplay.EyeRenderDesc eyeDesc = OVRManager.display.GetEyeRenderDesc(UnityEngine.VR.VRNode.LeftEye);
#endif
strFOV = System.String.Format("FOV (deg): {0:F3}", eyeDesc.fov.y);
}
/// <summary>
/// Updates resolution of eye texture
/// </summary>
void UpdateResolutionEyeTexture()
{
#if UNITY_2017_2_OR_NEWER
OVRDisplay.EyeRenderDesc leftEyeDesc = OVRManager.display.GetEyeRenderDesc(UnityEngine.XR.XRNode.LeftEye);
OVRDisplay.EyeRenderDesc rightEyeDesc = OVRManager.display.GetEyeRenderDesc(UnityEngine.XR.XRNode.RightEye);
float scale = UnityEngine.XR.XRSettings.renderViewportScale;
#else
OVRDisplay.EyeRenderDesc leftEyeDesc = OVRManager.display.GetEyeRenderDesc(UnityEngine.VR.VRNode.LeftEye);
OVRDisplay.EyeRenderDesc rightEyeDesc = OVRManager.display.GetEyeRenderDesc(UnityEngine.VR.VRNode.RightEye);
float scale = UnityEngine.VR.VRSettings.renderViewportScale;
#endif
float w = (int)(scale * (float)(leftEyeDesc.resolution.x + rightEyeDesc.resolution.x));
float h = (int)(scale * (float)Mathf.Max(leftEyeDesc.resolution.y, rightEyeDesc.resolution.y));
strResolutionEyeTexture = System.String.Format("Resolution : {0} x {1}", w, h);
}
/// <summary>
/// Updates latency values
/// </summary>
void UpdateLatencyValues()
{
#if !UNITY_ANDROID || UNITY_EDITOR
OVRDisplay.LatencyData latency = OVRManager.display.latency;
if (latency.render < 0.000001f && latency.timeWarp < 0.000001f && latency.postPresent < 0.000001f)
strLatencies = System.String.Format("Latency values are not available.");
else
strLatencies = System.String.Format("Render: {0:F3} TimeWarp: {1:F3} Post-Present: {2:F3}\nRender Error: {3:F3} TimeWarp Error: {4:F3}",
latency.render,
latency.timeWarp,
latency.postPresent,
latency.renderError,
latency.timeWarpError);
#endif
}
/// <summary>
/// Updates the FPS.
/// </summary>
void UpdateFPS()
{
timeLeft -= Time.unscaledDeltaTime;
accum += Time.unscaledDeltaTime;
++frames;
// Interval ended - update GUI text and start new interval
if (timeLeft <= 0.0)
{
// display two fractional digits (f2 format)
float fps = frames / accum;
strFPS = System.String.Format("FPS: {0:F2}", fps);
timeLeft += updateInterval;
accum = 0.0f;
frames = 0;
}
}
#endregion
}
| |
/// QAS Pro Web > (c) Experian > www.edq.com
/// Intranet > Rapid Addressing > Standard > RapidBase
/// Provide common functionality and value transfer
namespace Experian.Qas.Prowebintegration
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using Experian.Qas.Proweb;
/// <summary>
/// Intranet > Rapid Addressing > Standard > RapidBase
/// This is the base class for the pages of the scenario
/// It provides common functionality and facilitates inter-page value passing through the ViewState.
/// </summary>
public class RapidBasePage : System.Web.UI.Page
{
/** Attributes & Constants **/
// Picklist history, stored in ViewState
protected HistoryStack m_aHistory = null;
// List of datamaps available on server
protected IList<Dataset> m_atDatasets = null;
private static IAddressLookup addressLookup = null;
// Store the state of the previous page
private RapidBasePage StoredPage = null;
// Filenames
private const string PAGE_SEARCH = "RapidSearch.aspx";
private const string PAGE_FORMAT = "RapidAddress.aspx";
// Viewstate names
protected const string FIELD_CALLBACK = "Callback";
private const string FIELD_ENGINE = "Engine";
private const string FIELD_HISTORY = "History";
private const string FIELD_WARNING = "Warning";
private const string FIELD_DATALIST = "Datalist";
// Select Box width constants
protected const int MAX_DATAMAP_NAME_LENGTH = 26;
protected const string SELECT_WIDTH = "16em";
// Enumerate operations that can be performed on a picklist item
protected enum Commands
{
/// <summary>
/// No hyperlink action - self-explanatory informational.
/// </summary>
None,
/// <summary>
/// Step in to sub-picklist.
/// </summary>
StepIn,
/// <summary>
/// Force-accept an unrecognized address.
/// </summary>
ForceFormat,
/// <summary>
/// Format into final address.
/// </summary>
Format,
/// <summary>
/// User must enter a value within the range shown.
/// </summary>
HaltRange,
/// <summary>
/// User must enter premise details.
/// </summary>
HaltIncomplete
}
// Enumerate the picklist item types (affects icon displayed)
protected enum Types
{
/// <summary>
/// Picklist item is an alias (synonym).
/// </summary>
Alias,
/// <summary>
/// Picklist item is an informational.
/// </summary>
Info,
/// <summary>
/// Picklist item is a warning informational.
/// </summary>
InfoWarn,
/// <summary>
/// Picklist item is a name/person.
/// </summary>
Name,
/// <summary>
/// Picklist item is a name alias (i.e. forename synonym).
/// </summary>
NameAlias,
/// <summary>
/// Picklist item is a PO Box grouping.
/// </summary>
POBox,
/// <summary>
/// Picklist item is standard.
/// </summary>
Standard
}
// Picklist step-in warnings (displayed on next page)
protected enum StepinWarnings
{
/// <summary>
/// No warning.
/// </summary>
None,
/// <summary>
/// Auto-stepped past close matches.
/// </summary>
CloseMatches,
/// <summary>
/// Stepped into cross-border match.
/// </summary>
CrossBorder,
/// <summary>
/// Force-format step-in performed.
/// </summary>
ForceAccept,
/// <summary>
/// Stepped into informational item (i.e. 'Click to Show All').
/// </summary>
Info,
/// <summary>
/// Address elements have overflowed the layout.
/// </summary>
Overflow,
/// <summary>
/// Stepped into postcode recode.
/// </summary>
PostcodeRecode,
/// <summary>
/// Address elements have been truncated by the layout.
/// </summary>
Truncate
}
#region properties
/// <summary>
/// Gets the Javascript function to call on completion
/// </summary>
protected string StoredCallback
{
get
{
return (string)ViewState[FIELD_CALLBACK];
}
set
{
ViewState[FIELD_CALLBACK] = value;
}
}
/// <summary>
/// Gets the country data identifier (i.e. AUS)
/// </summary>
protected string StoredDataID
{
get
{
return (string)ViewState[Constants.FIELD_DATA_ID];
}
set
{
ViewState[Constants.FIELD_DATA_ID] = value;
}
}
/// <summary>
/// Gets or sets the stored List of datamaps available on server.
/// </summary>
protected IList<Dataset> StoredDataMapList
{
get
{
return (IList<Dataset>)ViewState[FIELD_DATALIST];
}
set
{
ViewState[FIELD_DATALIST] = value;
}
}
/// <summary>
/// Gets or sets the additional address/error information.
/// </summary>
protected string StoredErrorInfo
{
get
{
return (string)ViewState[Constants.FIELD_ERROR_INFO];
}
set
{
ViewState[Constants.FIELD_ERROR_INFO] = value;
}
}
/// <summary>
/// Gets or sets the moniker of the address.
/// </summary>
protected string StoredMoniker
{
get
{
return (string)ViewState[Constants.FIELD_MONIKER];
}
set
{
ViewState[Constants.FIELD_MONIKER] = value;
}
}
/// <summary>
/// Gets or sets the how we arrived on the formatting page (i.e. pre-search check failed).
/// </summary>
protected Constants.Routes StoredRoute
{
get
{
object objValue = ViewState[Constants.FIELD_ROUTE];
return (objValue != null) ? (Constants.Routes)objValue : Constants.Routes.Undefined;
}
set
{
ViewState[Constants.FIELD_ROUTE] = value;
}
}
/// <summary>
/// Gets or sets the search engine selected.
/// </summary>
protected Engine.EngineTypes StoredSearchEngine
{
get
{
object objValue = ViewState[FIELD_ENGINE];
return (objValue != null) ? (Engine.EngineTypes)objValue : Engine.EngineTypes.Typedown;
}
set
{
ViewState[FIELD_ENGINE] = value;
}
}
/// <summary>
/// Gets or sets the step-in warning (i.e. Postcode has been recoded).
/// </summary>
protected StepinWarnings StoredWarning
{
get
{
object objValue = ViewState[FIELD_WARNING];
return (objValue != null) ? (StepinWarnings)objValue : StepinWarnings.None;
}
set
{
ViewState[FIELD_WARNING] = value;
}
}
#endregion
/** Base methods **/
/// <summary>
/// Pick up the preceding page, so we can access it's ViewState (see Stored properties section).
/// </summary>
virtual protected void Page_Load(object sender, System.EventArgs e)
{
if (!IsPostBack && (Context.Handler is RapidBasePage))
{
// Retrieve the state of the previous page, so it is available to us
StoredPage = Context.Handler as RapidBasePage;
StoredCallback = StoredPage.StoredCallback;
if (StoredCallback == null)
{
StoredCallback = Request[FIELD_CALLBACK];
}
StoredDataID = StoredPage.StoredDataID;
StoredSearchEngine = StoredPage.StoredSearchEngine;
StoredErrorInfo = StoredPage.StoredErrorInfo;
StoredMoniker = StoredPage.StoredMoniker;
StoredRoute = StoredPage.StoredRoute;
StoredWarning = StoredPage.StoredWarning;
StoredDataMapList = StoredPage.StoredDataMapList;
}
else
{
// Point stored page to us, as we are the previous page
StoredPage = this;
}
// Pick up history, passed around in viewstate
m_aHistory = StoredPage.GetStoredHistory();
}
/// <summary>
/// Store the history back to the view state prior to rendering.
/// </summary>
/// <returns>object</returns>
protected override object SaveViewState()
{
SetStoredHistory(m_aHistory);
return base.SaveViewState();
}
/// <summary>
/// Gets Picklist history.
/// </summary>
/// <returns>HistoryStack</returns>
protected HistoryStack GetStoredHistory()
{
object objValue = ViewState[FIELD_HISTORY];
if (objValue is ArrayList)
{
HistoryStack stack = new HistoryStack((ArrayList)objValue);
return stack;
}
return new HistoryStack();
}
/** Common methods **/
/// <summary>
/// Gets the QAS service, connected to the configured server
/// Singleton pattern: maintain a single instance, created only on demand.
/// </summary>
protected IAddressLookup AddressLookup
{
get
{
if (addressLookup == null)
{
// Create QAS search object
addressLookup = QAS.GetSearchService();
}
return addressLookup;
}
}
/// <summary>
/// Get the layout from the config file.
/// </summary>
/// <returns>string</returns>
protected string GetLayout()
{
string sLayout;
string sDataID = StoredDataID;
// Look for a layout specific to this datamap
sLayout = System.Configuration.ConfigurationManager.AppSettings[Constants.KEY_LAYOUT + "." + sDataID];
if (sLayout == null || sLayout == string.Empty)
{
// No layout found specific to this datamap - try the default
sLayout = System.Configuration.ConfigurationManager.AppSettings[Constants.KEY_LAYOUT];
}
return sLayout;
}
/// <summary>
/// Transfer to the address searching and picklist display page.
/// </summary>
/// <param name="sDataID">string</param>
/// <param name="eEngine">QAS.EngineTypes</param>
protected void GoSearchPage(string sDataID, Engine.EngineTypes eEngine)
{
// Store values back to the view state
StoredPage.StoredDataID = sDataID;
StoredPage.SetStoredHistory(m_aHistory);
StoredPage.StoredSearchEngine = eEngine;
Server.Transfer(PAGE_SEARCH);
}
/// <summary>
/// Transfer to the address confirmation page to retrieve the found address.
/// </summary>
/// <param name="sDataID">string</param>
/// <param name="eEngine">EngineTypes</param>
/// <param name="sMoniker">string</param>
/// <param name="eWarn">StepinWarnings</param>
protected void GoFormatPage(string sDataID, Engine.EngineTypes eEngine, string sMoniker, StepinWarnings eWarn)
{
// Store values back to the view state
StoredPage.StoredDataID = sDataID;
StoredPage.StoredMoniker = sMoniker;
StoredPage.SetStoredHistory(m_aHistory);
StoredPage.StoredRoute = Constants.Routes.Okay;
StoredPage.StoredSearchEngine = eEngine;
StoredPage.StoredWarning = eWarn;
Server.Transfer(PAGE_FORMAT);
}
/// <summary>
/// Transfer to the address confirmation page for manual address entry, after capture failure.
/// </summary>
/// <param name="route">Constants.Routes</param>
/// <param name="sReason">string</param>
protected void GoErrorPage(Constants.Routes route, string sReason)
{
StoredPage.StoredErrorInfo = sReason;
StoredPage.StoredRoute = route;
Server.Transfer(PAGE_FORMAT);
}
/// <summary>
/// Transfer to the address confirmation page for manual address entry, after exception thrown.
/// </summary>
/// <param name="x">Exception</param>
protected void GoErrorPage(Exception x)
{
StoredPage.StoredErrorInfo = x.Message;
StoredPage.StoredRoute = Constants.Routes.Failed;
Server.Transfer(PAGE_FORMAT);
}
/** Page display **/
/// <summary>
/// Write out picklist HTML and associated action array to Javascript variables
/// This is included in two distinct places:
/// - main searching page, for whole page updating
/// - picklist results frame, for dynamic picklist updating
/// The picklist picks up and uses the values from the appropriate place.
/// </summary>
/// <param name="picklist">Picklist</param>
/// <param name="sDepth">string</param>
protected void RenderPicklistData(Picklist picklist, string sDepth)
{
if (picklist == null)
{
// No picklist in this context: write out empty values
Response.Write("var sPicklistHTML = '';\n");
Response.Write("var asActions = new Array();");
}
else
{
// Build sActions into a string, while writing picklistHTML out to Response
StringBuilder sActions = new StringBuilder();
// Build picklist HTML into JavaScript string
// - icon, operation, display text, hover text, postcode, score
Response.Write("var sPicklistHTML = \"<table class='picklist indent" + sDepth + "'>\\\n");
int index = 0;
foreach (PicklistItem item in picklist.PicklistItems)
{
// Step-in warning
StepinWarnings eWarn = StepinWarnings.None;
if (item.IsCrossBorderMatch)
{
eWarn = StepinWarnings.CrossBorder;
}
else if (item.IsPostcodeRecoded)
{
eWarn = StepinWarnings.PostcodeRecode;
}
// Commands: what to do if they click on the item
Commands eCmd = Commands.None;
if (item.CanStep)
{
eCmd = Commands.StepIn;
}
else if (item.IsFullAddress)
{
eCmd = item.IsInformation ? Commands.ForceFormat : Commands.Format;
}
else if (item.IsUnresolvableRange)
{
eCmd = Commands.HaltRange;
}
else if (item.IsIncompleteAddress)
{
eCmd = Commands.HaltIncomplete;
}
// Type: indicates the type of icon to display (used in combination with the operation)
Types eType = Types.Standard;
if (item.IsInformation)
{
eType = item.IsWarnInformation ? Types.InfoWarn : Types.Info;
eWarn = StepinWarnings.Info;
}
else if (item.IsDummyPOBox)
{
eType = Types.POBox;
}
else if (item.IsName)
{
eType = item.IsAliasMatch ? Types.NameAlias : Types.Name;
}
else if (item.IsAliasMatch || item.IsCrossBorderMatch || item.IsPostcodeRecoded)
{
eType = Types.Alias;
}
// Start building HTML
// Set the class depending on the function & type -> displayed icon
string sClass = "stop";
if (eCmd == Commands.StepIn)
{
if (eType == Types.Alias)
{
sClass = "aliasStep";
}
else if (eType == Types.Info)
{
sClass = "infoStep";
}
else if (eType == Types.POBox)
{
sClass = "pobox";
}
else
{
sClass = "stepIn";
}
}
else if (eCmd == Commands.Format)
{
if (eType == Types.Alias)
{
sClass = "alias";
}
else if (eType == Types.Name)
{
sClass = "name";
}
else if (eType == Types.NameAlias)
{
sClass = "nameAlias";
}
else
{
sClass = "format";
}
}
else if ((eCmd == Commands.HaltIncomplete) || (eCmd == Commands.HaltRange))
{
sClass = "halt";
}
else if (eType == Types.Info)
{
sClass = "info";
}
if (index == 0)
{
sClass += " first";
}
if (item.IsSubsidiaryData)
{
sClass += " sub";
}
// Hyperlink
string sAnchorStart = string.Empty, sAnchorEnd = string.Empty;
if (item.Text != null && eCmd != Commands.None)
{
sAnchorStart = "<a href='javascript:action(" + index.ToString() + ");' "
+ "tabindex='" + (index + 1) + "' "
+ "title=\\\"" + JavascriptEncode(item.Text) + "\\\">";
sAnchorEnd = "</a>";
}
string sScore = (item.Score > 0) ? item.Score + "%" : string.Empty;
// Write out HTML
Response.Write("<tr>");
Response.Write("<td class='pickitem " + sClass + "'>" + sAnchorStart + "<div>");
Response.Write(JavascriptEncode(Server.HtmlEncode(item.Text)) + "</div>" + sAnchorEnd + "</td>");
if (item.Postcode == null)
{
Response.Write("<td class='postcode'></td>");
}
else
{
Response.Write("<td class='postcode'>" + JavascriptEncode(Server.HtmlEncode(item.Postcode)) + "</td>");
}
Response.Write("<td class='score'>" + sScore + "</td>");
Response.Write("</tr>\\\n");
// Picklist actions - javascript array variable
sActions.Append("'" + (eCmd != Commands.None ? eCmd.ToString() : string.Empty));
switch (eCmd)
{
case Commands.StepIn:
sActions.Append("(\"" + item.Moniker + "\",\"" + JavascriptEncode(Server.HtmlEncode(item.Text)) + "\",");
sActions.Append("\"" + item.Postcode + "\",\"" + item.ScoreAsString + "\",\"" + eWarn.ToString() + "\")");
break;
case Commands.Format:
sActions.Append("(\"" + item.Moniker + "\",\"" + eWarn.ToString() + "\")");
break;
case Commands.ForceFormat:
sActions.Append("(\"" + item.Moniker + "\")");
break;
case Commands.HaltIncomplete:
case Commands.HaltRange:
sActions.Append("()");
break;
}
sActions.Append("',");
index++;
}
// Close off picklist HTML
Response.Write("</table>\";\n");
// Write out Actions
Response.Write("var asActions = new Array(");
Response.Write(sActions.ToString());
Response.Write("'');\n");
}
}
/// <summary>
/// Method override: Use picklist history in order to work out indent depth.
/// </summary>
/// <param name="picklist">Picklist</param>
protected void RenderPicklistData(Picklist picklist)
{
RenderPicklistData(picklist, m_aHistory.Count.ToString());
}
/// <summary>
/// Encode the string so it's value is correct when used as a Javascript string
/// i.e. Jack's "friendly" dog -> Jack\'s \"friendly\" dog.
/// </summary>
/// <param name="str">Plain text string to encode.</param>
/// <returns>String with special characters escaped.</returns>
protected string JavascriptEncode(string str)
{
return str.Replace("\\", "\\\\").Replace("'", "\\'").Replace("\"", "\\\"");
}
/// <summary>
/// Picklist history, set.
/// </summary>
/// <param name="value">HistoryStack</param>
protected void SetStoredHistory(HistoryStack value)
{
ViewState[FIELD_HISTORY] = value;
}
/** Support classes: Picklist history **/
/// <summary>
/// Helper class: stack of all the search picklists we've stepped through
/// Implemented using an ArrayList so we can enumerate forwards through them for display,
/// the 'bottom' of the stack is element 0, the 'top' is element Count - 1, where items are pushed and popped.
/// </summary>
[Serializable]
protected class HistoryStack : ArrayList
{
/// <summary>
/// Initialises a new instance of the class using default values for members (Default constructor)
/// </summary>
public HistoryStack()
{
}
/// <summary>
/// Initialises a new instance of HistryItem(s) (Construct from an ArrayList)
/// </summary>
/// <param name="vValue">ArrayList</param>
public HistoryStack(ArrayList vValue)
{
foreach (object obj in vValue)
{
base.Add((HistoryItem)obj);
}
}
/// <summary>
/// Gets or sets the element at the specified index
/// </summary>
/// <param name="iIndex">int</param>
/// <returns>HistoryItem</returns>
public new HistoryItem this[int iIndex]
{
get
{
return (HistoryItem)base[iIndex];
}
set
{
base[iIndex] = value;
}
}
/// <summary>
/// Inserts an object at the top of the stack: prevents duplicates
/// </summary>
/// <param name="item">HistoryItem</param>
public void Add(HistoryItem item)
{
if (Count == 0 || !Peek().Moniker.Equals(item.Moniker))
{
base.Add(item);
}
}
/// <summary>
/// Returns the object at the top of the stack without removing it
/// </summary>
/// <returns></returns>
public HistoryItem Peek()
{
return (HistoryItem)this[Count - 1];
}
/// <summary>
/// Removes and returns the object at the top of the stack
/// </summary>
/// <returns>HistoryItem</returns>
public HistoryItem Pop()
{
HistoryItem tail = Peek();
RemoveAt(Count - 1);
return tail;
}
/// <summary>
/// Inserts an object at the top of the stack
/// </summary>
/// <param name="sMoniker">string</param>
/// <param name="sText">string</param>
/// <param name="sPostcode">string</param>
/// <param name="sScore">string</param>
/// <param name="sRefine">string</param>
public void Push(string sMoniker, string sText, string sPostcode, string sScore, string sRefine)
{
HistoryItem item = new HistoryItem(sMoniker, sText, sPostcode, sScore, sRefine);
Add(item);
}
/// <summary>
/// Inserts an object at the top of the stack
/// </summary>
/// <param name="item">PicklistItem</param>
public void Push(PicklistItem item)
{
Push(item.Moniker, item.Text, item.Postcode, item.ScoreAsString, string.Empty);
}
/// <summary>
/// Truncate the stack down to a certain size
/// </summary>
/// <param name="iCount">int</param>
public void Truncate(int iCount)
{
if (Count > iCount)
{
RemoveRange(iCount, Count - iCount);
}
}
}
/// <summary>
/// Helper class: stores details of search picklists visited.
/// </summary>
[Serializable]
protected class HistoryItem
{
public string Moniker = string.Empty;
public string Text = string.Empty;
public string Postcode = string.Empty;
public string Score = string.Empty;
public string Refine = string.Empty;
public HistoryItem(string sMonikerIn, string sTextIn, string sPostcodeIn, string sScoreIn, string sRefineIn)
{
Moniker = sMonikerIn;
Text = sTextIn;
Postcode = sPostcodeIn;
Score = sScoreIn;
Refine = sRefineIn;
}
}
}
}
| |
// Copyright (c) 2015 fjz13. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#region Fast Binary format
/*
.----------.--------------. .----------.---------.
struct hierarchy | struct | BT_STOP_BASE |...| struct | BT_STOP |
'----------'--------------' '----------'---------'
.----------.----------. .----------.
struct | field | field |...| field |
'----------'----------' '----------'
.------.----.----------.
field | type | id | value |
'------'----'----------'
.---.---.---.---.---.---.---.---. i - id bits
type | 0 | 0 | 0 | t | t | t | t | t | t - type bits
'---'---'---'---'---'---'---'---' v - value bits
4 0
id .---. .---.---. .---.
| i |...| i | i |...| i |
'---' '---'---' '---'
7 0 15 8
.---.---.---.---.---.---.---.---.
value bool | | | | | | | | v |
'---'---'---'---'---'---'---'---'
0
integer, little endian
float, double
.-------.------------.
string, wstring | count | characters |
'-------'------------'
count variable uint32 count of 1-byte or 2-byte characters
characters 1-byte or 2-byte characters
.-------.-------.-------.
blob, list, set, | type | count | items |
vector, nullable '-------'-------'-------'
.---.---.---.---.---.---.---.---.
type | | | | t | t | t | t | t |
'---'---'---'---'---'---'---'---'
4 0
count variable uint32 count of items
items each item encoded according to its type
.----------.------------.-------.-----.-------.
map | key type | value type | count | key | value |
'----------'------------'-------'-----'-------'
.---.---.---.---.---.---.---.---.
key type, | | | | t | t | t | t | t |
value type '---'---'---'---'---'---'---'---'
4 0
count variable encoded uint32 count of {key,mapped} pairs
key, mapped each item encoded according to its type
variable uint32
.---.---. .---..---.---. .---..---.---. .---..---.---. .---..---.---.---.---. .---.
| 1 | v |...| v || 1 | v |...| v || 1 | v |...| v || 1 | v |...| v || 0 | 0 | 0 | v |...| v |
'---'---' '---''---'---' '---''---'---' '---''---'---' '---''---'---'---'---' '---'
6 0 13 7 20 14 27 21 31 28
1 to 5 bytes, high bit of every byte indicates if there is another byte
*/
#endregion
namespace Bond.Protocols
{
using System;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text;
using Bond.IO;
/// <summary>
/// Writer for the Fast Binary tagged protocol
/// </summary>
/// <typeparam name="O">Implemention of IOutputStream interface</typeparam>
[Reader(typeof(FastBinaryReader<>))]
public struct FastBinaryWriter<O> : IProtocolWriter
where O : IOutputStream
{
const ushort Magic = (ushort)ProtocolType.FAST_PROTOCOL;
readonly O output;
readonly ushort version;
/// <summary>
/// Create an instance of FastBinaryWriter
/// </summary>
/// <param name="output">Serialized payload output</param>
/// <param name="version">Protocol version</param>
public FastBinaryWriter(O output, ushort version = 1)
{
this.output = output;
this.version = version;
}
/// <summary>
/// Write protocol magic number and version
/// </summary>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteVersion()
{
output.WriteUInt16(Magic);
output.WriteUInt16(version);
}
#region Complex types
/// <summary>
/// Start writing a struct
/// </summary>
/// <param name="metadata">Schema metadata</param>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteStructBegin(Metadata metadata)
{}
/// <summary>
/// Start writing a base struct
/// </summary>
/// <param name="metadata">Base schema metadata</param>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteBaseBegin(Metadata metadata)
{}
/// <summary>
/// End writing a struct
/// </summary>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteStructEnd()
{
output.WriteUInt8((Byte)BondDataType.BT_STOP);
}
/// <summary>
/// End writing a base struct
/// </summary>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteBaseEnd()
{
output.WriteUInt8((Byte)BondDataType.BT_STOP_BASE);
}
/// <summary>
/// Start writing a field
/// </summary>
/// <param name="type">Type of the field</param>
/// <param name="id">Identifier of the field</param>
/// <param name="metadata">Metadata of the field</param>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteFieldBegin(BondDataType type, ushort id, Metadata metadata)
{
output.WriteUInt8((byte) type);
output.WriteUInt16(id);
}
/// <summary>
/// Indicate that field was omitted because it was set to its default value
/// </summary>
/// <param name="dataType">Type of the field</param>
/// <param name="id">Identifier of the field</param>
/// <param name="metadata">Metadata of the field</param>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteFieldOmitted(BondDataType dataType, ushort id, Metadata metadata)
{}
/// <summary>
/// End writing a field
/// </summary>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteFieldEnd()
{}
/// <summary>
/// Start writing a list or set container
/// </summary>
/// <param name="count">Number of elements in the container</param>
/// <param name="elementType">Type of the elements</param>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteContainerBegin(int count, BondDataType elementType)
{
output.WriteUInt8((byte)elementType);
output.WriteVarUInt32((uint)count);
}
/// <summary>
/// Start writing a map container
/// </summary>
/// <param name="count">Number of elements in the container</param>
/// <param name="keyType">Type of the keys</param>
/// /// <param name="valueType">Type of the values</param>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteContainerBegin(int count, BondDataType keyType, BondDataType valueType)
{
output.WriteUInt8((byte)keyType);
output.WriteUInt8((byte)valueType);
output.WriteVarUInt32((uint)count);
}
/// <summary>
/// End writing a container
/// </summary>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteContainerEnd()
{}
/// <summary>
/// Write array of bytes verbatim
/// </summary>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteBytes(ArraySegment<byte> data)
{
output.WriteBytes(data);
}
#endregion
#region Primitive types
/// <summary>
/// Write an UInt8
/// </summary>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteUInt8(Byte value)
{
output.WriteUInt8(value);
}
/// <summary>
/// Write an UInt16
/// </summary>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteUInt16(UInt16 value)
{
output.WriteUInt16(value);
}
/// <summary>
/// Write an UInt16
/// </summary>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteUInt32(UInt32 value)
{
output.WriteUInt32(value);
}
/// <summary>
/// Write an UInt64
/// </summary>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteUInt64(UInt64 value)
{
output.WriteUInt64(value);
}
/// <summary>
/// Write an Int8
/// </summary>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteInt8(SByte value)
{
output.WriteUInt8((Byte)value);
}
/// <summary>
/// Write an Int16
/// </summary>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteInt16(Int16 value)
{
output.WriteUInt16((ushort)value);
}
/// <summary>
/// Write an Int32
/// </summary>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteInt32(Int32 value)
{
output.WriteUInt32((uint)value);
}
/// <summary>
/// Write an Int64
/// </summary>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteInt64(Int64 value)
{
output.WriteUInt64((ulong)value);
}
/// <summary>
/// Write a float
/// </summary>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteFloat(float value)
{
output.WriteFloat(value);
}
/// <summary>
/// Write a double
/// </summary>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteDouble(double value)
{
output.WriteDouble(value);
}
/// <summary>
/// Write a bool
/// </summary>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteBool(bool value)
{
output.WriteUInt8((byte)(value ? 1 : 0));
}
/// <summary>
/// Write a UTF-8 string
/// </summary>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteString(string value)
{
if (value.Length == 0)
{
output.WriteVarUInt32(0);
}
else
{
var size = Encoding.UTF8.GetByteCount(value);
output.WriteVarUInt32((UInt32)size);
output.WriteString(Encoding.UTF8, value, size);
}
}
/// <summary>
/// Write a UTF-16 string
/// </summary>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteWString(string value)
{
if (value.Length == 0)
{
output.WriteVarUInt32(0);
}
else
{
output.WriteVarUInt32((UInt32)value.Length);
output.WriteString(Encoding.Unicode, value, value.Length << 1);
}
}
#endregion
}
/// <summary>
/// Reader for the Fast Binary tagged protocol
/// </summary>
/// <typeparam name="I">Implemention of IInputStream interface</typeparam>
public struct FastBinaryReader<I> : ITaggedProtocolReader, ICloneable<FastBinaryReader<I>>
where I : IInputStream, ICloneable<I>
{
readonly I input;
/// <summary>
/// Create an instance of FastBinaryReader
/// </summary>
/// <param name="input">Input payload</param>
/// <param name="version">Protocol version</param>
public FastBinaryReader(I input, ushort version = 1)
{
this.input = input;
}
/// <summary>
/// Clone the reader
/// </summary>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public FastBinaryReader<I> Clone()
{
return new FastBinaryReader<I>(input.Clone());
}
#region Complex types
/// <summary>
/// Start reading a struct
/// </summary>
/// <exception cref="EndOfStreamException"/>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void ReadStructBegin()
{ }
/// <summary>
/// Start reading a base of a struct
/// </summary>
/// <exception cref="EndOfStreamException"/>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void ReadBaseBegin()
{ }
/// <summary>
/// End reading a struct
/// </summary>
/// <exception cref="EndOfStreamException"/>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void ReadStructEnd()
{ }
/// <summary>
/// End reading a base of a struct
/// </summary>
/// <exception cref="EndOfStreamException"/>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void ReadBaseEnd()
{ }
/// <summary>
/// Start reading a field
/// </summary>
/// <param name="type">An out parameter set to the field type
/// or BT_STOP/BT_STOP_BASE if there is no more fields in current struct/base</param>
/// <param name="id">Out parameter set to the field identifier</param>
/// <exception cref="EndOfStreamException"/>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void ReadFieldBegin(out BondDataType type, out ushort id)
{
type = (BondDataType)input.ReadUInt8();
if (type != BondDataType.BT_STOP && type != BondDataType.BT_STOP_BASE)
id = input.ReadUInt16();
else
id = 0;
}
/// <summary>
/// End reading a field
/// </summary>
/// <exception cref="EndOfStreamException"/>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void ReadFieldEnd()
{ }
/// <summary>
/// Start reading a list or set container
/// </summary>
/// <param name="count">An out parameter set to number of items in the container</param>
/// <param name="elementType">An out parameter set to type of container elements</param>
/// <exception cref="EndOfStreamException"/>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void ReadContainerBegin(out int count, out BondDataType elementType)
{
elementType = (BondDataType)input.ReadUInt8();
count = (int)input.ReadVarUInt32();
}
/// <summary>
/// Start reading a map container
/// </summary>
/// <param name="count">An out parameter set to number of items in the container</param>
/// <param name="keyType">An out parameter set to the type of map keys</param>
/// <param name="valueType">An out parameter set to the type of map values</param>
/// <exception cref="EndOfStreamException"/>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void ReadContainerBegin(out int count, out BondDataType keyType, out BondDataType valueType)
{
keyType = (BondDataType)input.ReadUInt8();
valueType = (BondDataType)input.ReadUInt8();
count = (int)input.ReadVarUInt32();
}
/// <summary>
/// End reading a container
/// </summary>
/// <exception cref="EndOfStreamException"/>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void ReadContainerEnd()
{ }
#endregion
#region Primitive types
/// <summary>
/// Read an UInt8
/// </summary>
/// <exception cref="EndOfStreamException"/>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public byte ReadUInt8()
{
return input.ReadUInt8();
}
/// <summary>
/// Read an UInt16
/// </summary>
/// <exception cref="EndOfStreamException"/>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public ushort ReadUInt16()
{
return input.ReadUInt16();
}
/// <summary>
/// Read an UInt32
/// </summary>
/// <exception cref="EndOfStreamException"/>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public uint ReadUInt32()
{
return input.ReadUInt32();
}
/// <summary>
/// Read an UInt64
/// </summary>
/// <exception cref="EndOfStreamException"/>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public UInt64 ReadUInt64()
{
return input.ReadUInt64();
}
/// <summary>
/// Read an Int8
/// </summary>
/// <exception cref="EndOfStreamException"/>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public sbyte ReadInt8()
{
return (sbyte)input.ReadUInt8();
}
/// <summary>
/// Read an Int16
/// </summary>
/// <exception cref="EndOfStreamException"/>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public short ReadInt16()
{
return (short)input.ReadUInt16();
}
/// <summary>
/// Read an Int32
/// </summary>
/// <exception cref="EndOfStreamException"/>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public int ReadInt32()
{
return (int)input.ReadUInt32();
}
/// <summary>
/// Read an Int64
/// </summary>
/// <exception cref="EndOfStreamException"/>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public long ReadInt64()
{
return (long)input.ReadUInt64();
}
/// <summary>
/// Read a bool
/// </summary>
/// <exception cref="EndOfStreamException"/>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public bool ReadBool()
{
return input.ReadUInt8() != 0;
}
/// <summary>
/// Read a float
/// </summary>
/// <exception cref="EndOfStreamException"/>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public float ReadFloat()
{
return input.ReadFloat();
}
/// <summary>
/// Read a double
/// </summary>
/// <exception cref="EndOfStreamException"/>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public double ReadDouble()
{
return input.ReadDouble();
}
/// <summary>
/// Read a UTF-8 string
/// </summary>
/// <exception cref="EndOfStreamException"/>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public String ReadString()
{
var length = (int)input.ReadVarUInt32();
return length == 0 ? string.Empty : input.ReadString(Encoding.UTF8, length);
}
/// <summary>
/// Read a UTF-16 string
/// </summary>
/// <exception cref="EndOfStreamException"/>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public string ReadWString()
{
var length = (int)input.ReadVarUInt32();
return length == 0 ? string.Empty : input.ReadString(Encoding.Unicode, length << 1);
}
/// <summary>
/// Read an array of bytes verbatim
/// </summary>
/// <param name="count">Number of bytes to read</param>
/// <exception cref="EndOfStreamException"/>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public ArraySegment<byte> ReadBytes(int count)
{
return input.ReadBytes(count);
}
#endregion
#region Skip
/// <summary>
/// Skip a value of specified type
/// </summary>
/// <param name="type">Type of the value to skip</param>
/// <exception cref="EndOfStreamException"/>
public void Skip(BondDataType type)
{
switch (type)
{
case (BondDataType.BT_BOOL):
case (BondDataType.BT_UINT8):
case (BondDataType.BT_INT8):
input.SkipBytes(sizeof(byte));
break;
case (BondDataType.BT_UINT16):
case (BondDataType.BT_INT16):
input.SkipBytes(sizeof(ushort));
break;
case (BondDataType.BT_UINT32):
case (BondDataType.BT_INT32):
input.SkipBytes(sizeof(uint));
break;
case (BondDataType.BT_FLOAT):
input.SkipBytes(sizeof(float));
break;
case (BondDataType.BT_DOUBLE):
input.SkipBytes(sizeof(double));
break;
case (BondDataType.BT_UINT64):
case (BondDataType.BT_INT64):
input.SkipBytes(sizeof(ulong));
break;
case (BondDataType.BT_STRING):
input.SkipBytes((int)input.ReadVarUInt32());
break;
case (BondDataType.BT_WSTRING):
input.SkipBytes((int)(input.ReadVarUInt32() << 1));
break;
case BondDataType.BT_LIST:
case BondDataType.BT_SET:
SkipContainer();
break;
case BondDataType.BT_MAP:
SkipMap();
break;
case BondDataType.BT_STRUCT:
SkipStruct();
break;
default:
Throw.InvalidBondDataType(type);
break;
}
}
void SkipContainer()
{
BondDataType elementType;
int count;
ReadContainerBegin(out count, out elementType);
switch (elementType)
{
case BondDataType.BT_BOOL:
case BondDataType.BT_INT8:
case BondDataType.BT_UINT8:
input.SkipBytes(count);
break;
case (BondDataType.BT_UINT16):
case (BondDataType.BT_INT16):
input.SkipBytes(count * sizeof(ushort));
break;
case (BondDataType.BT_UINT32):
case (BondDataType.BT_INT32):
input.SkipBytes(count * sizeof(uint));
break;
case (BondDataType.BT_UINT64):
case (BondDataType.BT_INT64):
input.SkipBytes(count * sizeof(ulong));
break;
case BondDataType.BT_FLOAT:
input.SkipBytes(count * sizeof(float));
break;
case BondDataType.BT_DOUBLE:
input.SkipBytes(count * sizeof(double));
break;
default:
while (0 <= --count)
{
Skip(elementType);
}
break;
}
}
void SkipMap()
{
BondDataType keyType;
BondDataType valueType;
int count;
ReadContainerBegin(out count, out keyType, out valueType);
while (0 <= --count)
{
Skip(keyType);
Skip(valueType);
}
}
void SkipStruct()
{
while (true)
{
BondDataType type;
ushort id;
ReadFieldBegin(out type, out id);
if (type == BondDataType.BT_STOP_BASE) continue;
if (type == BondDataType.BT_STOP) break;
Skip(type);
}
}
#endregion
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Omnius.Base;
using Omnius.Collections;
namespace Omnius.Security
{
public class Miner
{
private CashAlgorithm _cashAlgorithm;
private int _limit;
private TimeSpan _computingTime;
public Miner(CashAlgorithm cashAlgorithm, int limit, TimeSpan computingTime)
{
_cashAlgorithm = cashAlgorithm;
_limit = limit;
_computingTime = computingTime;
}
public CashAlgorithm CashAlgorithm
{
get
{
return _cashAlgorithm;
}
}
public int Limit
{
get
{
return _limit;
}
}
public TimeSpan ComputingTime
{
get
{
return _computingTime;
}
}
public Task<Cash> Create(Stream stream, CancellationToken token)
{
if (stream == null) throw new ArgumentNullException(nameof(stream));
return Task.Run(() =>
{
if (this.Limit <= 0 && this.ComputingTime <= TimeSpan.Zero) return null;
if (this.CashAlgorithm == CashAlgorithm.Version1)
{
var minerUtils = new MinerUtils();
using (token.Register(() => minerUtils.Cancel()))
{
var key = minerUtils.Create_1(Sha256.Compute(stream), this.Limit, this.ComputingTime);
return new Cash(CashAlgorithm.Version1, key);
}
}
return null;
}, token);
}
public static Cost Verify(Cash cash, Stream stream)
{
if (cash == null) return null;
if (stream == null) throw new ArgumentNullException(nameof(stream));
if (cash.CashAlgorithm == CashAlgorithm.Version1)
{
var minerUtils = new MinerUtils();
return new Cost(cash.CashAlgorithm, minerUtils.Verify_1(cash.Key, Sha256.Compute(stream)));
}
return null;
}
private class MinerUtils
{
private static string _path;
static MinerUtils()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
if (Environment.Is64BitProcess)
{
_path = "Assemblies/Hashcash_x64.exe";
}
else
{
_path = "Assemblies/Hashcash_x86.exe";
}
}
else
{
throw new NotSupportedException();
}
}
private List<Process> _processes = new List<Process>();
private readonly object _lockObject = new object();
public byte[] Create_1(byte[] value, int limit, TimeSpan computationTime)
{
if (value == null) throw new ArgumentNullException(nameof(value));
if (value.Length != 32) throw new ArgumentOutOfRangeException(nameof(value));
var info = new ProcessStartInfo(_path);
info.CreateNoWindow = true;
info.UseShellExecute = false;
info.RedirectStandardOutput = true;
{
if (limit < 0) limit = -1;
int timeout;
if (computationTime < TimeSpan.Zero) timeout = -1;
else timeout = (int)computationTime.TotalSeconds;
info.Arguments = string.Format(
"hashcash1 create {0} {1} {2}",
NetworkConverter.ToHexString(value),
limit,
timeout);
}
using (var process = Process.Start(info))
{
process.PriorityClass = ProcessPriorityClass.Idle;
lock (_lockObject)
{
_processes.Add(process);
}
try
{
process.PriorityClass = ProcessPriorityClass.Idle;
try
{
string result = process.StandardOutput.ReadLine();
process.WaitForExit();
if (process.ExitCode != 0) throw new MinerException();
return NetworkConverter.FromHexString(result);
}
catch (MinerException)
{
throw;
}
catch (Exception e)
{
throw new MinerException(e.Message, e);
}
}
finally
{
lock (_lockObject)
{
_processes.Remove(process);
}
}
}
}
public int Verify_1(byte[] key, byte[] value)
{
if (key == null) throw new ArgumentNullException(nameof(key));
if (key.Length != 32) throw new ArgumentOutOfRangeException(nameof(key));
if (value == null) throw new ArgumentNullException(nameof(value));
if (value.Length != 32) throw new ArgumentOutOfRangeException(nameof(value));
var bufferManager = BufferManager.Instance;
try
{
byte[] result;
{
using (var safeBuffer = bufferManager.CreateSafeBuffer(64))
{
Unsafe.Copy(key, 0, safeBuffer.Value, 0, 32);
Unsafe.Copy(value, 0, safeBuffer.Value, 32, 32);
result = Sha256.Compute(safeBuffer.Value, 0, 64);
}
}
int count = 0;
for (int i = 0; i < 32; i++)
{
for (int j = 0; j < 8; j++)
{
if (((result[i] << j) & 0x80) == 0) count++;
else goto End;
}
}
End:
return count;
}
catch (Exception)
{
return 0;
}
}
public void Cancel()
{
lock (_lockObject)
{
foreach (var process in _processes.ToArray())
{
try
{
process.Kill();
}
catch (Exception)
{
}
}
_processes.Clear();
}
}
}
}
public class MinerException : Exception
{
public MinerException() : base() { }
public MinerException(string message) : base(message) { }
public MinerException(string message, Exception innerException) : base(message, innerException) { }
}
}
| |
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace Nest
{
[JsonConverter(typeof(AttachmentConverter))]
public class Attachment
{
/// <summary>
/// The author.
/// </summary>
[JsonProperty("author")]
public string Author { get; set; }
/// <summary>
/// The base64 encoded content. Can be explicitly set
/// </summary>
[JsonProperty("content")]
public string Content { get; set; }
/// <summary>
/// The length of the content before text extraction.
/// </summary>
[JsonProperty("content_length")]
public long? ContentLength { get; set; }
/// <summary>
/// The content type of the attachment. Can be explicitly set
/// </summary>
[JsonProperty("content_type")]
public string ContentType { get; set; }
/// <summary>
/// The date of the attachment.
/// </summary>
[JsonProperty("date")]
public DateTime? Date { get; set; }
/// <summary>
/// The keywords in the attachment.
/// </summary>
[JsonProperty("keywords")]
public string Keywords { get; set; }
/// <summary>
/// The language of the attachment. Can be explicitly set.
/// </summary>
[JsonProperty("language")]
public string Language { get; set; }
/// <summary>
/// Detect the language of the attachment. Language detection is
/// disabled by default.
/// </summary>
[JsonProperty("detect_language")]
public bool? DetectLanguage { get; set; }
/// <summary>
/// The name of the attachment. Can be explicitly set
/// </summary>
[JsonProperty("name")]
public string Name { get; set; }
/// <summary>
/// The title of the attachment.
/// </summary>
[JsonProperty("title")]
public string Title { get; set; }
/// <summary>
/// Determines how many characters are extracted when indexing the content.
/// By default, 100000 characters are extracted when indexing the content.
/// -1 can be set to extract all text, but note that all the text needs to be
/// allowed to be represented in memory
/// </summary>
[JsonProperty("indexed_chars")]
public long? IndexedCharacters { get; set; }
/// <summary>
/// Whether the attachment contains explicit metadata in addition to the
/// content. Used at indexing time to determine the serialized form of the
/// attachment.
/// </summary>
[JsonIgnore]
public bool ContainsMetadata => !Name.IsNullOrEmpty() ||
!ContentType.IsNullOrEmpty() ||
!Language.IsNullOrEmpty() ||
DetectLanguage.HasValue ||
IndexedCharacters.HasValue;
}
internal class AttachmentConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var attachment = (Attachment)value;
if (!attachment.ContainsMetadata)
{
writer.WriteValue(attachment.Content);
}
else
{
writer.WriteStartObject();
writer.WritePropertyName("_content");
writer.WriteValue(attachment.Content);
if (!string.IsNullOrEmpty(attachment.Name))
{
writer.WritePropertyName("_name");
writer.WriteValue(attachment.Name);
}
if (!string.IsNullOrEmpty(attachment.ContentType))
{
writer.WritePropertyName("_content_type");
writer.WriteValue(attachment.ContentType);
}
if (!string.IsNullOrEmpty(attachment.Language))
{
writer.WritePropertyName("_language");
writer.WriteValue(attachment.Language);
}
if (attachment.DetectLanguage.HasValue)
{
writer.WritePropertyName("_detect_language");
writer.WriteValue(attachment.DetectLanguage.Value);
}
if (attachment.IndexedCharacters.HasValue)
{
writer.WritePropertyName("_indexed_chars");
writer.WriteValue(attachment.IndexedCharacters.Value);
}
writer.WriteEndObject();
}
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.String)
{
return new Attachment { Content = (string)reader.Value };
}
if (reader.TokenType == JsonToken.StartObject)
{
var attachment = new Attachment();
while (reader.Read())
{
if (reader.TokenType == JsonToken.PropertyName)
{
var propertyName = (string)reader.Value;
switch (propertyName.ToLowerInvariant())
{
case "_content":
case "content":
attachment.Content = reader.ReadAsString();
break;
case "_name":
case "name":
attachment.Name = reader.ReadAsString();
break;
case "author":
attachment.Author = reader.ReadAsString();
break;
case "keywords":
attachment.Keywords = reader.ReadAsString();
break;
case "date":
reader.Read();
switch (reader.TokenType)
{
case JsonToken.String:
var value = (string)reader.Value;
if (!string.IsNullOrEmpty(value))
attachment.Date = Convert.ToDateTime(value);
break;
case JsonToken.Date:
attachment.Date = (DateTime?)reader.Value;
break;
}
break;
case "_content_type":
case "content_type":
case "contenttype":
attachment.ContentType = reader.ReadAsString();
break;
case "_content_length":
case "content_length":
case "contentlength":
reader.Read();
switch (reader.TokenType)
{
case JsonToken.String:
var value = (string)reader.Value;
if (!string.IsNullOrEmpty(value))
attachment.ContentLength = Convert.ToInt64(value);
break;
case JsonToken.Integer:
case JsonToken.Float:
attachment.ContentLength = (long?)reader.Value;
break;
}
break;
case "_language":
case "language":
attachment.Language = reader.ReadAsString();
break;
case "_detect_language":
attachment.DetectLanguage = reader.ReadAsBoolean();
break;
case "_indexed_chars":
case "indexed_chars":
reader.Read();
switch (reader.TokenType)
{
case JsonToken.String:
var value = (string)reader.Value;
if (!string.IsNullOrEmpty(value))
attachment.IndexedCharacters = Convert.ToInt64(value);
break;
case JsonToken.Integer:
case JsonToken.Float:
attachment.IndexedCharacters = (long?)reader.Value;
break;
}
break;
}
}
if (reader.TokenType == JsonToken.EndObject)
{
break;
}
}
return attachment;
}
return null;
}
public override bool CanConvert(Type objectType) => objectType == typeof(Attachment);
}
}
| |
// Copyright (c) 2014-2015 Robert Rouhani <robert.rouhani@gmail.com> and other contributors (see CONTRIBUTORS file).
// Licensed under the MIT License - https://raw.github.com/Robmaister/SharpNav/master/LICENSE
using System;
using System.Collections.Generic;
using SharpNav.Collections.Generic;
using SharpNav.Geometry;
#if MONOGAME
using Vector3 = Microsoft.Xna.Framework.Vector3;
#elif OPENTK
using Vector3 = OpenTK.Vector3;
#elif SHARPDX
using Vector3 = SharpDX.Vector3;
#endif
namespace SharpNav.Crowds
{
public class ObstacleAvoidanceQuery
{
#region Fields
private const int MaxPatternDivs = 32;
private const int MaxPatternRings = 4;
private ObstacleAvoidanceParams parameters;
private float invHorizTime;
private float vmax;
private float invVmax;
private int maxCircles;
private ObstacleCircle[] circles;
private int numCircles;
private int maxSegments;
private ObstacleSegment[] segments;
private int numSegments;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="ObstacleAvoidanceQuery" /> class.
/// </summary>
/// <param name="maxCircles">The maximum number of circles</param>
/// <param name="maxSegments">The maximum number of segments</param>
public ObstacleAvoidanceQuery(int maxCircles, int maxSegments)
{
this.maxCircles = maxCircles;
this.numCircles = 0;
this.circles = new ObstacleCircle[this.maxCircles];
this.maxSegments = maxSegments;
this.numSegments = 0;
this.segments = new ObstacleSegment[this.maxSegments];
}
#endregion
#region Methods
/// <summary>
/// Resets the ObstacleAvoidanceQuery's internal data
/// </summary>
public void Reset()
{
numCircles = 0;
numSegments = 0;
}
/// <summary>
/// Add a new circle to the array
/// </summary>
/// <param name="pos">The position</param>
/// <param name="rad">The radius</param>
/// <param name="vel">The velocity</param>
/// <param name="dvel">The desired velocity</param>
public void AddCircle(Vector3 pos, float rad, Vector3 vel, Vector3 dvel)
{
if (numCircles >= maxCircles)
return;
circles[numCircles].Position = pos;
circles[numCircles].Radius = rad;
circles[numCircles].Vel = vel;
circles[numCircles].DesiredVel = dvel;
numCircles++;
}
/// <summary>
/// Add a segment to the array
/// </summary>
/// <param name="p">One endpoint</param>
/// <param name="q">The other endpoint</param>
public void AddSegment(Vector3 p, Vector3 q)
{
if (numSegments > maxSegments)
return;
segments[numSegments].P = p;
segments[numSegments].Q = q;
numSegments++;
}
/// <summary>
/// Prepare the obstacles for further calculations
/// </summary>
/// <param name="position">Current position</param>
/// <param name="desiredVel">Desired velocity</param>
public void Prepare(Vector3 position, Vector3 desiredVel)
{
//prepare obstacles
for (int i = 0; i < numCircles; i++)
{
//side
Vector3 pa = position;
Vector3 pb = circles[i].Position;
Vector3 orig = new Vector3(0, 0, 0);
circles[i].Dp = pb - pa;
circles[i].Dp.Normalize();
Vector3 dv = circles[i].DesiredVel - desiredVel;
float a = Triangle3.Area2D(orig, circles[i].Dp, dv);
if (a < 0.01f)
{
circles[i].Np.X = -circles[i].Dp.Z;
circles[i].Np.Z = circles[i].Dp.X;
}
else
{
circles[i].Np.X = circles[i].Dp.Z;
circles[i].Np.Z = -circles[i].Dp.X;
}
}
for (int i = 0; i < numSegments; i++)
{
//precalculate if the agent is close to the segment
float r = 0.01f;
float t;
segments[i].Touch = Distance.PointToSegment2DSquared(ref position, ref segments[i].P, ref segments[i].Q, out t) < (r * r);
}
}
public float ProcessSample(Vector3 vcand, float cs, Vector3 position, float radius, Vector3 vel, Vector3 desiredVel)
{
//find min time of impact and exit amongst all obstacles
float tmin = parameters.HorizTime;
float side = 0;
int numSide = 0;
for (int i = 0; i < numCircles; i++)
{
ObstacleCircle cir = circles[i];
//RVO
Vector3 vab = vcand * 2;
vab = vab - vel;
vab = vab - cir.Vel;
//side
side += MathHelper.Clamp(Math.Min(Vector3Extensions.Dot2D(ref cir.Dp, ref vab) * 0.5f + 0.5f, Vector3Extensions.Dot2D(ref cir.Np, ref vab) * 2.0f), 0.0f, 1.0f);
numSide++;
float htmin = 0, htmax = 0;
if (!SweepCircleCircle(position, radius, vab, cir.Position, cir.Radius, ref htmin, ref htmax))
continue;
//handle overlapping obstacles
if (htmin < 0.0f && htmax > 0.0f)
{
//avoid more when overlapped
htmin = -htmin * 0.5f;
}
if (htmin >= 0.0f)
{
//the closest obstacle is sometime ahead of us, keep track of nearest obstacle
if (htmin < tmin)
tmin = htmin;
}
}
for (int i = 0; i < numSegments; i++)
{
ObstacleSegment seg = segments[i];
float htmin = 0;
if (seg.Touch)
{
//special case when the agent is very close to the segment
Vector3 sdir = seg.Q - seg.P;
Vector3 snorm = new Vector3(0, 0, 0);
snorm.X = -sdir.Z;
snorm.Z = sdir.X;
//if the velocity is pointing towards the segment, no collision
if (Vector3Extensions.Dot2D(ref snorm, ref vcand) < 0.0f)
continue;
//else immediate collision
htmin = 0.0f;
}
else
{
if (!IntersectRaySegment(position, vcand, seg.P, seg.Q, ref htmin))
continue;
}
//avoid less when facing walls
htmin *= 2.0f;
//the closest obstacle is somewhere ahead of us, keep track of the nearest obstacle
if (htmin < tmin)
tmin = htmin;
}
//normalize side bias
if (numSide != 0)
side /= numSide;
float vpen = parameters.WeightDesVel * (Vector3Extensions.Distance2D(vcand, desiredVel) * invVmax);
float vcpen = parameters.WeightCurVel * (Vector3Extensions.Distance2D(vcand, vel) * invVmax);
float spen = parameters.WeightSide * side;
float tpen = parameters.WeightToi * (1.0f / (0.1f + tmin * invHorizTime));
float penalty = vpen + vcpen + spen + tpen;
return penalty;
}
public bool SweepCircleCircle(Vector3 center0, float radius0, Vector3 v, Vector3 center1, float radius1, ref float tmin, ref float tmax)
{
const float EPS = 0.0001f;
Vector3 s = center1 - center0;
float r = radius0 + radius1;
float c = Vector3Extensions.Dot2D(ref s, ref s) - r * r;
float a = Vector3Extensions.Dot2D(ref v, ref v);
if (a < EPS)
return false; //not moving
//overlap, calculate time to exit
float b = Vector3Extensions.Dot2D(ref v, ref s);
float d = b * b - a * c;
if (d < 0.0f)
return false; //no intersection
a = 1.0f / a;
float rd = (float)Math.Sqrt(d);
tmin = (b - rd) * a;
tmax = (b + rd) * a;
return true;
}
/// <summary>
/// Determine whether the ray intersects the segment
/// </summary>
/// <param name="ap">A point</param>
/// <param name="u">A vector</param>
/// <param name="bp">Segment B endpoint</param>
/// <param name="bq">Another one of segment B's endpoints</param>
/// <param name="t">The parameter t</param>
/// <returns>True if intersect, false if not</returns>
public bool IntersectRaySegment(Vector3 ap, Vector3 u, Vector3 bp, Vector3 bq, ref float t)
{
Vector3 v = bq - bp;
Vector3 w = ap - bp;
float d;
Vector3Extensions.PerpDotXZ(ref u, ref v, out d);
d *= -1;
if (Math.Abs(d) < 1e-6f)
return false;
d = 1.0f / d;
Vector3Extensions.PerpDotXZ(ref v, ref w, out t);
t *= -d;
if (t < 0 || t > 1)
return false;
float s;
Vector3Extensions.PerpDotXZ(ref u, ref w, out s);
s *= -d;
if (s < 0 || s > 1)
return false;
return true;
}
public int SampleVelocityGrid(Vector3 pos, float rad, float vmax, Vector3 vel, Vector3 desiredVel, ref Vector3 nvel, ObstacleAvoidanceParams parameters)
{
Prepare(pos, desiredVel);
this.parameters = parameters;
this.invHorizTime = 1.0f / this.parameters.HorizTime;
this.vmax = vmax;
this.invVmax = 1.0f / vmax;
nvel = new Vector3(0, 0, 0);
float cvx = desiredVel.X * this.parameters.VelBias;
float cvz = desiredVel.Z * this.parameters.VelBias;
float cs = vmax * 2 * (1 - this.parameters.VelBias) / (float)(this.parameters.GridSize - 1);
float half = (this.parameters.GridSize - 1) * cs * 0.5f;
float minPenalty = float.MaxValue;
int numSamples = 0;
for (int y = 0; y < this.parameters.GridSize; y++)
{
for (int x = 0; x < this.parameters.GridSize; x++)
{
Vector3 vcand = new Vector3(0, 0, 0);
vcand.X = cvx + x * cs - half;
vcand.Y = 0;
vcand.Z = cvz + y * cs - half;
if (vcand.X * vcand.X + vcand.Z * vcand.Z > (vmax + cs / 2) * (vmax + cs / 2))
continue;
float penalty = ProcessSample(vcand, cs, pos, rad, vel, desiredVel);
numSamples++;
if (penalty < minPenalty)
{
minPenalty = penalty;
nvel = vcand;
}
}
}
return numSamples;
}
public int SampleVelocityAdaptive(Vector3 position, float radius, float vmax, Vector3 vel, Vector3 desiredVel, ref Vector3 nvel, ObstacleAvoidanceParams parameters)
{
Prepare(position, desiredVel);
this.parameters = parameters;
this.invHorizTime = 1.0f / parameters.HorizTime;
this.vmax = vmax;
this.invVmax = 1.0f / vmax;
nvel = new Vector3(0, 0, 0);
//build sampling pattern aligned to desired velocity
float[] pattern = new float[(MaxPatternDivs * MaxPatternRings + 1) * 2];
int numPatterns = 0;
int numDivs = parameters.AdaptiveDivs;
int numRings = parameters.AdaptiveRings;
int depth = parameters.AdaptiveDepth;
int newNumDivs = MathHelper.Clamp(numDivs, 1, MaxPatternDivs);
int newNumRings = MathHelper.Clamp(numRings, 1, MaxPatternRings);
float da = (1.0f / newNumDivs) * (float)Math.PI * 2;
float dang = (float)Math.Atan2(desiredVel.Z, desiredVel.X);
//always add sample at zero
pattern[numPatterns * 2 + 0] = 0;
pattern[numPatterns * 2 + 1] = 0;
numPatterns++;
for (int j = 0; j < newNumRings; j++)
{
float r = (float)(newNumRings - j) / (float)newNumRings;
float a = dang + (j & 1) * 0.5f * da;
for (int i = 0; i < newNumDivs; i++)
{
pattern[numPatterns * 2 + 0] = (float)Math.Cos(a) * r;
pattern[numPatterns * 2 + 1] = (float)Math.Sin(a) * r;
numPatterns++;
a += da;
}
}
//start sampling
float cr = vmax * (1.0f - parameters.VelBias);
Vector3 res = new Vector3(desiredVel.X * parameters.VelBias, 0, desiredVel.Z * parameters.VelBias);
int ns = 0;
for (int k = 0; k < depth; k++)
{
float minPenalty = float.MaxValue;
Vector3 bvel = new Vector3(0, 0, 0);
for (int i = 0; i < numPatterns; i++)
{
Vector3 vcand = new Vector3();
vcand.X = res.X + pattern[i * 2 + 0] * cr;
vcand.Y = 0;
vcand.Z = res.Z + pattern[i * 2 + 1] * cr;
if (vcand.X * vcand.X + vcand.Z * vcand.Z > (vmax + 0.001f) * (vmax + 0.001f))
continue;
float penalty = ProcessSample(vcand, cr / 10, position, radius, vel, desiredVel);
ns++;
if (penalty < minPenalty)
{
minPenalty = penalty;
bvel = vcand;
}
}
res = bvel;
cr *= 0.5f;
}
nvel = res;
return ns;
}
#endregion
private struct ObstacleCircle
{
/// <summary>
/// The position of the obstacle
/// </summary>
public Vector3 Position;
/// <summary>
/// The velocity of the obstacle
/// </summary>
public Vector3 Vel;
/// <summary>
/// The desired velocity of the obstacle
/// </summary>
public Vector3 DesiredVel;
/// <summary>
/// The radius of the obstacle
/// </summary>
public float Radius;
/// <summary>
/// Used for side selection during sampling
/// </summary>
public Vector3 Dp, Np;
}
private struct ObstacleSegment
{
/// <summary>
/// Endpoints of the obstacle segment
/// </summary>
public Vector3 P, Q;
public bool Touch;
}
public struct ObstacleAvoidanceParams
{
public float VelBias;
public float WeightDesVel;
public float WeightCurVel;
public float WeightSide;
public float WeightToi;
public float HorizTime;
public int GridSize;
public int AdaptiveDivs;
public int AdaptiveRings;
public int AdaptiveDepth;
}
}
}
| |
using UnityEngine;
using System.Collections.Generic;
public enum MegaRubberType
{
Custom,
SoftRubber,
HardRubber,
Jelly,
SoftLatex
}
[System.Serializable]
public class VertexRubber
{
public Vector3 pos;
public Vector3 cpos;
public Vector3 force;
public Vector3 acc;
public Vector3 vel;
public int[] indices;
public float weight;
public float stiff;
public VertexRubber(Vector3 v_target, float w, float s) { pos = v_target; weight = w; stiff = s; }
}
[AddComponentMenu("Modifiers/Rubber")]
public class MegaRubber : MegaModifier
{
public override string ModName() { return "Rubber"; }
public override string GetHelpURL() { return "?page_id=1254"; }
// From other system
public MegaRubberType Presets = MegaRubberType.Custom;
public MegaWeightChannel channel = MegaWeightChannel.Red;
public MegaWeightChannel stiffchannel = MegaWeightChannel.None;
public Vector3 Intensity = Vector3.one;
public float gravity = 0.0f;
public float mass = 1.0f;
public Vector3 stiffness = new Vector3(0.2f, 0.2f, 0.2f);
public Vector3 damping = new Vector3(0.7f, 0.7f, 0.7f);
public float threshold = 0.0f;
public float size = 0.001f;
public bool showweights = true;
float oomass;
float grav;
bool defined = false;
public VertexRubber[] vr;
int[] notmoved;
public Transform target;
[ContextMenu("Reset Physics")]
public void ResetPhysics()
{
MegaModifiers mod = GetComponent<MegaModifiers>();
if ( mod )
Init(mod);
}
int[] FindVerts(Vector3[] vts, Vector3 p)
{
List<int> indices = new List<int>();
for ( int i = 0; i < vts.Length; i++ )
{
if ( p.x == vts[i].x && p.y == vts[i].y && p.z == vts[i].z )
indices.Add(i);
}
return indices.ToArray();
}
bool HavePoint(Vector3[] vts, List<int> points, Vector3 p)
{
for ( int i = 0; i < points.Count; i++ )
{
if ( p.x == vts[points[i]].x && p.y == vts[points[i]].y && p.z == vts[points[i]].z )
return true;
}
return false;
}
void Init(MegaModifiers mod)
{
if ( mod.verts == null )
return;
List<int> noweights = new List<int>();
List<int> ActiveVertex = new List<int>();
int wc = (int)channel;
for ( int i = 0; i < mod.verts.Length; i++ )
{
// Dont add if we have already
if ( channel == MegaWeightChannel.None || mod.cols == null || mod.cols.Length == 0 )
{
}
else
{
if ( mod.cols[i][wc] > threshold )
{
if ( !HavePoint(mod.verts, ActiveVertex, mod.verts[i]) )
ActiveVertex.Add(i);
}
else
noweights.Add(i);
}
}
notmoved = noweights.ToArray();
if ( ActiveVertex.Count > 0 )
{
vr = new VertexRubber[ActiveVertex.Count];
for ( int i = 0; i < ActiveVertex.Count; i++ )
{
int ref_index = (int)ActiveVertex[i];
float stiff = 1.0f;
if ( stiffchannel != MegaWeightChannel.None && mod.cols != null && mod.cols.Length > 0 )
{
stiff = mod.cols[ref_index][(int)stiffchannel];
}
float intens = (mod.cols[ref_index][wc] - threshold) / (1.0f - threshold);
vr[i] = new VertexRubber(transform.TransformPoint(mod.verts[ref_index]), intens, stiff);
vr[i].indices = FindVerts(mod.verts, mod.verts[ref_index]);
}
}
else
vr = null;
defined = true;
}
public override bool ModLateUpdate(MegaModContext mc)
{
if ( weightsChanged )
{
ResetPhysics();
weightsChanged = false;
}
return Prepare(mc);
}
public override bool Prepare(MegaModContext mc)
{
if ( target )
{
tm = target.worldToLocalMatrix * transform.localToWorldMatrix;
invtm = tm.inverse; //target.worldToLocalMatrix;
}
else
{
tm = transform.localToWorldMatrix;
invtm = transform.worldToLocalMatrix;
}
oomass = 1.0f / mass;
grav = gravity * 0.1f;
if ( !defined )
Init(mc.mod);
if ( vr != null )
return true;
return false;
}
public override void Modify(MegaModifiers mc)
{
UpdateVerts(0, vr.Length);
for ( int i = 0; i < notmoved.Length; i++ )
sverts[notmoved[i]] = verts[notmoved[i]];
}
public void SetTarget(Transform target)
{
if ( target )
{
tm = target.worldToLocalMatrix * transform.localToWorldMatrix;
invtm = tm.inverse; //target.worldToLocalMatrix;
}
else
{
tm = transform.localToWorldMatrix;
invtm = transform.worldToLocalMatrix;
}
InitVerts(0, vr.Length);
}
void InitVerts(int start, int end)
{
for ( int i = start; i < end; i++ )
{
int ix = vr[i].indices[0];
Vector3 vp = verts[ix];
Vector3 v3_target = tm.MultiplyPoint(vp);
VertexRubber v = vr[i];
v.vel = Vector3.zero;
v.pos = v3_target;
}
}
void UpdateVerts(int start, int end)
{
Vector3 p = Vector3.zero;
for ( int i = start; i < end; i++ )
{
int ix = vr[i].indices[0];
Vector3 vp = verts[ix];
Vector3 v3_target = tm.MultiplyPoint(vp);
VertexRubber v = vr[i];
v.force.x = (v3_target.x - v.pos.x) * stiffness.x * v.stiff;
v.acc.x = v.force.x * oomass;
v.vel.x = damping.x * (v.vel.x + v.acc.x);
v.pos.x += v.vel.x; // * t;
v.force.y = (v3_target.y - v.pos.y) * stiffness.y * v.stiff;
v.force.y -= grav;
v.acc.y = v.force.y * oomass;
v.vel.y = damping.y * (v.vel.y + v.acc.y);
v.pos.y += v.vel.y; // * t;
v.force.z = (v3_target.z - v.pos.z) * stiffness.z * v.stiff;
v.acc.z = v.force.z * oomass;
v.vel.z = damping.z * (v.vel.z + v.acc.z);
v.pos.z += v.vel.z; // * t;
v3_target = invtm.MultiplyPoint(vr[i].pos);
p.x = vp.x + ((v3_target.x - vp.x) * v.weight * Intensity.x);
p.y = vp.y + ((v3_target.y - vp.y) * v.weight * Intensity.y);
p.z = vp.z + ((v3_target.z - vp.z) * v.weight * Intensity.z);
v.cpos = p;
for ( int v1 = 0; v1 < vr[i].indices.Length; v1++ )
{
int ix1 = vr[i].indices[v1];
sverts[ix1] = p;
}
}
}
public void ChangeMaterial()
{
switch ( Presets )
{
case MegaRubberType.HardRubber:
gravity = 0.0f;
mass = 8.0f;
stiffness = new Vector3(0.5f, 0.5f, 0.5f);
damping = new Vector3(0.9f, 0.9f, 0.9f);
Intensity = new Vector3(0.5f, 0.5f, 0.5f);
break;
case MegaRubberType.Jelly:
gravity = 0.0f;
mass = 1.0f;
stiffness = new Vector3(0.95f, 0.95f, 0.95f);
damping = new Vector3(0.95f, 0.95f, 0.95f);
Intensity = Vector3.one;
break;
case MegaRubberType.SoftRubber:
gravity = 0.0f;
mass = 2.0f;
stiffness = new Vector3(0.5f, 0.5f, 0.5f);
damping = new Vector3(0.85f, 0.85f, 0.85f);
Intensity = Vector3.one;
break;
case MegaRubberType.SoftLatex:
gravity = 1.0f;
mass = 0.9f;
stiffness = new Vector3(0.3f, 0.3f, 0.3f);
damping = new Vector3(0.25f, 0.25f, 0.25f);
Intensity = Vector3.one;
break;
}
}
public void ChangeChannel()
{
MegaModifiers mod = GetComponent<MegaModifiers>();
if ( mod )
Init(mod);
}
// Threaded
public override void DoWork(MegaModifiers mc, int index, int start, int end, int cores)
{
ModifyCompressedMT(mc, index, cores);
}
public void ModifyCompressedMT(MegaModifiers mc, int tindex, int cores)
{
int step = notmoved.Length / cores;
int startvert = (tindex * step);
int endvert = startvert + step;
if ( tindex == cores - 1 )
endvert = notmoved.Length;
if ( notmoved != null )
{
for ( int i = startvert; i < endvert; i++ )
{
int index = notmoved[i];
sverts[index] = verts[index];
}
}
step = vr.Length / cores;
startvert = (tindex * step);
endvert = startvert + step;
if ( tindex == cores - 1 )
endvert = vr.Length;
UpdateVerts(startvert, endvert);
}
bool weightsChanged = false;
MegaModifiers mods = null;
MegaModifiers GetMod()
{
if ( mods == null )
mods = GetComponent<MegaModifiers>();
return mods;
}
public void UpdateCols(int first, Color[] newcols)
{
GetMod();
if ( mods )
mods.UpdateCols(first, newcols);
weightsChanged = true;
}
public void UpdateCol(int i, Color col)
{
GetMod();
if ( mods )
mods.UpdateCol(i, col);
weightsChanged = true;
}
public void UpdateCols(Color[] newcols)
{
GetMod();
if ( mods )
mods.UpdateCols(newcols);
weightsChanged = true;
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using AspNet.Security.OpenIdConnect.Extensions;
using AspNet.Security.OpenIdConnect.Primitives;
using AspNet.Security.OpenIdConnect.Server;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Options;
using OpenIddict.Core;
using OrchardCore.Mvc.ActionConstraints;
using OrchardCore.OpenId.Models;
using OrchardCore.OpenId.Services;
using OrchardCore.OpenId.ViewModels;
using OrchardCore.Security;
using OrchardCore.Users;
namespace OrchardCore.OpenId.Controllers
{
[Authorize]
public class AccessController : Controller
{
private readonly OpenIddictApplicationManager<OpenIdApplication> _applicationManager;
private readonly IOptions<IdentityOptions> _identityOptions;
private readonly SignInManager<IUser> _signInManager;
private readonly IOpenIdService _openIdService;
private readonly RoleManager<IRole> _roleManager;
private readonly UserManager<IUser> _userManager;
private readonly IStringLocalizer<AccessController> T;
public AccessController(
OpenIddictApplicationManager<OpenIdApplication> applicationManager,
IOptions<IdentityOptions> identityOptions,
IStringLocalizer<AccessController> localizer,
IOpenIdService openIdService,
RoleManager<IRole> roleManager,
SignInManager<IUser> signInManager,
UserManager<IUser> userManager)
{
T = localizer;
_applicationManager = applicationManager;
_identityOptions = identityOptions;
_openIdService = openIdService;
_signInManager = signInManager;
_userManager = userManager;
_roleManager = roleManager;
}
[HttpGet, HttpPost]
public async Task<IActionResult> Authorize()
{
var response = HttpContext.GetOpenIdConnectResponse();
if (response != null)
{
return View("Error", new ErrorViewModel
{
Error = response.Error,
ErrorDescription = response.ErrorDescription
});
}
// If the request is missing, this likely means that
// this endpoint was not enabled in the settings.
// In this case, simply return a 404 response.
var request = HttpContext.GetOpenIdConnectRequest();
if (request == null)
{
return NotFound();
}
var application = await _applicationManager.FindByClientIdAsync(request.ClientId, HttpContext.RequestAborted);
if (application == null)
{
return View("Error", new ErrorViewModel
{
Error = OpenIdConnectConstants.Errors.InvalidClient,
ErrorDescription = T["Details concerning the calling client application cannot be found in the database"]
});
}
if (request.HasScope(OpenIdConnectConstants.Scopes.OfflineAccess) && !application.AllowRefreshTokenFlow)
{
return View("Error", new ErrorViewModel
{
Error = OpenIdConnectConstants.Errors.InvalidClient,
ErrorDescription = T["Offline scope is not allowed for this OpenID Connect Application"]
});
}
if (request.IsAuthorizationCodeFlow() && !application.AllowAuthorizationCodeFlow)
{
return View("Error", new ErrorViewModel
{
Error = OpenIdConnectConstants.Errors.UnauthorizedClient,
ErrorDescription = T["Authorization Code Flow is not allowed for this OpenID Connect Application"]
});
}
if (request.IsImplicitFlow() && !application.AllowImplicitFlow)
{
return View("Error", new ErrorViewModel
{
Error = OpenIdConnectConstants.Errors.UnauthorizedClient,
ErrorDescription = T["Implicit Flow is not allowed for this OpenID Connect Application"]
});
}
if (request.IsHybridFlow() && !application.AllowHybridFlow)
{
return View("Error", new ErrorViewModel
{
Error = OpenIdConnectConstants.Errors.UnauthorizedClient,
ErrorDescription = T["Hybrid Flow is not allowed for this OpenID Connect Application"]
});
}
if (Request.HasFormContentType)
{
if (!string.IsNullOrEmpty(Request.Form["submit.Accept"]))
{
return await IssueAccessIdentityTokensAsync(request);
}
else if (!string.IsNullOrEmpty(Request.Form["submit.Deny"]))
{
return Forbid(OpenIdConnectServerDefaults.AuthenticationScheme);
}
}
if (application.SkipConsent)
{
return await IssueAccessIdentityTokensAsync(request);
}
return View(new AuthorizeViewModel
{
ApplicationName = application.DisplayName,
RequestId = request.RequestId,
Scope = request.Scope
});
}
[AllowAnonymous, HttpGet]
public async Task<IActionResult> Logout()
{
var response = HttpContext.GetOpenIdConnectResponse();
if (response != null)
{
return View("Error", new ErrorViewModel
{
Error = response.Error,
ErrorDescription = response.ErrorDescription
});
}
// If the request is missing, this likely means that
// this endpoint was not enabled in the settings.
// In this case, simply return a 404 response.
var request = HttpContext.GetOpenIdConnectRequest();
if (request == null)
{
return NotFound();
}
await _signInManager.SignOutAsync();
// Returning a SignOutResult will ask OpenIddict to redirect the user agent
// to the post_logout_redirect_uri specified by the client application.
return SignOut(OpenIdConnectServerDefaults.AuthenticationScheme);
}
[AllowAnonymous, HttpPost]
[IgnoreAntiforgeryToken]
[Produces("application/json")]
public async Task<IActionResult> Token()
{
// Warning: this action is decorated with IgnoreAntiforgeryTokenAttribute to override
// the global antiforgery token validation policy applied by the MVC modules stack,
// which is required for this stateless OAuth2/OIDC token endpoint to work correctly.
// To prevent effective CSRF/session fixation attacks, this action MUST NOT return
// an authentication cookie or try to establish an ASP.NET Core user session.
// If the request is missing, this likely means that
// this endpoint was not enabled in the settings.
// In this case, simply return a 404 response.
var request = HttpContext.GetOpenIdConnectRequest();
if (request == null)
{
return NotFound();
}
var application = await _applicationManager.FindByClientIdAsync(request.ClientId, HttpContext.RequestAborted);
if (application == null)
{
return BadRequest(new OpenIdConnectResponse
{
Error = OpenIdConnectConstants.Errors.InvalidClient,
ErrorDescription = T["Details concerning the calling client application cannot be found in the database"]
});
}
if (request.HasScope(OpenIdConnectConstants.Scopes.OfflineAccess) && !application.AllowRefreshTokenFlow)
{
return BadRequest(new OpenIdConnectResponse
{
Error = OpenIdConnectConstants.Errors.InvalidRequest,
ErrorDescription = T["Offline scope is not allowed for this OpenID Connect Application"]
});
}
if (request.IsPasswordGrantType())
{
if (!application.AllowPasswordFlow)
{
return BadRequest(new OpenIdConnectResponse
{
Error = OpenIdConnectConstants.Errors.UnauthorizedClient,
ErrorDescription = T["Password Flow is not allowed for this OpenID Connect Application"]
});
}
return await ExchangePasswordGrantType(request);
}
if (request.IsClientCredentialsGrantType())
{
if (!application.AllowClientCredentialsFlow)
{
return BadRequest(new OpenIdConnectResponse
{
Error = OpenIdConnectConstants.Errors.UnauthorizedClient,
ErrorDescription = T["Client Credentials Flow is not allowed for this OpenID Connect Application"]
});
}
return await ExchangeClientCredentialsGrantType(request);
}
if (request.IsAuthorizationCodeGrantType())
{
if (!application.AllowAuthorizationCodeFlow)
{
return BadRequest(new OpenIdConnectResponse
{
Error = OpenIdConnectConstants.Errors.UnauthorizedClient,
ErrorDescription = T["Authorization Code Flow is not allowed for this OpenID Connect Application"]
});
}
return await ExchangeAuthorizationCodeOrRefreshTokenGrantType(request);
}
if (request.IsRefreshTokenGrantType())
{
if (!application.AllowRefreshTokenFlow)
{
return BadRequest(new OpenIdConnectResponse
{
Error = OpenIdConnectConstants.Errors.UnauthorizedClient,
ErrorDescription = T["Refresh Token Flow is not allowed for this OpenID Connect Application"]
});
}
return await ExchangeAuthorizationCodeOrRefreshTokenGrantType(request);
}
throw new NotSupportedException("The specified grant type is not supported.");
}
private async Task<IActionResult> ExchangeClientCredentialsGrantType(OpenIdConnectRequest request)
{
// Note: client authentication is always enforced by OpenIddict before this action is invoked.
var application = await _applicationManager.FindByClientIdAsync(request.ClientId, HttpContext.RequestAborted);
if (application == null)
{
return BadRequest(new OpenIdConnectResponse
{
Error = OpenIdConnectConstants.Errors.InvalidClient,
ErrorDescription = T["The client application is unknown."]
});
}
var identity = new ClaimsIdentity(
OpenIdConnectServerDefaults.AuthenticationScheme,
OpenIdConnectConstants.Claims.Name,
OpenIdConnectConstants.Claims.Role);
identity.AddClaim(OpenIdConnectConstants.Claims.Subject, application.ClientId);
identity.AddClaim(OpenIdConnectConstants.Claims.Name,
await _applicationManager.GetDisplayNameAsync(application, HttpContext.RequestAborted),
OpenIdConnectConstants.Destinations.AccessToken,
OpenIdConnectConstants.Destinations.IdentityToken);
foreach (var roleName in application.RoleNames)
{
identity.AddClaim(identity.RoleClaimType, roleName,
OpenIdConnectConstants.Destinations.AccessToken,
OpenIdConnectConstants.Destinations.IdentityToken);
foreach (var claim in await _roleManager.GetClaimsAsync(await _roleManager.FindByIdAsync(roleName)))
{
identity.AddClaim(claim.Type, claim.Value, OpenIdConnectConstants.Destinations.AccessToken,
OpenIdConnectConstants.Destinations.IdentityToken);
}
}
var ticket = new AuthenticationTicket(
new ClaimsPrincipal(identity),
new AuthenticationProperties(),
OpenIdConnectServerDefaults.AuthenticationScheme);
ticket.SetResources(await GetResourcesAsync(request));
return SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme);
}
private async Task<IActionResult> ExchangePasswordGrantType(OpenIdConnectRequest request)
{
var user = await _userManager.FindByNameAsync(request.Username);
if (user == null)
{
return BadRequest(new OpenIdConnectResponse
{
Error = OpenIdConnectConstants.Errors.InvalidGrant,
ErrorDescription = T["The username/password couple is invalid."]
});
}
var result = await _signInManager.CheckPasswordSignInAsync(user, request.Password, lockoutOnFailure: true);
if (result.IsNotAllowed)
{
return BadRequest(new OpenIdConnectResponse
{
Error = OpenIdConnectConstants.Errors.InvalidGrant,
ErrorDescription = T["The specified user is not allowed to sign in."]
});
}
else if (result.RequiresTwoFactor)
{
return BadRequest(new OpenIdConnectResponse
{
Error = OpenIdConnectConstants.Errors.InvalidGrant,
ErrorDescription = T["The specified user is not allowed to sign in using the password method."]
});
}
else if (!result.Succeeded)
{
return BadRequest(new OpenIdConnectResponse
{
Error = OpenIdConnectConstants.Errors.InvalidGrant,
ErrorDescription = T["The username/password couple is invalid."]
});
}
var ticket = await CreateTicketAsync(request, user);
return SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme);
}
private async Task<IActionResult> ExchangeAuthorizationCodeOrRefreshTokenGrantType(OpenIdConnectRequest request)
{
// Retrieve the claims principal stored in the authorization code/refresh token.
//var info = await HttpContext.Authentication.GetAuthenticateInfoAsync(
var info = await HttpContext.AuthenticateAsync(
OpenIdConnectServerDefaults.AuthenticationScheme);
// Retrieve the user profile corresponding to the authorization code/refresh token.
// Note: if you want to automatically invalidate the authorization code/refresh token
// when the user password/roles change, use the following line instead:
// var user = _signInManager.ValidateSecurityStampAsync(info.Principal);
var user = await _userManager.GetUserAsync(info.Principal);
if (user == null)
{
return BadRequest(new OpenIdConnectResponse
{
Error = OpenIdConnectConstants.Errors.InvalidGrant,
ErrorDescription = T["The token is no longer valid."]
});
}
// Ensure the user is still allowed to sign in.
if (!await _signInManager.CanSignInAsync(user))
{
return BadRequest(new OpenIdConnectResponse
{
Error = OpenIdConnectConstants.Errors.InvalidGrant,
ErrorDescription = T["The user is no longer allowed to sign in."]
});
}
// Create a new authentication ticket, but reuse the properties stored in the
// authorization code/refresh token, including the scopes originally granted.
var ticket = await CreateTicketAsync(request, user, info.Properties);
return SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme);
}
private async Task<IActionResult> IssueAccessIdentityTokensAsync(OpenIdConnectRequest request)
{
// Retrieve the profile of the logged in user.
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return View("Error", new ErrorViewModel
{
Error = OpenIdConnectConstants.Errors.ServerError,
ErrorDescription = T["An internal error has occurred"]
});
}
var ticket = await CreateTicketAsync(request, user);
// Returning a SignInResult will ask OpenIddict to issue the appropriate access/identity tokens.
return SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme);
}
private async Task<AuthenticationTicket> CreateTicketAsync(
OpenIdConnectRequest request, IUser user,
AuthenticationProperties properties = null)
{
// Create a new ClaimsPrincipal containing the claims that
// will be used to create an id_token, a token or a code.
var principal = await _signInManager.CreateUserPrincipalAsync(user);
var identity = (ClaimsIdentity) principal.Identity;
// Note: while ASP.NET Core Identity uses the legacy WS-Federation claims (exposed by the ClaimTypes class),
// OpenIddict uses the newer JWT claims defined by the OpenID Connect specification. To ensure the mandatory
// subject claim is correctly populated (and avoid an InvalidOperationException), it's manually added here.
if (string.IsNullOrEmpty(principal.FindFirstValue(OpenIdConnectConstants.Claims.Subject)))
{
identity.AddClaim(new Claim(OpenIdConnectConstants.Claims.Subject, await _userManager.GetUserIdAsync(user)));
}
// Create a new authentication ticket holding the user identity.
var ticket = new AuthenticationTicket(principal, properties,
OpenIdConnectServerDefaults.AuthenticationScheme);
if (!request.IsAuthorizationCodeGrantType() && !request.IsRefreshTokenGrantType())
{
// Set the list of scopes granted to the client application.
// Note: the offline_access scope must be granted
// to allow OpenIddict to return a refresh token.
ticket.SetScopes(new[]
{
OpenIdConnectConstants.Scopes.OpenId,
OpenIdConnectConstants.Scopes.Email,
OpenIdConnectConstants.Scopes.Profile,
OpenIdConnectConstants.Scopes.OfflineAccess,
OpenIddictConstants.Scopes.Roles
}.Intersect(request.GetScopes()));
ticket.SetResources(await GetResourcesAsync(request));
}
// Note: by default, claims are NOT automatically included in the access and identity tokens.
// To allow OpenIddict to serialize them, you must attach them a destination, that specifies
// whether they should be included in access tokens, in identity tokens or in both.
foreach (var claim in ticket.Principal.Claims)
{
// Never include the security stamp in the access and identity tokens, as it's a secret value.
if (claim.Type == _identityOptions.Value.ClaimsIdentity.SecurityStampClaimType)
{
continue;
}
var destinations = new List<string>
{
OpenIdConnectConstants.Destinations.AccessToken
};
// Only add the iterated claim to the id_token if the corresponding scope was granted to the client application.
// The other claims will only be added to the access_token, which is encrypted when using the default format.
if ((claim.Type == OpenIdConnectConstants.Claims.Name && ticket.HasScope(OpenIdConnectConstants.Scopes.Profile)) ||
(claim.Type == OpenIdConnectConstants.Claims.Email && ticket.HasScope(OpenIdConnectConstants.Scopes.Email)) ||
(claim.Type == OpenIdConnectConstants.Claims.Role && ticket.HasScope(OpenIddictConstants.Claims.Roles)))
{
destinations.Add(OpenIdConnectConstants.Destinations.IdentityToken);
}
claim.SetDestinations(destinations);
}
return ticket;
}
private async Task<IEnumerable<string>> GetResourcesAsync(OpenIdConnectRequest request)
{
var settings = await _openIdService.GetOpenIdSettingsAsync();
// If at least one resource was specified, use Intersect() to exclude values that are not
// listed as valid audiences in the OpenID Connect settings associated with the tenant.
var resources = request.GetResources();
if (resources.Any())
{
return resources.Intersect(settings.Audiences);
}
return settings.Audiences;
}
}
}
| |
namespace KabMan.Client
{
partial class frmServerDetail
{
/// <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(frmServerDetail));
DevExpress.XtraEditors.DXErrorProvider.ConditionValidationRule conditionValidationRule3 = new DevExpress.XtraEditors.DXErrorProvider.ConditionValidationRule();
DevExpress.XtraEditors.DXErrorProvider.ConditionValidationRule conditionValidationRule4 = new DevExpress.XtraEditors.DXErrorProvider.ConditionValidationRule();
DevExpress.XtraEditors.DXErrorProvider.ConditionValidationRule conditionValidationRule1 = new DevExpress.XtraEditors.DXErrorProvider.ConditionValidationRule();
this.layoutControl1 = new DevExpress.XtraLayout.LayoutControl();
this.txtStandort = new DevExpress.XtraEditors.TextEdit();
this.lkpLocation = new DevExpress.XtraEditors.LookUpEdit();
this.cmbOP = new DevExpress.XtraEditors.ComboBoxEdit();
this.btnSchliessen = new DevExpress.XtraEditors.SimpleButton();
this.btnSpeichern = new DevExpress.XtraEditors.SimpleButton();
this.txtServerName = new DevExpress.XtraEditors.TextEdit();
this.layoutControlGroup1 = new DevExpress.XtraLayout.LayoutControlGroup();
this.layoutControlItem1 = new DevExpress.XtraLayout.LayoutControlItem();
this.emptySpaceItem1 = new DevExpress.XtraLayout.EmptySpaceItem();
this.layoutControlItem2 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlItem3 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlItem4 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlItem5 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlItem6 = new DevExpress.XtraLayout.LayoutControlItem();
this.dxValidationProvider1 = new DevExpress.XtraEditors.DXErrorProvider.DXValidationProvider(this.components);
this.layoutControlGroup2 = new DevExpress.XtraLayout.LayoutControlGroup();
((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).BeginInit();
this.layoutControl1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.txtStandort.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.lkpLocation.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.cmbOP.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.txtServerName.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem3)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem4)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem5)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem6)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.dxValidationProvider1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup2)).BeginInit();
this.SuspendLayout();
//
// layoutControl1
//
this.layoutControl1.AllowCustomizationMenu = false;
this.layoutControl1.Appearance.DisabledLayoutGroupCaption.ForeColor = System.Drawing.SystemColors.GrayText;
this.layoutControl1.Appearance.DisabledLayoutGroupCaption.Options.UseForeColor = true;
this.layoutControl1.Appearance.DisabledLayoutItem.ForeColor = System.Drawing.SystemColors.GrayText;
this.layoutControl1.Appearance.DisabledLayoutItem.Options.UseForeColor = true;
this.layoutControl1.Controls.Add(this.txtStandort);
this.layoutControl1.Controls.Add(this.lkpLocation);
this.layoutControl1.Controls.Add(this.cmbOP);
this.layoutControl1.Controls.Add(this.btnSchliessen);
this.layoutControl1.Controls.Add(this.btnSpeichern);
this.layoutControl1.Controls.Add(this.txtServerName);
resources.ApplyResources(this.layoutControl1, "layoutControl1");
this.layoutControl1.Name = "layoutControl1";
this.layoutControl1.Root = this.layoutControlGroup1;
//
// txtStandort
//
resources.ApplyResources(this.txtStandort, "txtStandort");
this.txtStandort.Name = "txtStandort";
this.txtStandort.Properties.CharacterCasing = System.Windows.Forms.CharacterCasing.Upper;
this.txtStandort.Properties.MaxLength = 10;
this.txtStandort.StyleController = this.layoutControl1;
conditionValidationRule3.ConditionOperator = DevExpress.XtraEditors.DXErrorProvider.ConditionOperator.IsNotBlank;
resources.ApplyResources(conditionValidationRule3, "conditionValidationRule3");
conditionValidationRule3.ErrorType = DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning;
this.dxValidationProvider1.SetValidationRule(this.txtStandort, conditionValidationRule3);
//
// lkpLocation
//
resources.ApplyResources(this.lkpLocation, "lkpLocation");
this.lkpLocation.Name = "lkpLocation";
this.lkpLocation.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(((DevExpress.XtraEditors.Controls.ButtonPredefines)(resources.GetObject("lkpLocation.Properties.Buttons"))))});
this.lkpLocation.Properties.Columns.AddRange(new DevExpress.XtraEditors.Controls.LookUpColumnInfo[] {
new DevExpress.XtraEditors.Controls.LookUpColumnInfo("LocationName", "Location", 20, DevExpress.Utils.FormatType.None, "", true, DevExpress.Utils.HorzAlignment.Default, DevExpress.Data.ColumnSortOrder.None)});
this.lkpLocation.Properties.NullText = resources.GetString("lkpLocation.Properties.NullText");
this.lkpLocation.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.Standard;
this.lkpLocation.StyleController = this.layoutControl1;
this.lkpLocation.EditValueChanged += new System.EventHandler(this.lkpLocation_EditValueChanged);
this.lkpLocation.ProcessNewValue += new DevExpress.XtraEditors.Controls.ProcessNewValueEventHandler(this.lkpLocation_ProcessNewValue);
//
// cmbOP
//
resources.ApplyResources(this.cmbOP, "cmbOP");
this.cmbOP.Name = "cmbOP";
this.cmbOP.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(((DevExpress.XtraEditors.Controls.ButtonPredefines)(resources.GetObject("cmbOP.Properties.Buttons"))))});
this.cmbOP.Properties.Items.AddRange(new object[] {
resources.GetString("cmbOP.Properties.Items"),
resources.GetString("cmbOP.Properties.Items1"),
resources.GetString("cmbOP.Properties.Items2")});
this.cmbOP.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
this.cmbOP.StyleController = this.layoutControl1;
conditionValidationRule4.ConditionOperator = DevExpress.XtraEditors.DXErrorProvider.ConditionOperator.IsNotBlank;
resources.ApplyResources(conditionValidationRule4, "conditionValidationRule4");
conditionValidationRule4.ErrorType = DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning;
this.dxValidationProvider1.SetValidationRule(this.cmbOP, conditionValidationRule4);
//
// btnSchliessen
//
resources.ApplyResources(this.btnSchliessen, "btnSchliessen");
this.btnSchliessen.Name = "btnSchliessen";
this.btnSchliessen.StyleController = this.layoutControl1;
this.btnSchliessen.Click += new System.EventHandler(this.btnSchliessen_Click);
//
// btnSpeichern
//
resources.ApplyResources(this.btnSpeichern, "btnSpeichern");
this.btnSpeichern.Name = "btnSpeichern";
this.btnSpeichern.StyleController = this.layoutControl1;
this.btnSpeichern.Click += new System.EventHandler(this.btnSpeichern_Click);
//
// txtServerName
//
resources.ApplyResources(this.txtServerName, "txtServerName");
this.txtServerName.Name = "txtServerName";
this.txtServerName.Properties.CharacterCasing = System.Windows.Forms.CharacterCasing.Upper;
this.txtServerName.Properties.MaxLength = 20;
this.txtServerName.StyleController = this.layoutControl1;
conditionValidationRule1.ConditionOperator = DevExpress.XtraEditors.DXErrorProvider.ConditionOperator.IsNotBlank;
resources.ApplyResources(conditionValidationRule1, "conditionValidationRule1");
conditionValidationRule1.ErrorType = DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning;
this.dxValidationProvider1.SetValidationRule(this.txtServerName, conditionValidationRule1);
//
// layoutControlGroup1
//
resources.ApplyResources(this.layoutControlGroup1, "layoutControlGroup1");
this.layoutControlGroup1.Items.AddRange(new DevExpress.XtraLayout.BaseLayoutItem[] {
this.layoutControlItem1,
this.emptySpaceItem1,
this.layoutControlItem2,
this.layoutControlItem3,
this.layoutControlItem4,
this.layoutControlItem5,
this.layoutControlItem6});
this.layoutControlGroup1.Location = new System.Drawing.Point(0, 0);
this.layoutControlGroup1.Name = "Root";
this.layoutControlGroup1.Size = new System.Drawing.Size(326, 160);
this.layoutControlGroup1.Spacing = new DevExpress.XtraLayout.Utils.Padding(0, 0, 0, 0);
this.layoutControlGroup1.TextVisible = false;
//
// layoutControlItem1
//
this.layoutControlItem1.Control = this.txtServerName;
resources.ApplyResources(this.layoutControlItem1, "layoutControlItem1");
this.layoutControlItem1.Location = new System.Drawing.Point(0, 31);
this.layoutControlItem1.Name = "layoutControlItem1";
this.layoutControlItem1.Size = new System.Drawing.Size(324, 31);
this.layoutControlItem1.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem1.TextSize = new System.Drawing.Size(86, 20);
//
// emptySpaceItem1
//
resources.ApplyResources(this.emptySpaceItem1, "emptySpaceItem1");
this.emptySpaceItem1.Location = new System.Drawing.Point(0, 124);
this.emptySpaceItem1.Name = "emptySpaceItem1";
this.emptySpaceItem1.Size = new System.Drawing.Size(158, 34);
this.emptySpaceItem1.TextSize = new System.Drawing.Size(0, 0);
//
// layoutControlItem2
//
this.layoutControlItem2.Control = this.btnSpeichern;
resources.ApplyResources(this.layoutControlItem2, "layoutControlItem2");
this.layoutControlItem2.Location = new System.Drawing.Point(158, 124);
this.layoutControlItem2.Name = "layoutControlItem2";
this.layoutControlItem2.Size = new System.Drawing.Size(85, 34);
this.layoutControlItem2.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem2.TextSize = new System.Drawing.Size(0, 0);
this.layoutControlItem2.TextToControlDistance = 0;
this.layoutControlItem2.TextVisible = false;
//
// layoutControlItem3
//
this.layoutControlItem3.Control = this.btnSchliessen;
resources.ApplyResources(this.layoutControlItem3, "layoutControlItem3");
this.layoutControlItem3.Location = new System.Drawing.Point(243, 124);
this.layoutControlItem3.Name = "layoutControlItem3";
this.layoutControlItem3.Size = new System.Drawing.Size(81, 34);
this.layoutControlItem3.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem3.TextSize = new System.Drawing.Size(0, 0);
this.layoutControlItem3.TextToControlDistance = 0;
this.layoutControlItem3.TextVisible = false;
//
// layoutControlItem4
//
this.layoutControlItem4.Control = this.cmbOP;
resources.ApplyResources(this.layoutControlItem4, "layoutControlItem4");
this.layoutControlItem4.Location = new System.Drawing.Point(0, 93);
this.layoutControlItem4.Name = "layoutControlItem4";
this.layoutControlItem4.Size = new System.Drawing.Size(324, 31);
this.layoutControlItem4.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem4.TextSize = new System.Drawing.Size(86, 20);
//
// layoutControlItem5
//
this.layoutControlItem5.Control = this.lkpLocation;
resources.ApplyResources(this.layoutControlItem5, "layoutControlItem5");
this.layoutControlItem5.Location = new System.Drawing.Point(0, 0);
this.layoutControlItem5.Name = "layoutControlItem5";
this.layoutControlItem5.Size = new System.Drawing.Size(324, 31);
this.layoutControlItem5.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem5.TextSize = new System.Drawing.Size(86, 20);
//
// layoutControlItem6
//
this.layoutControlItem6.Control = this.txtStandort;
resources.ApplyResources(this.layoutControlItem6, "layoutControlItem6");
this.layoutControlItem6.Location = new System.Drawing.Point(0, 62);
this.layoutControlItem6.Name = "layoutControlItem6";
this.layoutControlItem6.Size = new System.Drawing.Size(324, 31);
this.layoutControlItem6.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem6.TextSize = new System.Drawing.Size(86, 20);
//
// dxValidationProvider1
//
this.dxValidationProvider1.ValidationMode = DevExpress.XtraEditors.DXErrorProvider.ValidationMode.Manual;
//
// layoutControlGroup2
//
resources.ApplyResources(this.layoutControlGroup2, "layoutControlGroup2");
this.layoutControlGroup2.Location = new System.Drawing.Point(0, 124);
this.layoutControlGroup2.Name = "layoutControlGroup2";
this.layoutControlGroup2.Size = new System.Drawing.Size(345, 56);
//
// frmServerDetail
//
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.layoutControl1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.KeyPreview = true;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "frmServerDetail";
this.ShowInTaskbar = false;
this.Load += new System.EventHandler(this.frmServerDetail_Load);
this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.frmServerDetail_KeyPress);
((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).EndInit();
this.layoutControl1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.txtStandort.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.lkpLocation.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.cmbOP.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.txtServerName.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem3)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem4)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem5)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem6)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.dxValidationProvider1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup2)).EndInit();
this.ResumeLayout(false);
}
#endregion
private DevExpress.XtraLayout.LayoutControl layoutControl1;
private DevExpress.XtraLayout.LayoutControlGroup layoutControlGroup1;
private DevExpress.XtraEditors.TextEdit txtServerName;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem1;
private DevExpress.XtraLayout.EmptySpaceItem emptySpaceItem1;
private DevExpress.XtraEditors.SimpleButton btnSchliessen;
private DevExpress.XtraEditors.SimpleButton btnSpeichern;
private DevExpress.XtraEditors.DXErrorProvider.DXValidationProvider dxValidationProvider1;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem2;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem3;
private DevExpress.XtraEditors.ComboBoxEdit cmbOP;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem4;
private DevExpress.XtraEditors.LookUpEdit lkpLocation;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem5;
private DevExpress.XtraEditors.TextEdit txtStandort;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem6;
private DevExpress.XtraLayout.LayoutControlGroup layoutControlGroup2;
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace DriverAssistent_WebService.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
private const int DefaultCollectionSize = 3;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
// <copyright file="DummyClient.cs" company="Google Inc.">
// Copyright (C) 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
namespace GooglePlayGames.BasicApi
{
using System;
using GooglePlayGames.BasicApi.Multiplayer;
using GooglePlayGames.OurUtils;
using UnityEngine.SocialPlatforms;
public class DummyClient : IPlayGamesClient
{
public void Authenticate(System.Action<bool> callback, bool silent)
{
LogUsage();
if (callback != null)
{
callback.Invoke(false);
}
}
public bool IsAuthenticated()
{
LogUsage();
return false;
}
public void SignOut()
{
LogUsage();
}
public string GetAccessToken()
{
LogUsage();
return "DummyAccessToken";
}
public string GetIdToken()
{
LogUsage();
return "DummyIdToken";
}
public string GetUserId()
{
LogUsage();
return "DummyID";
}
public string GetToken()
{
return "DummyToken";
}
public string GetUserEmail()
{
return string.Empty;
}
public string GetUserDisplayName()
{
LogUsage();
return "Player";
}
public string GetUserImageUrl()
{
LogUsage();
return null;
}
public void LoadUsers(string[] userIds, Action<IUserProfile[]> callback)
{
LogUsage();
if (callback != null)
{
callback.Invoke(null);
}
}
public void LoadAchievements(Action<Achievement[]> callback)
{
LogUsage();
if (callback != null)
{
callback.Invoke(null);
}
}
public Achievement GetAchievement(string achId)
{
LogUsage();
return null;
}
public void UnlockAchievement(string achId, Action<bool> callback)
{
LogUsage();
if (callback != null)
{
callback.Invoke(false);
}
}
public void RevealAchievement(string achId, Action<bool> callback)
{
LogUsage();
if (callback != null)
{
callback.Invoke(false);
}
}
public void IncrementAchievement(string achId, int steps, Action<bool> callback)
{
LogUsage();
if (callback != null)
{
callback.Invoke(false);
}
}
public void SetStepsAtLeast(string achId, int steps, Action<bool> callback)
{
LogUsage();
if (callback != null)
{
callback.Invoke(false);
}
}
public void ShowAchievementsUI(Action<UIStatus> callback)
{
LogUsage();
if (callback != null)
{
callback.Invoke(UIStatus.VersionUpdateRequired);
}
}
public void ShowLeaderboardUI(string lbId, LeaderboardTimeSpan span,
Action<UIStatus> callback)
{
LogUsage();
if (callback != null)
{
callback.Invoke(UIStatus.VersionUpdateRequired);
}
}
public int LeaderboardMaxResults()
{
return 25;
}
public void LoadScores(string leaderboardId, LeaderboardStart start,
int rowCount, LeaderboardCollection collection,
LeaderboardTimeSpan timeSpan,
Action<LeaderboardScoreData> callback)
{
LogUsage();
if (callback != null)
{
callback(new LeaderboardScoreData(leaderboardId,
ResponseStatus.LicenseCheckFailed));
}
}
public void LoadMoreScores(ScorePageToken token, int rowCount,
Action<LeaderboardScoreData> callback)
{
LogUsage();
if (callback != null)
{
callback(new LeaderboardScoreData(token.LeaderboardId,
ResponseStatus.LicenseCheckFailed));
}
}
public void SubmitScore(string lbId, long score, Action<bool> callback)
{
LogUsage();
if (callback != null)
{
callback.Invoke(false);
}
}
public void SubmitScore(string lbId, long score, string metadata,
Action<bool> callback)
{
LogUsage();
if (callback != null)
{
callback.Invoke(false);
}
}
public IRealTimeMultiplayerClient GetRtmpClient()
{
LogUsage();
return null;
}
public ITurnBasedMultiplayerClient GetTbmpClient()
{
LogUsage();
return null;
}
public SavedGame.ISavedGameClient GetSavedGameClient()
{
LogUsage();
return null;
}
public GooglePlayGames.BasicApi.Events.IEventsClient GetEventsClient()
{
LogUsage();
return null;
}
public GooglePlayGames.BasicApi.Quests.IQuestsClient GetQuestsClient()
{
LogUsage();
return null;
}
public void RegisterInvitationDelegate(InvitationReceivedDelegate deleg)
{
LogUsage();
}
public Invitation GetInvitationFromNotification()
{
LogUsage();
return null;
}
public bool HasInvitationFromNotification()
{
LogUsage();
return false;
}
public void LoadFriends(Action<bool> callback)
{
LogUsage();
callback(false);
}
public IUserProfile[] GetFriends()
{
LogUsage();
return new IUserProfile[0];
}
private static void LogUsage()
{
Logger.d("Received method call on DummyClient - using stub implementation.");
}
}
}
| |
#region License
//
// PrimitiveKey.cs July 2007
//
// Copyright (C) 2007, Niall Gallagher <niallg@users.sf.net>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
//
#endregion
#region Using directives
using SimpleFramework.Xml.Strategy;
using SimpleFramework.Xml.Stream;
using System;
#endregion
namespace SimpleFramework.Xml.Core {
/// <summary>
/// The <c>PrimitiveKey</c> is used to serialize a primitive key
/// to and from a node. If a key name is provided in the annotation
/// then this will serialize and deserialize that key with the given
/// name, if the key is an attribute, then it is written using the
/// provided name.
/// </code>
/// <entry key="one">example one</entry>
/// <entry key="two">example two</entry>
/// <entry key="three">example three</entry>
/// </code>
/// Allowing the key to be written as either an XML attribute or an
/// element enables a more flexible means for representing the key.
/// Composite elements can not be used as attribute values as they do
/// not serialize to a string. Primitive keys as elements can be
/// maintained as references using the cycle strategy.
/// </summary>
/// <seealso>
/// SimpleFramework.Xml.Core.CompositeMap
/// </seealso>
class PrimitiveKey : Converter {
/// <summary>
/// The primitive factory used to resolve the primitive to a string.
/// </summary>
private readonly PrimitiveFactory factory;
/// <summary>
/// This is the context used to support the serialization process.
/// </summary>
private readonly Context context;
/// <summary>
/// The primitive converter used to read the key from the node.
/// </summary>
private readonly Primitive root;
/// <summary>
/// This is the style used to style the XML elements for the key.
/// </summary>
private readonly Style style;
/// <summary>
/// The entry object contains the details on how to write the key.
/// </summary>
private readonly Entry entry;
/// <summary>
/// Represents the primitive type the key is serialized to and from.
/// </summary>
private readonly Type type;
/// <summary>
/// Constructor for the <c>PrimitiveKey</c> object. This is
/// used to create the key object which converts the map key to an
/// instance of the key type. This can also resolve references.
/// </summary>
/// <param name="context">
/// this is the context object used for serialization
/// </param>
/// <param name="entry">
/// this is the entry object that describes entries
/// </param>
/// <param name="type">
/// this is the type that this converter deals with
/// </param>
public PrimitiveKey(Context context, Entry entry, Type type) {
this.factory = new PrimitiveFactory(context, type);
this.root = new Primitive(context, type);
this.style = context.Style;
this.context = context;
this.entry = entry;
this.type = type;
}
/// <summary>
/// This method is used to read the key value from the node. The
/// value read from the node is resolved using the template filter.
/// If the key value can not be found according to the annotation
/// attributes then an exception is thrown.
/// </summary>
/// <param name="node">
/// this is the node to read the key value from
/// </param>
/// <returns>
/// this returns the value deserialized from the node
/// </returns>
public Object Read(InputNode node) {
Class expect = type.Type;
String name = entry.Key;
if(name == null) {
name = context.GetName(expect);
}
if(!entry.IsAttribute()) {
return ReadElement(node, name);
}
return ReadAttribute(node, name);
}
/// <summary>
/// This method is used to read the key value from the node. The
/// value read from the node is resolved using the template filter.
/// If the key value can not be found according to the annotation
/// attributes then an exception is thrown.
/// </summary>
/// <param name="node">
/// this is the node to read the key value from
/// </param>
/// <param name="value">
/// this is the value to deserialize in to
/// </param>
/// <returns>
/// this returns the value deserialized from the node
/// </returns>
public Object Read(InputNode node, Object value) {
Class expect = type.Type;
if(value != null) {
throw new PersistenceException("Can not read key of %s", expect);
}
return Read(node);
}
/// <summary>
/// This method is used to read the key value from the node. The
/// value read from the node is resolved using the template filter.
/// If the key value can not be found according to the annotation
/// attributes then an null is assumed and returned.
/// </summary>
/// <param name="node">
/// this is the node to read the key value from
/// </param>
/// <param name="key">
/// this is the name of the attribute used by the key
/// </param>
/// <returns>
/// this returns the value deserialized from the node
/// </returns>
public Object ReadAttribute(InputNode node, String key) {
String name = style.GetAttribute(key);
InputNode child = node.GetAttribute(name);
if(child == null) {
return null;
}
return root.Read(child);
}
/// <summary>
/// This method is used to read the key value from the node. The
/// value read from the node is resolved using the template filter.
/// If the key value can not be found according to the annotation
/// attributes then null is assumed and returned.
/// </summary>
/// <param name="node">
/// this is the node to read the key value from
/// </param>
/// <param name="key">
/// this is the name of the element used by the key
/// </param>
/// <returns>
/// this returns the value deserialized from the node
/// </returns>
public Object ReadElement(InputNode node, String key) {
String name = style.GetElement(key);
InputNode child = node.getNext(name);
if(child == null) {
return null;
}
return root.Read(child);
}
/// <summary>
/// This method is used to read the key value from the node. The
/// value read from the node is resolved using the template filter.
/// If the key value can not be found according to the annotation
/// attributes then the node is considered as null and is valid.
/// </summary>
/// <param name="node">
/// this is the node to read the key value from
/// </param>
/// <returns>
/// this returns the value deserialized from the node
/// </returns>
public bool Validate(InputNode node) {
Class expect = type.Type;
String name = entry.Key;
if(name == null) {
name = context.GetName(expect);
}
if(!entry.IsAttribute()) {
return ValidateElement(node, name);
}
return ValidateAttribute(node, name);
}
/// <summary>
/// This method is used to read the key value from the node. The
/// value read from the node is resolved using the template filter.
/// If the key value can not be found according to the annotation
/// attributes then the node is considered as null and is valid.
/// </summary>
/// <param name="node">
/// this is the node to read the key value from
/// </param>
/// <param name="key">
/// this is the name of the attribute used by the key
/// </param>
/// <returns>
/// this returns the value deserialized from the node
/// </returns>
public bool ValidateAttribute(InputNode node, String key) {
String name = style.GetElement(key);
InputNode child = node.GetAttribute(name);
if(child == null) {
return true;
}
return root.Validate(child);
}
/// <summary>
/// This method is used to read the key value from the node. The
/// value read from the node is resolved using the template filter.
/// If the key value can not be found according to the annotation
/// attributes then the node is considered as null and is valid.
/// </summary>
/// <param name="node">
/// this is the node to read the key value from
/// </param>
/// <param name="key">
/// this is the name of the element used by the key
/// </param>
/// <returns>
/// this returns the value deserialized from the node
/// </returns>
public bool ValidateElement(InputNode node, String key) {
String name = style.GetElement(key);
InputNode child = node.getNext(name);
if(child == null) {
return true;
}
return root.Validate(child);
}
/// <summary>
/// This method is used to write the value to the specified node.
/// The value written to the node can be an attribute or an element
/// depending on the annotation attribute values. This method will
/// maintain references for serialized elements.
/// </summary>
/// <param name="node">
/// this is the node that the value is written to
/// </param>
/// <param name="item">
/// this is the item that is to be written
/// </param>
public void Write(OutputNode node, Object item) {
if(!entry.IsAttribute()) {
WriteElement(node, item);
} else if(item != null) {
WriteAttribute(node, item);
}
}
/// <summary>
/// This method is used to write the value to the specified node.
/// This will write the item as an element to the provided node,
/// also this enables references to be used during serialization.
/// </summary>
/// <param name="node">
/// this is the node that the value is written to
/// </param>
/// <param name="item">
/// this is the item that is to be written
/// </param>
public void WriteElement(OutputNode node, Object item) {
Class expect = type.Type;
String key = entry.Key;
if(key == null) {
key = context.GetName(expect);
}
String name = style.GetElement(key);
OutputNode child = node.getChild(name);
if(item != null) {
if(!IsOverridden(child, item)) {
root.Write(child, item);
}
}
}
/// <summary>
/// This method is used to write the value to the specified node.
/// This will write the item as an attribute to the provided node,
/// the name of the attribute is taken from the annotation.
/// </summary>
/// <param name="node">
/// this is the node that the value is written to
/// </param>
/// <param name="item">
/// this is the item that is to be written
/// </param>
public void WriteAttribute(OutputNode node, Object item) {
Class expect = type.Type;
String text = factory.GetText(item);
String key = entry.Key;
if(key == null) {
key = context.GetName(expect);
}
String name = style.GetAttribute(key);
if(text != null) {
node.setAttribute(name, text);
}
}
/// <summary>
/// This is used to determine whether the specified value has been
/// overridden by the strategy. If the item has been overridden
/// then no more serialization is require for that value, this is
/// effectively telling the serialization process to stop writing.
/// </summary>
/// <param name="node">
/// the node that a potential override is written to
/// </param>
/// <param name="value">
/// this is the object instance to be serialized
/// </param>
/// <returns>
/// returns true if the strategy overrides the object
/// </returns>
public bool IsOverridden(OutputNode node, Object value) {
return factory.SetOverride(type, value, node);
}
}
}
| |
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Tynamix.ObjectFiller.Test.TestPoco.Person;
namespace Tynamix.ObjectFiller.Test
{
[TestClass]
public class PersonFillingTest
{
[TestMethod]
public void TestFillPerson()
{
Filler<Person> pFiller = new Filler<Person>();
pFiller.Setup()
.OnType<IAddress>().CreateInstanceOf<Address>();
Person filledPerson = pFiller.Create();
Assert.IsNotNull(filledPerson.Address);
Assert.IsNotNull(filledPerson.Addresses);
Assert.IsNotNull(filledPerson.StringToIAddress);
Assert.IsNotNull(filledPerson.SureNames);
}
[TestMethod]
public void TestFillPersonWithEnumerable()
{
Filler<Person> pFiller = new Filler<Person>();
pFiller.Setup()
.OnType<IAddress>().CreateInstanceOf<Address>()
.OnProperty(x => x.Age).Use(Enumerable.Range(18, 60));
Person filledPerson = pFiller.Create();
Assert.IsNotNull(filledPerson.Address);
Assert.IsNotNull(filledPerson.Addresses);
Assert.IsNotNull(filledPerson.StringToIAddress);
Assert.IsNotNull(filledPerson.SureNames);
}
[TestMethod]
public void TestNameListStringRandomizer()
{
Filler<Person> pFiller = new Filler<Person>();
pFiller.Setup().OnType<IAddress>().CreateInstanceOf<Address>()
.OnProperty(p => p.FirstName).Use(new RealNames(NameStyle.FirstName))
.OnProperty(p => p.LastName).Use(new RealNames(NameStyle.LastName));
Person filledPerson = pFiller.Create();
Assert.IsNotNull(filledPerson.FirstName);
Assert.IsNotNull(filledPerson.LastName);
}
[TestMethod]
public void TestFirstNameAsConstantLastNameAsRealName()
{
Filler<Person> pFiller = new Filler<Person>();
pFiller.Setup()
.OnType<IAddress>().CreateInstanceOf<Address>()
.OnProperty(p => p.FirstName).Use(() => "John")
.OnProperty(p => p.LastName).Use(new RealNames(NameStyle.LastName));
Person filledPerson = pFiller.Create();
Assert.IsNotNull(filledPerson.FirstName);
Assert.AreEqual("John", filledPerson.FirstName);
Assert.IsNotNull(filledPerson.LastName);
}
[TestMethod]
public void GeneratePersonWithGivenSetOfNamesAndAges()
{
List<string> names = new List<string> { "Tom", "Maik", "John", "Leo" };
List<int> ages = new List<int> { 10, 15, 18, 22, 26 };
Filler<Person> pFiller = new Filler<Person>();
pFiller.Setup()
.OnType<IAddress>().CreateInstanceOf<Address>()
.OnProperty(p => p.FirstName).Use(new RandomListItem<string>(names))
.OnProperty(p => p.Age).Use(new RandomListItem<int>(ages));
var pF = pFiller.Create();
Assert.IsTrue(names.Contains(pF.FirstName));
Assert.IsTrue(ages.Contains(pF.Age));
}
[TestMethod]
public void BigComplicated()
{
Filler<Person> pFiller = new Filler<Person>();
pFiller.Setup()
.OnType<IAddress>().CreateInstanceOf<Address>()
.OnProperty(p => p.LastName, p => p.FirstName).DoIt(At.TheEnd).Use(new RealNames(NameStyle.FirstName))
.OnProperty(p => p.Age).Use(() =>Random.Next(10, 32))
.SetupFor<Address>()
.OnProperty(a => a.City).Use(new MnemonicString(1))
.OnProperty(a => a.Street).IgnoreIt();
var pF = pFiller.Create();
Assert.IsNotNull(pF);
Assert.IsNotNull(pF.Address);
Assert.IsNull(pF.Address.Street);
}
[TestMethod]
public void FluentTest()
{
Filler<Person> pFiller = new Filler<Person>();
pFiller.Setup()
.OnProperty(x => x.Age).Use(() => 18)
.OnType<IAddress>().CreateInstanceOf<Address>();
Person p = pFiller.Create();
Assert.IsNotNull(p);
Assert.AreEqual(18, p.Age);
}
[TestMethod]
public void TestSetupForTypeOverrideSettings()
{
Filler<Person> pFiller = new Filler<Person>();
pFiller.Setup()
.OnType<IAddress>().CreateInstanceOf<Address>()
.OnType<int>().Use(() => 1)
.SetupFor<Address>(true);
Person p = pFiller.Create();
Assert.AreEqual(1, p.Age);
Assert.AreNotEqual(1, p.Address.HouseNumber);
}
[TestMethod]
public void TestSetupForTypeWithoutOverrideSettings()
{
Filler<Person> pFiller = new Filler<Person>();
pFiller.Setup()
.OnType<IAddress>().CreateInstanceOf<Address>()
.OnType<int>().Use(() => 1)
.SetupFor<Address>();
Person p = pFiller.Create();
Assert.AreEqual(1, p.Age);
Assert.AreEqual(1, p.Address.HouseNumber);
}
[TestMethod]
public void TestIgnoreAllOfType()
{
Filler<Person> pFiller = new Filler<Person>();
pFiller.Setup()
.OnType<IAddress>().CreateInstanceOf<Address>()
.OnType<string>().IgnoreIt()
;
Person p = pFiller.Create();
Assert.IsNotNull(p);
Assert.IsNull(p.FirstName);
Assert.IsNotNull(p.Address);
Assert.IsNull(p.Address.City);
}
[TestMethod]
public void TestIgnoreAllOfComplexType()
{
Filler<Person> pFiller = new Filler<Person>();
pFiller.Setup()
.OnType<IAddress>().CreateInstanceOf<Address>()
.OnType<Address>().IgnoreIt()
.OnType<IAddress>().IgnoreIt();
Person p = pFiller.Create();
Assert.IsNotNull(p);
Assert.IsNull(p.Address);
}
[TestMethod]
public void TestIgnoreAllOfTypeDictionary()
{
Filler<Person> pFiller = new Filler<Person>();
pFiller.Setup()
.OnType<IAddress>().CreateInstanceOf<Address>()
.OnType<Address>().IgnoreIt()
.OnType<IAddress>().IgnoreIt()
.OnType<Dictionary<string, IAddress>>().IgnoreIt();
Person p = pFiller.Create();
Assert.IsNotNull(p);
Assert.IsNull(p.Address);
Assert.IsNull(p.StringToIAddress);
}
[TestMethod]
public void TestPropertyOrderDoNameLast()
{
Filler<OrderedPersonProperties> filler = new Filler<OrderedPersonProperties>();
filler.Setup()
.OnProperty(x => x.Name).DoIt(At.TheEnd).UseDefault();
var p = filler.Create();
Assert.IsNotNull(p);
Assert.AreEqual(3, p.NameCount);
}
[TestMethod]
public void TestPropertyOrderDoNameFirst()
{
Filler<OrderedPersonProperties> filler = new Filler<OrderedPersonProperties>();
filler.Setup()
.OnProperty(x => x.Name).DoIt(At.TheBegin).UseDefault();
var p = filler.Create();
Assert.IsNotNull(p);
Assert.AreEqual(1, p.NameCount);
}
}
}
| |
using Avalonia.Media;
using SkiaSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using Avalonia.Platform;
using Avalonia.Rendering;
using Avalonia.Rendering.Utilities;
namespace Avalonia.Skia
{
internal class DrawingContextImpl : IDrawingContextImpl
{
private readonly Vector _dpi;
private readonly Matrix? _postTransform;
private readonly IDisposable[] _disposables;
private readonly IVisualBrushRenderer _visualBrushRenderer;
private Stack<PaintWrapper> maskStack = new Stack<PaintWrapper>();
public SKCanvas Canvas { get; private set; }
public DrawingContextImpl(
SKCanvas canvas,
Vector dpi,
IVisualBrushRenderer visualBrushRenderer,
params IDisposable[] disposables)
{
_dpi = dpi;
if (dpi.X != 96 || dpi.Y != 96)
_postTransform = Matrix.CreateScale(dpi.X / 96, dpi.Y / 96);
_visualBrushRenderer = visualBrushRenderer;
_disposables = disposables;
Canvas = canvas;
Transform = Matrix.Identity;
}
public void Clear(Color color)
{
Canvas.Clear(color.ToSKColor());
}
public void DrawImage(IBitmapImpl source, double opacity, Rect sourceRect, Rect destRect)
{
var impl = (BitmapImpl)source;
var s = sourceRect.ToSKRect();
var d = destRect.ToSKRect();
using (var paint = new SKPaint()
{ Color = new SKColor(255, 255, 255, (byte)(255 * opacity)) })
{
Canvas.DrawBitmap(impl.Bitmap, s, d, paint);
}
}
public void DrawImage(IBitmapImpl source, IBrush opacityMask, Rect opacityMaskRect, Rect destRect)
{
PushOpacityMask(opacityMask, opacityMaskRect);
DrawImage(source, 1, new Rect(0, 0, source.PixelWidth, source.PixelHeight), destRect);
PopOpacityMask();
}
public void DrawLine(Pen pen, Point p1, Point p2)
{
using (var paint = CreatePaint(pen, new Size(Math.Abs(p2.X - p1.X), Math.Abs(p2.Y - p1.Y))))
{
Canvas.DrawLine((float)p1.X, (float)p1.Y, (float)p2.X, (float)p2.Y, paint.Paint);
}
}
public void DrawGeometry(IBrush brush, Pen pen, IGeometryImpl geometry)
{
var impl = (StreamGeometryImpl)geometry;
var size = geometry.Bounds.Size;
using (var fill = brush != null ? CreatePaint(brush, size) : default(PaintWrapper))
using (var stroke = pen?.Brush != null ? CreatePaint(pen, size) : default(PaintWrapper))
{
if (fill.Paint != null)
{
Canvas.DrawPath(impl.EffectivePath, fill.Paint);
}
if (stroke.Paint != null)
{
Canvas.DrawPath(impl.EffectivePath, stroke.Paint);
}
}
}
private struct PaintState : IDisposable
{
private readonly SKColor _color;
private readonly SKShader _shader;
private readonly SKPaint _paint;
public PaintState(SKPaint paint, SKColor color, SKShader shader)
{
_paint = paint;
_color = color;
_shader = shader;
}
public void Dispose()
{
_paint.Color = _color;
_paint.Shader = _shader;
}
}
internal struct PaintWrapper : IDisposable
{
//We are saving memory allocations there
//TODO: add more disposable fields if needed
public readonly SKPaint Paint;
private IDisposable _disposable1;
public IDisposable ApplyTo(SKPaint paint)
{
var state = new PaintState(paint, paint.Color, paint.Shader);
paint.Color = Paint.Color;
paint.Shader = Paint.Shader;
return state;
}
public void AddDisposable(IDisposable disposable)
{
if (_disposable1 == null)
_disposable1 = disposable;
else
throw new InvalidOperationException();
}
public PaintWrapper(SKPaint paint)
{
Paint = paint;
_disposable1 = null;
}
public void Dispose()
{
Paint?.Dispose();
_disposable1?.Dispose();
}
}
internal PaintWrapper CreatePaint(IBrush brush, Size targetSize)
{
SKPaint paint = new SKPaint();
var rv = new PaintWrapper(paint);
paint.IsStroke = false;
double opacity = brush.Opacity * _currentOpacity;
paint.IsAntialias = true;
var solid = brush as ISolidColorBrush;
if (solid != null)
{
paint.Color = new SKColor(solid.Color.R, solid.Color.G, solid.Color.B, (byte) (solid.Color.A * opacity));
return rv;
}
paint.Color = (new SKColor(255, 255, 255, (byte)(255 * opacity)));
var gradient = brush as IGradientBrush;
if (gradient != null)
{
var tileMode = gradient.SpreadMethod.ToSKShaderTileMode();
var stopColors = gradient.GradientStops.Select(s => s.Color.ToSKColor()).ToArray();
var stopOffsets = gradient.GradientStops.Select(s => (float)s.Offset).ToArray();
var linearGradient = brush as ILinearGradientBrush;
if (linearGradient != null)
{
var start = linearGradient.StartPoint.ToPixels(targetSize).ToSKPoint();
var end = linearGradient.EndPoint.ToPixels(targetSize).ToSKPoint();
// would be nice to cache these shaders possibly?
using (var shader = SKShader.CreateLinearGradient(start, end, stopColors, stopOffsets, tileMode))
paint.Shader = shader;
}
else
{
var radialGradient = brush as IRadialGradientBrush;
if (radialGradient != null)
{
var center = radialGradient.Center.ToPixels(targetSize).ToSKPoint();
var radius = (float)radialGradient.Radius;
// TODO: There is no SetAlpha in SkiaSharp
//paint.setAlpha(128);
// would be nice to cache these shaders possibly?
using (var shader = SKShader.CreateRadialGradient(center, radius, stopColors, stopOffsets, tileMode))
paint.Shader = shader;
}
}
return rv;
}
var tileBrush = brush as ITileBrush;
var visualBrush = brush as IVisualBrush;
var tileBrushImage = default(BitmapImpl);
if (visualBrush != null)
{
if (_visualBrushRenderer != null)
{
var intermediateSize = _visualBrushRenderer.GetRenderTargetSize(visualBrush);
if (intermediateSize.Width >= 1 && intermediateSize.Height >= 1)
{
var intermediate = new BitmapImpl((int)intermediateSize.Width, (int)intermediateSize.Height, _dpi);
using (var ctx = intermediate.CreateDrawingContext(_visualBrushRenderer))
{
ctx.Clear(Colors.Transparent);
_visualBrushRenderer.RenderVisualBrush(ctx, visualBrush);
}
rv.AddDisposable(tileBrushImage);
tileBrushImage = intermediate;
}
}
else
{
throw new NotSupportedException("No IVisualBrushRenderer was supplied to DrawingContextImpl.");
}
}
else
{
tileBrushImage = (BitmapImpl)((tileBrush as IImageBrush)?.Source?.PlatformImpl);
}
if (tileBrush != null && tileBrushImage != null)
{
var calc = new TileBrushCalculator(tileBrush, new Size(tileBrushImage.PixelWidth, tileBrushImage.PixelHeight), targetSize);
var bitmap = new BitmapImpl((int)calc.IntermediateSize.Width, (int)calc.IntermediateSize.Height, _dpi);
rv.AddDisposable(bitmap);
using (var context = bitmap.CreateDrawingContext(null))
{
var rect = new Rect(0, 0, tileBrushImage.PixelWidth, tileBrushImage.PixelHeight);
context.Clear(Colors.Transparent);
context.PushClip(calc.IntermediateClip);
context.Transform = calc.IntermediateTransform;
context.DrawImage(tileBrushImage, 1, rect, rect);
context.PopClip();
}
SKMatrix translation = SKMatrix.MakeTranslation(-(float)calc.DestinationRect.X, -(float)calc.DestinationRect.Y);
SKShaderTileMode tileX =
tileBrush.TileMode == TileMode.None
? SKShaderTileMode.Clamp
: tileBrush.TileMode == TileMode.FlipX || tileBrush.TileMode == TileMode.FlipXY
? SKShaderTileMode.Mirror
: SKShaderTileMode.Repeat;
SKShaderTileMode tileY =
tileBrush.TileMode == TileMode.None
? SKShaderTileMode.Clamp
: tileBrush.TileMode == TileMode.FlipY || tileBrush.TileMode == TileMode.FlipXY
? SKShaderTileMode.Mirror
: SKShaderTileMode.Repeat;
using (var shader = SKShader.CreateBitmap(bitmap.Bitmap, tileX, tileY, translation))
paint.Shader = shader;
}
return rv;
}
private PaintWrapper CreatePaint(Pen pen, Size targetSize)
{
var rv = CreatePaint(pen.Brush, targetSize);
var paint = rv.Paint;
paint.IsStroke = true;
paint.StrokeWidth = (float)pen.Thickness;
if (pen.StartLineCap == PenLineCap.Round)
paint.StrokeCap = SKStrokeCap.Round;
else if (pen.StartLineCap == PenLineCap.Square)
paint.StrokeCap = SKStrokeCap.Square;
else
paint.StrokeCap = SKStrokeCap.Butt;
if (pen.LineJoin == PenLineJoin.Miter)
paint.StrokeJoin = SKStrokeJoin.Miter;
else if (pen.LineJoin == PenLineJoin.Round)
paint.StrokeJoin = SKStrokeJoin.Round;
else
paint.StrokeJoin = SKStrokeJoin.Bevel;
paint.StrokeMiter = (float)pen.MiterLimit;
if (pen.DashStyle?.Dashes != null && pen.DashStyle.Dashes.Count > 0)
{
var pe = SKPathEffect.CreateDash(
pen.DashStyle?.Dashes.Select(x => (float)x).ToArray(),
(float)pen.DashStyle.Offset);
paint.PathEffect = pe;
rv.AddDisposable(pe);
}
return rv;
}
public void DrawRectangle(Pen pen, Rect rect, float cornerRadius = 0)
{
using (var paint = CreatePaint(pen, rect.Size))
{
var rc = rect.ToSKRect();
if (cornerRadius == 0)
{
Canvas.DrawRect(rc, paint.Paint);
}
else
{
Canvas.DrawRoundRect(rc, cornerRadius, cornerRadius, paint.Paint);
}
}
}
public void FillRectangle(IBrush brush, Rect rect, float cornerRadius = 0)
{
using (var paint = CreatePaint(brush, rect.Size))
{
var rc = rect.ToSKRect();
if (cornerRadius == 0)
{
Canvas.DrawRect(rc, paint.Paint);
}
else
{
Canvas.DrawRoundRect(rc, cornerRadius, cornerRadius, paint.Paint);
}
}
}
public void DrawText(IBrush foreground, Point origin, IFormattedTextImpl text)
{
using (var paint = CreatePaint(foreground, text.Size))
{
var textImpl = (FormattedTextImpl)text;
textImpl.Draw(this, Canvas, origin.ToSKPoint(), paint);
}
}
public void PushClip(Rect clip)
{
Canvas.Save();
Canvas.ClipRect(clip.ToSKRect());
}
public void PopClip()
{
Canvas.Restore();
}
private double _currentOpacity = 1.0f;
private readonly Stack<double> _opacityStack = new Stack<double>();
public void PushOpacity(double opacity)
{
_opacityStack.Push(_currentOpacity);
_currentOpacity *= opacity;
}
public void PopOpacity()
{
_currentOpacity = _opacityStack.Pop();
}
public virtual void Dispose()
{
if(_disposables!=null)
foreach (var disposable in _disposables)
disposable?.Dispose();
}
public void PushGeometryClip(IGeometryImpl clip)
{
Canvas.Save();
Canvas.ClipPath(((StreamGeometryImpl)clip).EffectivePath);
}
public void PopGeometryClip()
{
Canvas.Restore();
}
public void PushOpacityMask(IBrush mask, Rect bounds)
{
Canvas.SaveLayer(new SKPaint());
maskStack.Push(CreatePaint(mask, bounds.Size));
}
public void PopOpacityMask()
{
Canvas.SaveLayer(new SKPaint { BlendMode = SKBlendMode.DstIn });
using (var paintWrapper = maskStack.Pop())
{
Canvas.DrawPaint(paintWrapper.Paint);
}
Canvas.Restore();
Canvas.Restore();
}
private Matrix _currentTransform;
public Matrix Transform
{
get { return _currentTransform; }
set
{
if (_currentTransform == value)
return;
_currentTransform = value;
var transform = value;
if (_postTransform.HasValue)
transform *= _postTransform.Value;
Canvas.SetMatrix(transform.ToSKMatrix());
}
}
}
}
| |
/*
* BitVector32.cs - Implementation of
* "System.Collections.Specialized.BitVector32".
*
* Copyright (C) 2002 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.Collections.Specialized
{
#if !ECMA_COMPAT
using System;
using System.Text;
public struct BitVector32
{
// Internal state.
private int data;
// Constructors.
public BitVector32(int data)
{
this.data = data;
}
public BitVector32(BitVector32 value)
{
this.data = value.data;
}
// Create masks.
public static int CreateMask()
{
return 1;
}
public static int CreateMask(int previous)
{
if(previous == 0)
{
return 1;
}
else if(previous == unchecked((int)0x80000000))
{
throw new Exception(S._("Arg_MaskDone"));
}
else
{
return (previous << 1);
}
}
// Get the number of bits in a value.
private static int GetNumBits(int value)
{
int bits = 0;
value &= 0xFFFF;
while(value != 0)
{
++bits;
value >>= 1;
}
return bits;
}
// Create a bit vector section.
public static Section CreateSection(short maxValue)
{
return new Section(GetNumBits(maxValue), 0);
}
public static Section CreateSection(short maxValue, Section section)
{
return new Section(GetNumBits(maxValue),
section.offset + GetNumBits(section.mask));
}
// Return the full data for this bit vector.
public int Data
{
get
{
return data;
}
}
// Get or set a bit.
public bool this[int bit]
{
get
{
return ((data & bit) == bit);
}
set
{
if(value)
data |= bit;
else
data &= ~bit;
}
}
public int this[Section section]
{
get
{
return (data >> section.offset) & section.mask;
}
set
{
int mask = section.mask;
int offset = section.offset;
data = (data & ~(mask << offset)) |
((value & mask) << offset);
}
}
// Determine if two bit vectors are equal.
public override bool Equals(Object obj)
{
if(obj is BitVector32)
{
return (data == ((BitVector32)obj).data);
}
else
{
return false;
}
}
// Get the hash code for this bit vector.
public override int GetHashCode()
{
return data;
}
// Convert a bit vector into a string.
public static String ToString(BitVector32 value)
{
StringBuilder builder = new StringBuilder();
builder.Append("BitVector32{");
uint data = (uint)(value.data);
uint mask = 0x80000000;
int bit;
for(bit = 0; bit < 32; ++bit)
{
if((data & mask) != 0)
{
builder.Append('1');
}
else
{
builder.Append('0');
}
mask >>= 1;
}
builder.Append('}');
return builder.ToString();
}
public override String ToString()
{
return ToString(this);
}
// Structure that represents a bit vector section.
public struct Section
{
// Internal state.
internal short mask, offset;
// Constructor.
internal Section(int bits, int offset)
{
if((bits + offset) > 32)
{
throw new Exception(S._("Arg_MaskDone"));
}
this.mask = (short)(bits != 0 ? (1 << (bits - 1)) : 0);
this.offset = (short)offset;
}
// Properties.
public short Mask
{
get
{
return mask;
}
}
public short Offset
{
get
{
return offset;
}
}
// Determine if two sections are equal.
public override bool Equals(Object obj)
{
if(obj is Section)
{
Section sect = (Section)obj;
return (mask == sect.mask && offset == sect.offset);
}
else
{
return false;
}
}
// Get the hash code for this section.
public override int GetHashCode()
{
return mask + offset;
}
// Convert a section into a string.
public static String ToString(Section value)
{
return "Section{0x" + Convert.ToString(value.mask, 16) +
", 0x" + Convert.ToString(value.offset, 16);
}
public override String ToString()
{
return ToString(this);
}
}; // struct Section
}; // struct BitVector32
#endif // !ECMA_COMPAT
}; // namespace System.Collections.Specialized
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using ComplexTestSupport;
using Xunit;
namespace System.Numerics.Tests
{
public class implicitExplicitCastOperatorsTest
{
private static void VerifyInt16ImplicitCastToComplex(Int16 value)
{
Complex c_cast = value;
Support.VerifyRealImaginaryProperties(c_cast, value, 0.0,
string.Format("Int16ImplicitCast ({0})", value));
if (value != Int16.MaxValue)
{
Complex c_cast_plus = c_cast + 1;
Support.VerifyRealImaginaryProperties(c_cast_plus, value + 1, 0.0,
string.Format("PLuS + Int16ImplicitCast ({0})", value));
}
if (value != Int16.MinValue)
{
Complex c_cast_minus = c_cast - 1;
Support.VerifyRealImaginaryProperties(c_cast_minus, value - 1, 0.0,
string.Format("Minus - Int16ImplicitCast + 1 ({0})", value));
}
}
[Fact]
public static void RunTests_Int16ImplicitCastToComplex()
{
VerifyInt16ImplicitCastToComplex(Int16.MinValue);
for (int i = 0; i < 3; ++i)
{
Int16 randomValue = Support.GetRandomInt16Value(true);
VerifyInt16ImplicitCastToComplex(randomValue);
}
VerifyInt16ImplicitCastToComplex(-1);
VerifyInt16ImplicitCastToComplex(0);
VerifyInt16ImplicitCastToComplex(1);
for (int i = 0; i < 3; ++i)
{
Int16 randomValue = Support.GetRandomInt16Value(false);
VerifyInt16ImplicitCastToComplex(randomValue);
}
VerifyInt16ImplicitCastToComplex(Int16.MaxValue);
}
private static void VerifyInt32ImplicitCastToComplex(Int32 value)
{
Complex c_cast = value;
Support.VerifyRealImaginaryProperties(c_cast, value, 0.0,
string.Format("Int32ImplicitCast ({0})", value));
if (value != Int32.MaxValue)
{
Complex c_cast_plus = c_cast + 1;
Support.VerifyRealImaginaryProperties(c_cast_plus, value + 1, 0.0,
string.Format("PLuS + Int32ImplicitCast ({0})", value));
}
if (value != Int32.MinValue)
{
Complex c_cast_minus = c_cast - 1;
Support.VerifyRealImaginaryProperties(c_cast_minus, value - 1, 0.0,
string.Format("Minus - Int32ImplicitCast + 1 ({0})", value));
}
}
[Fact]
public static void RunTests_Int32ImplicitCastToComplex()
{
VerifyInt32ImplicitCastToComplex(Int32.MinValue);
for (int i = 0; i < 3; ++i)
{
Int32 randomValue = Support.GetRandomInt32Value(true);
VerifyInt32ImplicitCastToComplex(randomValue);
}
VerifyInt32ImplicitCastToComplex(-1);
VerifyInt32ImplicitCastToComplex(0);
VerifyInt32ImplicitCastToComplex(1);
for (int i = 0; i < 3; ++i)
{
Int32 randomValue = Support.GetRandomInt32Value(false);
VerifyInt32ImplicitCastToComplex(randomValue);
}
VerifyInt32ImplicitCastToComplex(Int32.MaxValue);
}
private static void VerifyInt64ImplicitCastToComplex(Int64 value)
{
Complex c_cast = value;
Support.VerifyRealImaginaryProperties(c_cast, value, 0.0,
string.Format("Int64ImplicitCast ({0})", value));
if (value != Int64.MaxValue)
{
Complex c_cast_plus = c_cast + 1;
Support.VerifyRealImaginaryProperties(c_cast_plus, value + 1, 0.0,
string.Format("PLuS + Int64ImplicitCast ({0})", value));
}
if (value != Int64.MinValue)
{
Complex c_cast_minus = c_cast - 1;
Support.VerifyRealImaginaryProperties(c_cast_minus, value - 1, 0.0,
string.Format("Minus - Int64ImplicitCast + 1 ({0})", value));
}
}
[Fact]
public static void RunTests_Int64ImplicitCastToComplex()
{
VerifyInt64ImplicitCastToComplex(Int64.MinValue);
for (int i = 0; i < 3; ++i)
{
Int64 randomValue = Support.GetRandomInt64Value(true);
VerifyInt64ImplicitCastToComplex(randomValue);
}
VerifyInt64ImplicitCastToComplex(-1);
VerifyInt64ImplicitCastToComplex(0);
VerifyInt64ImplicitCastToComplex(1);
for (int i = 0; i < 3; ++i)
{
Int64 randomValue = Support.GetRandomInt64Value(false);
VerifyInt64ImplicitCastToComplex(randomValue);
}
VerifyInt64ImplicitCastToComplex(Int64.MaxValue);
}
private static void VerifyUInt16ImplicitCastToComplex(UInt16 value)
{
Complex c_cast = value;
Support.VerifyRealImaginaryProperties(c_cast, value, 0.0,
string.Format("UInt16ImplicitCast ({0})", value));
if (value != UInt16.MaxValue)
{
Complex c_cast_plus = c_cast + 1;
Support.VerifyRealImaginaryProperties(c_cast_plus, value + 1, 0.0,
string.Format("PLuS + UInt16ImplicitCast ({0})", value));
}
if (value != UInt16.MinValue)
{
Complex c_cast_minus = c_cast - 1;
Support.VerifyRealImaginaryProperties(c_cast_minus, value - 1, 0.0,
string.Format("Minus - UInt16ImplicitCast + 1 ({0})", value));
}
}
[Fact]
public static void RunTests_UInt16ImplicitCastToComplex()
{
VerifyUInt16ImplicitCastToComplex(UInt16.MinValue);
VerifyUInt16ImplicitCastToComplex(0);
VerifyUInt16ImplicitCastToComplex(1);
#if CLS_Compliant
for (int i = 0; i < 3; ++i)
{
UInt16 randomValue = Support.GetRandomUInt16Value();
VerifyUInt16ImplicitCastToComplex(randomValue);
}
#endif
VerifyUInt16ImplicitCastToComplex(UInt16.MaxValue);
}
private static void VerifyUInt32ImplicitCastToComplex(UInt32 value)
{
Complex c_cast = value;
Support.VerifyRealImaginaryProperties(c_cast, value, 0.0,
string.Format("UInt32ImplicitCast ({0})", value));
if (value != UInt32.MaxValue)
{
Complex c_cast_plus = c_cast + 1;
Support.VerifyRealImaginaryProperties(c_cast_plus, value + 1, 0.0,
string.Format("PLuS + UInt32ImplicitCast ({0})", value));
}
if (value != UInt32.MinValue)
{
Complex c_cast_minus = c_cast - 1;
Support.VerifyRealImaginaryProperties(c_cast_minus, value - 1, 0.0,
string.Format("Minus - UInt32ImplicitCast + 1 ({0})", value));
}
}
[Fact]
public static void RunTests_UInt32ImplicitCastToComplex()
{
VerifyUInt32ImplicitCastToComplex(UInt32.MinValue);
VerifyUInt32ImplicitCastToComplex(0);
VerifyUInt32ImplicitCastToComplex(1);
#if CLS_Compliant
for (int i = 0; i < 3; ++i)
{
UInt32 randomValue = Support.GetRandomUInt32Value();
VerifyUInt32ImplicitCastToComplex(randomValue);
}
#endif
VerifyUInt32ImplicitCastToComplex(UInt32.MaxValue);
}
private static void VerifyUInt64ImplicitCastToComplex(UInt64 value)
{
Complex c_cast = value;
Support.VerifyRealImaginaryProperties(c_cast, value, 0.0,
string.Format("UInt64ImplicitCast ({0})", value));
if (value != UInt64.MaxValue)
{
Complex c_cast_plus = c_cast + 1;
Support.VerifyRealImaginaryProperties(c_cast_plus, value + 1, 0.0,
string.Format("PLuS + UInt64ImplicitCast ({0})", value));
}
if (value != UInt64.MinValue)
{
Complex c_cast_minus = c_cast - 1;
Support.VerifyRealImaginaryProperties(c_cast_minus, value - 1, 0.0,
string.Format("Minus - UInt64ImplicitCast + 1 ({0})", value));
}
}
[Fact]
public static void RunTests_UInt64ImplicitCastToComplex()
{
VerifyUInt64ImplicitCastToComplex(UInt64.MinValue);
VerifyUInt64ImplicitCastToComplex(0);
VerifyUInt64ImplicitCastToComplex(1);
#if CLS_Compliant
for (int i = 0; i < 3; ++i)
{
UInt64 randomValue = Support.GetRandomUInt64Value();
VerifyUInt64ImplicitCastToComplex(randomValue);
}
#endif
VerifyUInt64ImplicitCastToComplex(UInt64.MaxValue);
}
private static void VerifySByteImplicitCastToComplex(SByte value)
{
Complex c_cast = value;
Support.VerifyRealImaginaryProperties(c_cast, value, 0.0,
string.Format("SByteImplicitCast ({0})", value));
if (value != SByte.MaxValue)
{
Complex c_cast_plus = c_cast + 1;
Support.VerifyRealImaginaryProperties(c_cast_plus, value + 1, 0.0,
string.Format("PLuS + SByteImplicitCast ({0})", value));
}
if (value != SByte.MinValue)
{
Complex c_cast_minus = c_cast - 1;
Support.VerifyRealImaginaryProperties(c_cast_minus, value - 1, 0.0,
string.Format("Minus - SByteImplicitCast + 1 ({0})", value));
}
}
[Fact]
public static void RunTests_SByteImplicitCastToComplex()
{
VerifySByteImplicitCastToComplex(SByte.MinValue);
#if CLS_Compliant
for (int i = 0; i < 3; ++i)
{
SByte randomValue = Support.GetRandomSByteValue(false);
VerifySByteImplicitCastToComplex(randomValue);
}
#endif
VerifySByteImplicitCastToComplex(0);
VerifySByteImplicitCastToComplex(1);
#if CLS_Compliant
for (int i = 0; i < 3; ++i)
{
SByte randomValue = Support.GetRandomSByteValue(true);
VerifySByteImplicitCastToComplex(randomValue);
}
#endif
VerifySByteImplicitCastToComplex(SByte.MaxValue);
}
private static void VerifyByteImplicitCastToComplex(Byte value)
{
Complex c_cast = value;
Support.VerifyRealImaginaryProperties(c_cast, value, 0.0,
string.Format("ByteImplicitCast ({0})", value));
if (value != Byte.MaxValue)
{
Complex c_cast_plus = c_cast + 1;
Support.VerifyRealImaginaryProperties(c_cast_plus, value + 1, 0.0,
string.Format("PLuS + ByteImplicitCast ({0})", value));
}
if (value != Byte.MinValue)
{
Complex c_cast_minus = c_cast - 1;
Support.VerifyRealImaginaryProperties(c_cast_minus, value - 1, 0.0,
string.Format("Minus - ByteImplicitCast + 1 ({0})", value));
}
}
[Fact]
public static void RunTests_ByteImplicitCastToComplex()
{
VerifyByteImplicitCastToComplex(Byte.MinValue);
VerifyByteImplicitCastToComplex(0);
VerifyByteImplicitCastToComplex(1);
for (int i = 0; i < 3; ++i)
{
Byte randomValue = Support.GetRandomByteValue();
VerifyByteImplicitCastToComplex(randomValue);
}
VerifyByteImplicitCastToComplex(Byte.MaxValue);
}
private static void VerifySingleImplicitCastToComplex(Single value)
{
Complex c_cast = value;
Support.VerifyRealImaginaryProperties(c_cast, value, 0.0,
string.Format("SingleImplicitCast ({0})", value));
if (value != Single.MaxValue)
{
Complex c_cast_plus = c_cast + 1;
Support.VerifyRealImaginaryProperties(c_cast_plus, value + 1, 0.0,
string.Format("PLuS + SingleImplicitCast ({0})", value));
}
if (value != Single.MinValue)
{
Complex c_cast_minus = c_cast - 1;
Support.VerifyRealImaginaryProperties(c_cast_minus, value - 1, 0.0,
string.Format("Minus - SingleImplicitCast + 1 ({0})", value));
}
}
[Fact]
public static void RunTests_SingleImplicitCastToComplex()
{
VerifySingleImplicitCastToComplex(Single.MinValue);
for (int i = 0; i < 3; ++i)
{
Single randomValue = Support.GetRandomSingleValue(false);
VerifySingleImplicitCastToComplex(randomValue);
}
VerifySingleImplicitCastToComplex(0);
VerifySingleImplicitCastToComplex(1);
for (int i = 0; i < 3; ++i)
{
Single randomValue = Support.GetRandomSingleValue(true);
VerifySingleImplicitCastToComplex(randomValue);
}
VerifySingleImplicitCastToComplex(Single.MaxValue);
}
private static void VerifyDoubleImplicitCastToComplex(double value)
{
Complex c_cast = value;
Support.VerifyRealImaginaryProperties(c_cast, value, 0.0,
string.Format("DoubleImplicitCast ({0})", value));
if (value != double.MaxValue)
{
Complex c_cast_plus = c_cast + 1;
Support.VerifyRealImaginaryProperties(c_cast_plus, value + 1, 0.0,
string.Format("PLuS + DoubleImplicitCast ({0})", value));
}
if (value != double.MinValue)
{
Complex c_cast_minus = c_cast - 1;
Support.VerifyRealImaginaryProperties(c_cast_minus, value - 1, 0.0,
string.Format("Minus - DoubleImplicitCast + 1 ({0})", value));
}
}
[Fact]
public static void RunTests_DoubleImplicitCastToComplex()
{
VerifyDoubleImplicitCastToComplex(double.MinValue);
for (int i = 0; i < 3; ++i)
{
double randomValue = Support.GetRandomDoubleValue(false);
VerifyDoubleImplicitCastToComplex(randomValue);
}
VerifyDoubleImplicitCastToComplex(0);
VerifyDoubleImplicitCastToComplex(1);
for (int i = 0; i < 3; ++i)
{
double randomValue = Support.GetRandomDoubleValue(true);
VerifyDoubleImplicitCastToComplex(randomValue);
}
VerifyDoubleImplicitCastToComplex(double.MaxValue);
}
private static void VerifyBigIntegerExplicitCastToComplex(BigInteger value)
{
Complex c_cast = (Complex)value;
Support.VerifyRealImaginaryProperties(c_cast, (Double)value, 0.0,
string.Format("BigIntegerExplicitCast ({0})", value));
if (value != (BigInteger)double.MaxValue)
{
Complex c_cast_plus = c_cast + 1;
Support.VerifyRealImaginaryProperties(c_cast_plus, (Double)(value + 1), 0.0,
string.Format("PLuS + BigIntegerExplicitCast ({0})", value));
}
if (value != (BigInteger)double.MinValue)
{
Complex c_cast_minus = c_cast - 1;
Support.VerifyRealImaginaryProperties(c_cast_minus, (Double)(value - 1), 0.0,
string.Format("Minus - BigIntegerExplicitCast + 1 ({0})", value));
}
}
[Fact]
public static void RunTests_BigIntegerExplicitCastToComplex()
{
VerifyBigIntegerExplicitCastToComplex((BigInteger)double.MinValue);
for (int i = 0; i < 3; ++i)
{
BigInteger randomValue = Support.GetRandomBigIntegerValue(false);
VerifyBigIntegerExplicitCastToComplex(randomValue);
}
VerifyBigIntegerExplicitCastToComplex(0);
VerifyBigIntegerExplicitCastToComplex(1);
for (int i = 0; i < 3; ++i)
{
BigInteger randomValue = Support.GetRandomBigIntegerValue(true);
VerifyBigIntegerExplicitCastToComplex(randomValue);
}
VerifyBigIntegerExplicitCastToComplex((BigInteger)double.MaxValue);
}
private static void VerifyDecimalExplicitCastToComplex(Decimal value)
{
Complex c_cast = (Complex)value;
Support.VerifyRealImaginaryProperties(c_cast, (Double)value, 0.0,
string.Format("DecimalExplicitCast ({0})", value));
if (value != Decimal.MaxValue)
{
Complex c_cast_plus = c_cast + 1;
Support.VerifyRealImaginaryProperties(c_cast_plus, (Double)(value + 1), 0.0,
string.Format("PLuS + DecimalExplicitCast ({0})", value));
}
if (value != Decimal.MinValue)
{
Complex c_cast_minus = c_cast - 1;
Support.VerifyRealImaginaryProperties(c_cast_minus, (Double)(value - 1), 0.0,
string.Format("Minus - DecimalExplicitCast + 1 ({0})", value));
}
}
[Fact]
public static void RunTests_DecimalExplicitCastToComplex()
{
VerifyDecimalExplicitCastToComplex(Decimal.MinValue);
for (int i = 0; i < 3; ++i)
{
Decimal randomValue = Support.GetRandomDecimalValue(false);
VerifyDecimalExplicitCastToComplex(randomValue);
}
VerifyDecimalExplicitCastToComplex(0);
VerifyDecimalExplicitCastToComplex(1);
for (int i = 0; i < 3; ++i)
{
Decimal randomValue = Support.GetRandomDecimalValue(true);
VerifyDecimalExplicitCastToComplex(randomValue);
}
VerifyDecimalExplicitCastToComplex(Decimal.MaxValue);
}
}
}
| |
/*
* 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 Nini.Config;
using NUnit.Framework;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Region.CoreModules.Avatar.Attachments;
using OpenSim.Region.CoreModules.Avatar.AvatarFactory;
using OpenSim.Region.CoreModules.Framework.InventoryAccess;
using OpenSim.Region.CoreModules.Framework.UserManagement;
using OpenSim.Region.CoreModules.ServiceConnectorsOut.Avatar;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.AvatarService;
using OpenSim.Tests.Common;
namespace OpenSim.Region.OptionalModules.World.NPC.Tests
{
[TestFixture]
public class NPCModuleTests : OpenSimTestCase
{
private TestScene m_scene;
private AvatarFactoryModule m_afMod;
private UserManagementModule m_umMod;
private AttachmentsModule m_attMod;
private NPCModule m_npcMod;
[TestFixtureSetUp]
public void FixtureInit()
{
// Don't allow tests to be bamboozled by asynchronous events. Execute everything on the same thread.
Util.FireAndForgetMethod = FireAndForgetMethod.None;
}
[TestFixtureTearDown]
public void TearDown()
{
// We must set this back afterwards, otherwise later tests will fail since they're expecting multiple
// threads. Possibly, later tests should be rewritten not to worry about such things.
Util.FireAndForgetMethod = Util.DefaultFireAndForgetMethod;
}
public void SetUpScene()
{
SetUpScene(256, 256);
}
public void SetUpScene(uint sizeX, uint sizeY)
{
IConfigSource config = new IniConfigSource();
config.AddConfig("NPC");
config.Configs["NPC"].Set("Enabled", "true");
config.AddConfig("Modules");
config.Configs["Modules"].Set("InventoryAccessModule", "BasicInventoryAccessModule");
m_afMod = new AvatarFactoryModule();
m_umMod = new UserManagementModule();
m_attMod = new AttachmentsModule();
m_npcMod = new NPCModule();
m_scene = new SceneHelpers().SetupScene("test scene", UUID.Random(), 1000, 1000, sizeX, sizeY, config);
SceneHelpers.SetupSceneModules(m_scene, config, m_afMod, m_umMod, m_attMod, m_npcMod, new BasicInventoryAccessModule());
}
[Test]
public void TestCreate()
{
TestHelpers.InMethod();
// log4net.Config.XmlConfigurator.Configure();
SetUpScene();
ScenePresence sp = SceneHelpers.AddScenePresence(m_scene, TestHelpers.ParseTail(0x1));
// ScenePresence originalAvatar = scene.GetScenePresence(originalClient.AgentId);
// 8 is the index of the first baked texture in AvatarAppearance
UUID originalFace8TextureId = TestHelpers.ParseTail(0x10);
Primitive.TextureEntry originalTe = new Primitive.TextureEntry(UUID.Zero);
Primitive.TextureEntryFace originalTef = originalTe.CreateFace(8);
originalTef.TextureID = originalFace8TextureId;
// We also need to add the texture to the asset service, otherwise the AvatarFactoryModule will tell
// ScenePresence.SendInitialData() to reset our entire appearance.
m_scene.AssetService.Store(AssetHelpers.CreateNotecardAsset(originalFace8TextureId));
m_afMod.SetAppearance(sp, originalTe, null, null);
UUID npcId = m_npcMod.CreateNPC("John", "Smith", new Vector3(128, 128, 30), UUID.Zero, true, m_scene, sp.Appearance);
ScenePresence npc = m_scene.GetScenePresence(npcId);
Assert.That(npc, Is.Not.Null);
Assert.That(npc.Appearance.Texture.FaceTextures[8].TextureID, Is.EqualTo(originalFace8TextureId));
Assert.That(m_umMod.GetUserName(npc.UUID), Is.EqualTo(string.Format("{0} {1}", npc.Firstname, npc.Lastname)));
IClientAPI client;
Assert.That(m_scene.TryGetClient(npcId, out client), Is.True);
// Have to account for both SP and NPC.
Assert.That(m_scene.AuthenticateHandler.GetAgentCircuits().Count, Is.EqualTo(2));
}
[Test]
public void TestRemove()
{
TestHelpers.InMethod();
// log4net.Config.XmlConfigurator.Configure();
SetUpScene();
ScenePresence sp = SceneHelpers.AddScenePresence(m_scene, TestHelpers.ParseTail(0x1));
// ScenePresence originalAvatar = scene.GetScenePresence(originalClient.AgentId);
Vector3 startPos = new Vector3(128, 128, 30);
UUID npcId = m_npcMod.CreateNPC("John", "Smith", startPos, UUID.Zero, true, m_scene, sp.Appearance);
m_npcMod.DeleteNPC(npcId, m_scene);
ScenePresence deletedNpc = m_scene.GetScenePresence(npcId);
Assert.That(deletedNpc, Is.Null);
IClientAPI client;
Assert.That(m_scene.TryGetClient(npcId, out client), Is.False);
// Have to account for SP still present.
Assert.That(m_scene.AuthenticateHandler.GetAgentCircuits().Count, Is.EqualTo(1));
}
[Test]
public void TestCreateWithAttachments()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
SetUpScene();
UUID userId = TestHelpers.ParseTail(0x1);
UserAccountHelpers.CreateUserWithInventory(m_scene, userId);
ScenePresence sp = SceneHelpers.AddScenePresence(m_scene, userId);
UUID attItemId = TestHelpers.ParseTail(0x2);
UUID attAssetId = TestHelpers.ParseTail(0x3);
string attName = "att";
UserInventoryHelpers.CreateInventoryItem(m_scene, attName, attItemId, attAssetId, sp.UUID, InventoryType.Object);
m_attMod.RezSingleAttachmentFromInventory(sp, attItemId, (uint)AttachmentPoint.Chest);
UUID npcId = m_npcMod.CreateNPC("John", "Smith", new Vector3(128, 128, 30), UUID.Zero, true, m_scene, sp.Appearance);
ScenePresence npc = m_scene.GetScenePresence(npcId);
// Check scene presence status
Assert.That(npc.HasAttachments(), Is.True);
List<SceneObjectGroup> attachments = npc.GetAttachments();
Assert.That(attachments.Count, Is.EqualTo(1));
SceneObjectGroup attSo = attachments[0];
// Just for now, we won't test the name since this is (wrongly) the asset part name rather than the item
// name. TODO: Do need to fix ultimately since the item may be renamed before being passed on to an NPC.
// Assert.That(attSo.Name, Is.EqualTo(attName));
Assert.That(attSo.AttachmentPoint, Is.EqualTo((byte)AttachmentPoint.Chest));
Assert.That(attSo.IsAttachment);
Assert.That(attSo.UsesPhysics, Is.False);
Assert.That(attSo.IsTemporary, Is.False);
Assert.That(attSo.OwnerID, Is.EqualTo(npc.UUID));
}
[Test]
public void TestCreateWithMultiAttachments()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
SetUpScene();
// m_attMod.DebugLevel = 1;
UUID userId = TestHelpers.ParseTail(0x1);
UserAccountHelpers.CreateUserWithInventory(m_scene, userId);
ScenePresence sp = SceneHelpers.AddScenePresence(m_scene, userId);
InventoryItemBase att1Item
= UserInventoryHelpers.CreateInventoryItem(
m_scene, "att1", TestHelpers.ParseTail(0x2), TestHelpers.ParseTail(0x3), sp.UUID, InventoryType.Object);
InventoryItemBase att2Item
= UserInventoryHelpers.CreateInventoryItem(
m_scene, "att2", TestHelpers.ParseTail(0x12), TestHelpers.ParseTail(0x13), sp.UUID, InventoryType.Object);
m_attMod.RezSingleAttachmentFromInventory(sp, att1Item.ID, (uint)AttachmentPoint.Chest);
m_attMod.RezSingleAttachmentFromInventory(sp, att2Item.ID, (uint)AttachmentPoint.Chest | 0x80);
UUID npcId = m_npcMod.CreateNPC("John", "Smith", new Vector3(128, 128, 30), UUID.Zero, true, m_scene, sp.Appearance);
ScenePresence npc = m_scene.GetScenePresence(npcId);
// Check scene presence status
Assert.That(npc.HasAttachments(), Is.True);
List<SceneObjectGroup> attachments = npc.GetAttachments();
Assert.That(attachments.Count, Is.EqualTo(2));
// Just for now, we won't test the name since this is (wrongly) the asset part name rather than the item
// name. TODO: Do need to fix ultimately since the item may be renamed before being passed on to an NPC.
// Assert.That(attSo.Name, Is.EqualTo(attName));
TestAttachedObject(attachments[0], AttachmentPoint.Chest, npc.UUID);
TestAttachedObject(attachments[1], AttachmentPoint.Chest, npc.UUID);
// Attached objects on the same point must have different FromItemIDs to be shown to other avatars, at least
// on Singularity 1.8.5. Otherwise, only one (the first ObjectUpdate sent) appears.
Assert.AreNotEqual(attachments[0].FromItemID, attachments[1].FromItemID);
}
private void TestAttachedObject(SceneObjectGroup attSo, AttachmentPoint attPoint, UUID ownerId)
{
Assert.That(attSo.AttachmentPoint, Is.EqualTo((byte)attPoint));
Assert.That(attSo.IsAttachment);
Assert.That(attSo.UsesPhysics, Is.False);
Assert.That(attSo.IsTemporary, Is.False);
Assert.That(attSo.OwnerID, Is.EqualTo(ownerId));
}
[Test]
public void TestLoadAppearance()
{
TestHelpers.InMethod();
// log4net.Config.XmlConfigurator.Configure();
SetUpScene();
UUID userId = TestHelpers.ParseTail(0x1);
UserAccountHelpers.CreateUserWithInventory(m_scene, userId);
ScenePresence sp = SceneHelpers.AddScenePresence(m_scene, userId);
UUID npcId = m_npcMod.CreateNPC("John", "Smith", new Vector3(128, 128, 30), UUID.Zero, true, m_scene, sp.Appearance);
// Now add the attachment to the original avatar and use that to load a new appearance
// TODO: Could also run tests loading from a notecard though this isn't much different for our purposes here
UUID attItemId = TestHelpers.ParseTail(0x2);
UUID attAssetId = TestHelpers.ParseTail(0x3);
string attName = "att";
UserInventoryHelpers.CreateInventoryItem(m_scene, attName, attItemId, attAssetId, sp.UUID, InventoryType.Object);
m_attMod.RezSingleAttachmentFromInventory(sp, attItemId, (uint)AttachmentPoint.Chest);
m_npcMod.SetNPCAppearance(npcId, sp.Appearance, m_scene);
ScenePresence npc = m_scene.GetScenePresence(npcId);
// Check scene presence status
Assert.That(npc.HasAttachments(), Is.True);
List<SceneObjectGroup> attachments = npc.GetAttachments();
Assert.That(attachments.Count, Is.EqualTo(1));
SceneObjectGroup attSo = attachments[0];
// Just for now, we won't test the name since this is (wrongly) the asset part name rather than the item
// name. TODO: Do need to fix ultimately since the item may be renamed before being passed on to an NPC.
// Assert.That(attSo.Name, Is.EqualTo(attName));
Assert.That(attSo.AttachmentPoint, Is.EqualTo((byte)AttachmentPoint.Chest));
Assert.That(attSo.IsAttachment);
Assert.That(attSo.UsesPhysics, Is.False);
Assert.That(attSo.IsTemporary, Is.False);
Assert.That(attSo.OwnerID, Is.EqualTo(npc.UUID));
}
[Test]
public void TestMove()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
SetUpScene();
ScenePresence sp = SceneHelpers.AddScenePresence(m_scene, TestHelpers.ParseTail(0x1));
// ScenePresence originalAvatar = scene.GetScenePresence(originalClient.AgentId);
Vector3 startPos = new Vector3(128, 128, 30);
UUID npcId = m_npcMod.CreateNPC("John", "Smith", startPos, UUID.Zero, true, m_scene, sp.Appearance);
ScenePresence npc = m_scene.GetScenePresence(npcId);
Assert.That(npc.AbsolutePosition, Is.EqualTo(startPos));
// For now, we'll make the scene presence fly to simplify this test, but this needs to change.
npc.Flying = true;
m_scene.Update(1);
Assert.That(npc.AbsolutePosition, Is.EqualTo(startPos));
Vector3 targetPos = startPos + new Vector3(0, 10, 0);
m_npcMod.MoveToTarget(npc.UUID, m_scene, targetPos, false, false, false);
Assert.That(npc.AbsolutePosition, Is.EqualTo(startPos));
//Assert.That(npc.Rotation, Is.EqualTo(new Quaternion(0, 0, 0.7071068f, 0.7071068f)));
Assert.That(
npc.Rotation, new QuaternionToleranceConstraint(new Quaternion(0, 0, 0.7071068f, 0.7071068f), 0.000001));
m_scene.Update(1);
// We should really check the exact figure.
Assert.That(npc.AbsolutePosition.X, Is.EqualTo(startPos.X));
Assert.That(npc.AbsolutePosition.Y, Is.GreaterThan(startPos.Y));
Assert.That(npc.AbsolutePosition.Z, Is.EqualTo(startPos.Z));
Assert.That(npc.AbsolutePosition.Z, Is.LessThan(targetPos.X));
m_scene.Update(10);
double distanceToTarget = Util.GetDistanceTo(npc.AbsolutePosition, targetPos);
Assert.That(distanceToTarget, Is.LessThan(1), "NPC not within 1 unit of target position on first move");
Assert.That(npc.AbsolutePosition, Is.EqualTo(targetPos));
Assert.That(npc.AgentControlFlags, Is.EqualTo((uint)AgentManager.ControlFlags.NONE));
// Try a second movement
startPos = npc.AbsolutePosition;
targetPos = startPos + new Vector3(10, 0, 0);
m_npcMod.MoveToTarget(npc.UUID, m_scene, targetPos, false, false, false);
Assert.That(npc.AbsolutePosition, Is.EqualTo(startPos));
// Assert.That(npc.Rotation, Is.EqualTo(new Quaternion(0, 0, 0, 1)));
Assert.That(
npc.Rotation, new QuaternionToleranceConstraint(new Quaternion(0, 0, 0, 1), 0.000001));
m_scene.Update(1);
// We should really check the exact figure.
Assert.That(npc.AbsolutePosition.X, Is.GreaterThan(startPos.X));
Assert.That(npc.AbsolutePosition.X, Is.LessThan(targetPos.X));
Assert.That(npc.AbsolutePosition.Y, Is.EqualTo(startPos.Y));
Assert.That(npc.AbsolutePosition.Z, Is.EqualTo(startPos.Z));
m_scene.Update(10);
distanceToTarget = Util.GetDistanceTo(npc.AbsolutePosition, targetPos);
Assert.That(distanceToTarget, Is.LessThan(1), "NPC not within 1 unit of target position on second move");
Assert.That(npc.AbsolutePosition, Is.EqualTo(targetPos));
}
[Test]
public void TestMoveInVarRegion()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
SetUpScene(512, 512);
ScenePresence sp = SceneHelpers.AddScenePresence(m_scene, TestHelpers.ParseTail(0x1));
// ScenePresence originalAvatar = scene.GetScenePresence(originalClient.AgentId);
Vector3 startPos = new Vector3(128, 246, 30);
UUID npcId = m_npcMod.CreateNPC("John", "Smith", startPos, UUID.Zero, true, m_scene, sp.Appearance);
ScenePresence npc = m_scene.GetScenePresence(npcId);
Assert.That(npc.AbsolutePosition, Is.EqualTo(startPos));
// For now, we'll make the scene presence fly to simplify this test, but this needs to change.
npc.Flying = true;
m_scene.Update(1);
Assert.That(npc.AbsolutePosition, Is.EqualTo(startPos));
Vector3 targetPos = startPos + new Vector3(0, 20, 0);
m_npcMod.MoveToTarget(npc.UUID, m_scene, targetPos, false, false, false);
Assert.That(npc.AbsolutePosition, Is.EqualTo(startPos));
//Assert.That(npc.Rotation, Is.EqualTo(new Quaternion(0, 0, 0.7071068f, 0.7071068f)));
Assert.That(
npc.Rotation, new QuaternionToleranceConstraint(new Quaternion(0, 0, 0.7071068f, 0.7071068f), 0.000001));
m_scene.Update(1);
// We should really check the exact figure.
Assert.That(npc.AbsolutePosition.X, Is.EqualTo(startPos.X));
Assert.That(npc.AbsolutePosition.Y, Is.GreaterThan(startPos.Y));
Assert.That(npc.AbsolutePosition.Z, Is.EqualTo(startPos.Z));
Assert.That(npc.AbsolutePosition.Z, Is.LessThan(targetPos.X));
for (int i = 0; i < 20; i++)
{
m_scene.Update(1);
// Console.WriteLine("pos: {0}", npc.AbsolutePosition);
}
double distanceToTarget = Util.GetDistanceTo(npc.AbsolutePosition, targetPos);
Assert.That(distanceToTarget, Is.LessThan(1), "NPC not within 1 unit of target position on first move");
Assert.That(npc.AbsolutePosition, Is.EqualTo(targetPos));
Assert.That(npc.AgentControlFlags, Is.EqualTo((uint)AgentManager.ControlFlags.NONE));
}
[Test]
public void TestSitAndStandWithSitTarget()
{
TestHelpers.InMethod();
// log4net.Config.XmlConfigurator.Configure();
SetUpScene();
ScenePresence sp = SceneHelpers.AddScenePresence(m_scene, TestHelpers.ParseTail(0x1));
Vector3 startPos = new Vector3(128, 128, 30);
UUID npcId = m_npcMod.CreateNPC("John", "Smith", startPos, UUID.Zero, true, m_scene, sp.Appearance);
ScenePresence npc = m_scene.GetScenePresence(npcId);
SceneObjectPart part = SceneHelpers.AddSceneObject(m_scene).RootPart;
part.SitTargetPosition = new Vector3(0, 0, 1);
m_npcMod.Sit(npc.UUID, part.UUID, m_scene);
Assert.That(part.SitTargetAvatar, Is.EqualTo(npcId));
Assert.That(npc.ParentID, Is.EqualTo(part.LocalId));
// Assert.That(
// npc.AbsolutePosition,
// Is.EqualTo(part.AbsolutePosition + part.SitTargetPosition + ScenePresence.SIT_TARGET_ADJUSTMENT));
m_npcMod.Stand(npc.UUID, m_scene);
Assert.That(part.SitTargetAvatar, Is.EqualTo(UUID.Zero));
Assert.That(npc.ParentID, Is.EqualTo(0));
}
[Test]
public void TestSitAndStandWithNoSitTarget()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
SetUpScene();
ScenePresence sp = SceneHelpers.AddScenePresence(m_scene, TestHelpers.ParseTail(0x1));
// FIXME: To get this to work for now, we are going to place the npc right next to the target so that
// the autopilot doesn't trigger
Vector3 startPos = new Vector3(1, 1, 1);
UUID npcId = m_npcMod.CreateNPC("John", "Smith", startPos, UUID.Zero, true, m_scene, sp.Appearance);
ScenePresence npc = m_scene.GetScenePresence(npcId);
SceneObjectPart part = SceneHelpers.AddSceneObject(m_scene).RootPart;
m_npcMod.Sit(npc.UUID, part.UUID, m_scene);
Assert.That(part.SitTargetAvatar, Is.EqualTo(UUID.Zero));
Assert.That(npc.ParentID, Is.EqualTo(part.LocalId));
// We should really be using the NPC size but this would mean preserving the physics actor since it is
// removed on sit.
Assert.That(
npc.AbsolutePosition,
Is.EqualTo(part.AbsolutePosition + new Vector3(0, 0, sp.PhysicsActor.Size.Z / 2)));
m_npcMod.Stand(npc.UUID, m_scene);
Assert.That(part.SitTargetAvatar, Is.EqualTo(UUID.Zero));
Assert.That(npc.ParentID, Is.EqualTo(0));
}
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Xml;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.Framework.Scenes.Serialization
{
/// <summary>
/// Serialize and deserialize scene objects.
/// </summary>
/// This should really be in OpenSim.Framework.Serialization but this would mean circular dependency problems
/// right now - hopefully this isn't forever.
public class SceneObjectSerializer
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Deserialize a scene object from the original xml format
/// </summary>
/// <param name="serialization"></param>
/// <returns></returns>
public static SceneObjectGroup FromOriginalXmlFormat(string serialization)
{
return FromOriginalXmlFormat(UUID.Zero, serialization);
}
/// <summary>
/// Deserialize a scene object from the original xml format
/// </summary>
/// <param name="serialization"></param>
/// <returns></returns>
public static SceneObjectPart RootPartInOriginalXmlFormat(UUID fromUserInventoryItemID, string xmlData)
{
//m_log.DebugFormat("[SOG]: Starting deserialization of SOG");
//int time = System.Environment.TickCount;
SceneObjectPart part = new SceneObjectPart();
// libomv.types changes UUID to Guid
xmlData = xmlData.Replace("<UUID>", "<Guid>");
xmlData = xmlData.Replace("</UUID>", "</Guid>");
// Handle Nested <UUID><UUID> property
xmlData = xmlData.Replace("<Guid><Guid>", "<UUID><Guid>");
xmlData = xmlData.Replace("</Guid></Guid>", "</Guid></UUID>");
try
{
StringReader sr;
XmlTextReader reader;
XmlNodeList parts;
XmlDocument doc;
doc = new XmlDocument();
doc.LoadXml(xmlData);
parts = doc.GetElementsByTagName("RootPart");
if (parts.Count < 1)
return null;
sr = new StringReader(parts[0].InnerXml);
reader = new XmlTextReader(sr);
part = SceneObjectPart.FromXml(fromUserInventoryItemID, reader);
reader.Close();
sr.Close();
return part;
}
catch (Exception e)
{
m_log.ErrorFormat(
"[SERIALIZER]: Deserialization of root part xml failed with {0}. xml was {1}", e, xmlData);
}
return null;
}
/// <summary>
/// Deserialize a scene object from the original xml format
/// </summary>
/// <param name="serialization"></param>
/// <returns></returns>
public static SceneObjectGroup FromOriginalXmlFormat(UUID fromUserInventoryItemID, string xmlData)
{
//m_log.DebugFormat("[SOG]: Starting deserialization of SOG");
//int time = System.Environment.TickCount;
SceneObjectGroup sceneObject = new SceneObjectGroup();
// libomv.types changes UUID to Guid
xmlData = xmlData.Replace("<UUID>", "<Guid>");
xmlData = xmlData.Replace("</UUID>", "</Guid>");
// Handle Nested <UUID><UUID> property
xmlData = xmlData.Replace("<Guid><Guid>", "<UUID><Guid>");
xmlData = xmlData.Replace("</Guid></Guid>", "</Guid></UUID>");
try
{
StringReader sr;
XmlTextReader reader;
XmlNodeList parts;
XmlDocument doc;
int linkNum;
doc = new XmlDocument();
doc.LoadXml(xmlData);
parts = doc.GetElementsByTagName("RootPart");
if (parts.Count == 0)
{
throw new Exception("Invalid Xml format - no root part");
}
else
{
sr = new StringReader(parts[0].InnerXml);
reader = new XmlTextReader(sr);
sceneObject.SetRootPart(SceneObjectPart.FromXml(fromUserInventoryItemID, reader));
reader.Close();
sr.Close();
}
parts = doc.GetElementsByTagName("Part");
for (int i = 0; i < parts.Count; i++)
{
sr = new StringReader(parts[i].InnerXml);
reader = new XmlTextReader(sr);
SceneObjectPart part = SceneObjectPart.FromXml(reader);
linkNum = part.LinkNum;
sceneObject.AddPart(part);
part.LinkNum = linkNum;
part.TrimPermissions();
part.StoreUndoState();
reader.Close();
sr.Close();
}
// Script state may, or may not, exist. Not having any, is NOT
// ever a problem.
sceneObject.LoadScriptState(doc);
//m_log.DebugFormat("[SERIALIZER]: Finished deserialization of SOG {0}, {1}ms", Name, System.Environment.TickCount - time);
return sceneObject;
}
catch (Exception e)
{
m_log.ErrorFormat(
"[SERIALIZER]: Deserialization of xml failed with {0}. xml was {1}", e, xmlData);
}
return null;
}
/// <summary>
/// Serialize a scene object to the original xml format
/// </summary>
/// <param name="sceneObject"></param>
/// <returns></returns>
public static string ToOriginalXmlFormat(SceneObjectGroup sceneObject, StopScriptReason stopScriptReason)
{
using (StringWriter sw = new StringWriter())
{
using (XmlTextWriter writer = new XmlTextWriter(sw))
{
ToOriginalXmlFormat(sceneObject, writer, stopScriptReason);
}
return sw.ToString();
}
}
/// <summary>
/// Serialize a scene object to the original xml format
/// </summary>
/// <param name="sceneObject"></param>
/// <returns></returns>
public static void ToOriginalXmlFormat(SceneObjectGroup sceneObject, XmlTextWriter writer, StopScriptReason stopScriptReason)
{
//m_log.DebugFormat("[SERIALIZER]: Starting serialization of {0}", Name);
//int time = System.Environment.TickCount;
writer.WriteStartElement(String.Empty, "SceneObjectGroup", String.Empty);
writer.WriteStartElement(String.Empty, "RootPart", String.Empty);
sceneObject.RootPart.ToXml(writer);
writer.WriteEndElement();
writer.WriteStartElement(String.Empty, "OtherParts", String.Empty);
lock (sceneObject.Children)
{
foreach (SceneObjectPart part in sceneObject.Children.Values)
{
if (part.UUID != sceneObject.RootPart.UUID)
{
writer.WriteStartElement(String.Empty, "Part", String.Empty);
part.ToXml(writer);
writer.WriteEndElement();
}
}
}
writer.WriteEndElement(); // OtherParts
sceneObject.SaveScriptedState(writer, stopScriptReason);
writer.WriteEndElement(); // SceneObjectGroup
//m_log.DebugFormat("[SERIALIZER]: Finished serialization of SOG {0}, {1}ms", Name, System.Environment.TickCount - time);
}
public static SceneObjectGroup FromXml2Format(string xmlData)
{
//m_log.DebugFormat("[SOG]: Starting deserialization of SOG");
//int time = System.Environment.TickCount;
SceneObjectGroup sceneObject = new SceneObjectGroup();
// libomv.types changes UUID to Guid
xmlData = xmlData.Replace("<UUID>", "<Guid>");
xmlData = xmlData.Replace("</UUID>", "</Guid>");
// Handle Nested <UUID><UUID> property
xmlData = xmlData.Replace("<Guid><Guid>", "<UUID><Guid>");
xmlData = xmlData.Replace("</Guid></Guid>", "</Guid></UUID>");
try
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlData);
XmlNodeList parts = doc.GetElementsByTagName("SceneObjectPart");
// Process the root part first
if (parts.Count > 0)
{
StringReader sr = new StringReader(parts[0].OuterXml);
XmlTextReader reader = new XmlTextReader(sr);
sceneObject.SetRootPart(SceneObjectPart.FromXml(reader));
reader.Close();
sr.Close();
}
// Then deal with the rest
for (int i = 1; i < parts.Count; i++)
{
StringReader sr = new StringReader(parts[i].OuterXml);
XmlTextReader reader = new XmlTextReader(sr);
SceneObjectPart part = SceneObjectPart.FromXml(reader);
int originalLinkNum = part.LinkNum;
sceneObject.AddPart(part);
// SceneObjectGroup.AddPart() tries to be smart and automatically set the LinkNum.
// We override that here
if (originalLinkNum != 0)
part.LinkNum = originalLinkNum;
part.StoreUndoState();
reader.Close();
sr.Close();
}
// Script state may, or may not, exist. Not having any, is NOT
// ever a problem.
sceneObject.LoadScriptState(doc);
//m_log.DebugFormat("[SERIALIZER]: Finished deserialization of SOG {0}, {1}ms", Name, System.Environment.TickCount - time);
return sceneObject;
}
catch (Exception e)
{
m_log.ErrorFormat("[SERIALIZER]: Deserialization of xml failed with {0}. xml was {1}", e, xmlData);
}
return null;
}
/// <summary>
/// Serialize a scene object to the 'xml2' format.
/// </summary>
/// <param name="sceneObject"></param>
/// <returns></returns>
public static string ToXml2Format(SceneObjectGroup sceneObject, bool stopScripts)
{
StopScriptReason reason = stopScripts ? StopScriptReason.Derez : StopScriptReason.None;
return ToXml2Format(sceneObject, reason, true);
}
public static string ToXml2Format(SceneObjectGroup sceneObject, StopScriptReason stopScriptReason, bool saveScriptState)
{
using (StringWriter sw = new StringWriter())
{
using (XmlTextWriter writer = new XmlTextWriter(sw))
{
ToXml2Format(sceneObject, writer, stopScriptReason);
}
return sw.ToString();
}
}
public static void ToXml2Format(SceneObjectGroup sceneObject, XmlTextWriter writer, StopScriptReason stopScriptReason)
{
ToXml2Format(sceneObject, writer, stopScriptReason, true);
}
/// <summary>
/// Serialize a scene object to the 'xml2' format.
/// </summary>
/// <param name="sceneObject"></param>
/// <returns></returns>
public static void ToXml2Format(SceneObjectGroup sceneObject, XmlTextWriter writer, StopScriptReason stopScriptReason, bool saveScriptState)
{
//m_log.DebugFormat("[SERIALIZER]: Starting serialization of SOG {0} to XML2", Name);
//int time = System.Environment.TickCount;
writer.WriteStartElement(String.Empty, "SceneObjectGroup", String.Empty);
sceneObject.RootPart.ToXml(writer);
writer.WriteStartElement(String.Empty, "OtherParts", String.Empty);
List<SceneObjectPart> parts = new List<SceneObjectPart>(sceneObject.Children.Values);
foreach (SceneObjectPart part in parts)
{
if (part.UUID != sceneObject.RootPart.UUID)
{
part.ToXml(writer);
}
}
writer.WriteEndElement(); // End of OtherParts
if (saveScriptState)
{
sceneObject.SaveScriptedState(writer, stopScriptReason);
}
writer.WriteEndElement(); // End of SceneObjectGroup
//m_log.DebugFormat("[SERIALIZER]: Finished serialization of SOG {0} to XML2, {1}ms", Name, System.Environment.TickCount - time);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interactivity;
namespace Core.Common.Wpf
{
/*from http://mvvmlight.codeplex.com/SourceControl/latest#GalaSoft.MvvmLight/GalaSoft.MvvmLight.Platform (NET45)/Command/IEventArgsConverter.cs
* Copyright (c) 2009 - 2013 Laurent Bugnion (GalaSoft), laurent@galasoft.ch
*
* 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.
* */
/// <summary>
/// This <see cref="T:System.Windows.Interactivity.TriggerAction`1" /> can be
/// used to bind any event on any FrameworkElement to an <see cref="ICommand" />.
/// Typically, this element is used in XAML to connect the attached element
/// to a command located in a ViewModel. This trigger can only be attached
/// to a FrameworkElement or a class deriving from FrameworkElement.
/// <para>To access the EventArgs of the fired event, use a RelayCommand<EventArgs>
/// and leave the CommandParameter and CommandParameterValue empty!</para>
/// </summary>
public class EventToCommand : TriggerAction<DependencyObject>
{
/// <summary>
/// Identifies the <see cref="CommandParameter" /> dependency property
/// </summary>
public static readonly DependencyProperty CommandParameterProperty = DependencyProperty.Register(
"CommandParameter",
typeof(object),
typeof(EventToCommand),
new PropertyMetadata(
null,
(s, e) =>
{
var sender = s as EventToCommand;
if (sender == null)
{
return;
}
if (sender.AssociatedObject == null)
{
return;
}
sender.EnableDisableElement();
}));
/// <summary>
/// Identifies the <see cref="Command" /> dependency property
/// </summary>
public static readonly DependencyProperty CommandProperty = DependencyProperty.Register(
"Command",
typeof(ICommand),
typeof(EventToCommand),
new PropertyMetadata(
null,
(s, e) => OnCommandChanged(s as EventToCommand, e)));
/// <summary>
/// Identifies the <see cref="MustToggleIsEnabled" /> dependency property
/// </summary>
public static readonly DependencyProperty MustToggleIsEnabledProperty = DependencyProperty.Register(
"MustToggleIsEnabled",
typeof(bool),
typeof(EventToCommand),
new PropertyMetadata(
false,
(s, e) =>
{
var sender = s as EventToCommand;
if (sender == null)
{
return;
}
if (sender.AssociatedObject == null)
{
return;
}
sender.EnableDisableElement();
}));
private object _commandParameterValue;
private bool? _mustToggleValue;
/// <summary>
/// Gets or sets the ICommand that this trigger is bound to. This
/// is a DependencyProperty.
/// </summary>
public ICommand Command
{
get
{
return (ICommand)GetValue(CommandProperty);
}
set
{
SetValue(CommandProperty, value);
}
}
/// <summary>
/// Gets or sets an object that will be passed to the <see cref="Command" />
/// attached to this trigger. This is a DependencyProperty.
/// </summary>
public object CommandParameter
{
get
{
return GetValue(CommandParameterProperty);
}
set
{
SetValue(CommandParameterProperty, value);
}
}
/// <summary>
/// Gets or sets an object that will be passed to the <see cref="Command" />
/// attached to this trigger. This property is here for compatibility
/// with the Silverlight version. This is NOT a DependencyProperty.
/// For databinding, use the <see cref="CommandParameter" /> property.
/// </summary>
public object CommandParameterValue
{
get
{
return _commandParameterValue ?? CommandParameter;
}
set
{
_commandParameterValue = value;
EnableDisableElement();
}
}
/// <summary>
/// Gets or sets a value indicating whether the attached element must be
/// disabled when the <see cref="Command" /> property's CanExecuteChanged
/// event fires. If this property is true, and the command's CanExecute
/// method returns false, the element will be disabled. If this property
/// is false, the element will not be disabled when the command's
/// CanExecute method changes. This is a DependencyProperty.
/// </summary>
public bool MustToggleIsEnabled
{
get
{
return (bool)GetValue(MustToggleIsEnabledProperty);
}
set
{
SetValue(MustToggleIsEnabledProperty, value);
}
}
/// <summary>
/// Gets or sets a value indicating whether the attached element must be
/// disabled when the <see cref="Command" /> property's CanExecuteChanged
/// event fires. If this property is true, and the command's CanExecute
/// method returns false, the element will be disabled. This property is here for
/// compatibility with the Silverlight version. This is NOT a DependencyProperty.
/// For databinding, use the <see cref="MustToggleIsEnabled" /> property.
/// </summary>
public bool MustToggleIsEnabledValue
{
get
{
return _mustToggleValue == null
? MustToggleIsEnabled
: _mustToggleValue.Value;
}
set
{
_mustToggleValue = value;
EnableDisableElement();
}
}
/// <summary>
/// Called when this trigger is attached to a FrameworkElement.
/// </summary>
protected override void OnAttached()
{
base.OnAttached();
EnableDisableElement();
}
#if SILVERLIGHT
private Control GetAssociatedObject()
{
return AssociatedObject as Control;
}
#else
/// <summary>
/// This method is here for compatibility
/// with the Silverlight version.
/// </summary>
/// <returns>The FrameworkElement to which this trigger
/// is attached.</returns>
private FrameworkElement GetAssociatedObject()
{
return AssociatedObject as FrameworkElement;
}
#endif
/// <summary>
/// This method is here for compatibility
/// with the Silverlight 3 version.
/// </summary>
/// <returns>The command that must be executed when
/// this trigger is invoked.</returns>
private ICommand GetCommand()
{
return Command;
}
/// <summary>
/// Specifies whether the EventArgs of the event that triggered this
/// action should be passed to the bound RelayCommand. If this is true,
/// the command should accept arguments of the corresponding
/// type (for example RelayCommand<MouseButtonEventArgs>).
/// </summary>
public bool PassEventArgsToCommand
{
get;
set;
}
/// <summary>
/// Gets or sets a converter used to convert the EventArgs when using
/// <see cref="PassEventArgsToCommand"/>. If PassEventArgsToCommand is false,
/// this property is never used.
/// </summary>
public IEventArgsConverter EventArgsConverter
{
get;
set;
}
/// <summary>
/// The <see cref="EventArgsConverterParameter" /> dependency property's name.
/// </summary>
public const string EventArgsConverterParameterPropertyName = "EventArgsConverterParameter";
/// <summary>
/// Gets or sets a parameters for the converter used to convert the EventArgs when using
/// <see cref="PassEventArgsToCommand"/>. If PassEventArgsToCommand is false,
/// this property is never used. This is a dependency property.
/// </summary>
public object EventArgsConverterParameter
{
get
{
return GetValue(EventArgsConverterParameterProperty);
}
set
{
SetValue(EventArgsConverterParameterProperty, value);
}
}
/// <summary>
/// Identifies the <see cref="EventArgsConverterParameter" /> dependency property.
/// </summary>
public static readonly DependencyProperty EventArgsConverterParameterProperty = DependencyProperty.Register(
EventArgsConverterParameterPropertyName,
typeof(object),
typeof(EventToCommand),
new PropertyMetadata(null));
/// <summary>
/// Provides a simple way to invoke this trigger programatically
/// without any EventArgs.
/// </summary>
public void Invoke()
{
Invoke(null);
}
/// <summary>
/// Executes the trigger.
/// <para>To access the EventArgs of the fired event, use a RelayCommand<EventArgs>
/// and leave the CommandParameter and CommandParameterValue empty!</para>
/// </summary>
/// <param name="parameter">The EventArgs of the fired event.</param>
protected override void Invoke(object parameter)
{
if (AssociatedElementIsDisabled())
{
return;
}
var command = GetCommand();
var commandParameter = CommandParameterValue;
if (commandParameter == null
&& PassEventArgsToCommand)
{
commandParameter = EventArgsConverter == null
? parameter
: EventArgsConverter.Convert(parameter, EventArgsConverterParameter);
}
if (command != null
&& command.CanExecute(commandParameter))
{
command.Execute(commandParameter);
}
}
private static void OnCommandChanged(
EventToCommand element,
DependencyPropertyChangedEventArgs e)
{
if (element == null)
{
return;
}
if (e.OldValue != null)
{
((ICommand)e.OldValue).CanExecuteChanged -= element.OnCommandCanExecuteChanged;
}
var command = (ICommand)e.NewValue;
if (command != null)
{
command.CanExecuteChanged += element.OnCommandCanExecuteChanged;
}
element.EnableDisableElement();
}
private bool AssociatedElementIsDisabled()
{
var element = GetAssociatedObject();
return AssociatedObject == null
|| (element != null
&& !element.IsEnabled);
}
private void EnableDisableElement()
{
var element = GetAssociatedObject();
if (element == null)
{
return;
}
var command = GetCommand();
if (MustToggleIsEnabledValue
&& command != null)
{
element.IsEnabled = command.CanExecute(CommandParameterValue);
}
}
private void OnCommandCanExecuteChanged(object sender, EventArgs e)
{
EnableDisableElement();
}
}
/// <summary>
/// The definition of the converter used to convert an EventArgs
/// in the <see cref="EventToCommand"/> class, if the
/// <see cref="EventToCommand.PassEventArgsToCommand"/> property is true.
/// Set an instance of this class to the <see cref="EventToCommand.EventArgsConverter"/>
/// property of the EventToCommand instance.
/// </summary>
public interface IEventArgsConverter
{
/// <summary>
/// The method used to convert the EventArgs instance.
/// </summary>
/// <param name="value">An instance of EventArgs passed by the
/// event that the EventToCommand instance is handling.</param>
/// <param name="parameter">An optional parameter used for the conversion. Use
/// the <see cref="EventToCommand.EventArgsConverterParameter"/> property
/// to set this value. This may be null.</param>
/// <returns>The converted value.</returns>
object Convert(object value, object parameter);
}
}
| |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System;
using System.Collections;
using System.Collections.Generic;
using DotSpatial.Data;
using DotSpatial.Symbology;
namespace DotSpatial.Controls
{
/// <summary>
/// Represents collection of map layers.
/// </summary>
public class MapLayerCollection : LayerCollection, IMapLayerCollection
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="MapLayerCollection"/> class that is blank.
/// This is especially useful for tracking layers that can draw themselves. This does not concern itself with
/// view extents like a dataframe, but rather is a grouping of layers that is itself also an IMapLayer.
/// </summary>
/// <param name="containerFrame">The map frame.</param>
/// <param name="progressHandler">The progress handler.</param>
public MapLayerCollection(IMapFrame containerFrame, IProgressHandler progressHandler)
{
base.MapFrame = containerFrame;
base.ParentGroup = containerFrame;
ProgressHandler = progressHandler;
}
/// <summary>
/// Initializes a new instance of the <see cref="MapLayerCollection"/> class in the situation
/// where the map frame is not the immediate parent, but rather the group is the immediate parent,
/// while frame is the ultimate map frame that contains this geo layer collection.
/// </summary>
/// <param name="frame">The map frame.</param>
/// <param name="group">The parent of this.</param>
/// <param name="progressHandler">The progress handler.</param>
public MapLayerCollection(IMapFrame frame, IMapGroup group, IProgressHandler progressHandler)
{
base.MapFrame = frame;
ParentGroup = group;
ProgressHandler = progressHandler;
}
/// <summary>
/// Initializes a new instance of the <see cref="MapLayerCollection"/> class that is blank.
/// This is especially useful for tracking layers that can draw themselves. This does not concern itself with
/// view extents like a dataframe, but rather is a grouping of layers that is itself also an IMapLayer.
/// </summary>
/// <param name="containerFrame">The map frame.</param>
public MapLayerCollection(IMapFrame containerFrame)
{
base.MapFrame = containerFrame;
ParentGroup = containerFrame;
}
/// <summary>
/// Initializes a new instance of the <see cref="MapLayerCollection"/> class
/// that is free-floating. This will not be contained in a map frame.
/// </summary>
public MapLayerCollection()
{
}
#endregion
#region Events
/// <summary>
/// Occurs when the stencil for one of the layers has been updated in a specific region.
/// </summary>
public event EventHandler<ClipArgs> BufferChanged;
#endregion
#region Properties
/// <summary>
/// Gets or sets the map frame of this layer collection.
/// </summary>
public new IMapFrame MapFrame
{
get
{
return base.MapFrame as IMapFrame;
}
set
{
base.MapFrame = value;
}
}
/// <inheritdoc />
public new bool IsReadOnly => false;
/// <inheritdoc />
public new IMapGroup ParentGroup
{
get
{
return base.ParentGroup as IMapGroup;
}
set
{
base.ParentGroup = value;
}
}
/// <summary>
/// Gets or sets the progress handler to report progress for time consuming actions.
/// </summary>
public IProgressHandler ProgressHandler { get; set; }
/// <inheritdoc />
public new IMapLayer SelectedLayer
{
get
{
return base.SelectedLayer as IMapLayer;
}
set
{
base.SelectedLayer = value;
}
}
#endregion
/// <summary>
/// The default, indexed value of type T.
/// </summary>
/// <param name="index">The numeric index.</param>
/// <returns>An object of type T corresponding to the index value specified.</returns>
public new IMapLayer this[int index]
{
get
{
return base[index] as IMapLayer;
}
set
{
base[index] = value;
}
}
#region Methods
/// <summary>
/// This overload automatically constructs a new MapLayer from the specified
/// feature layer with the default drawing characteristics and returns a valid
/// IMapLayer which can be further cast into a PointLayer, MapLineLayer or
/// a PolygonLayer, depending on the data that is passed in.
/// </summary>
/// <param name="layer">A pre-existing FeatureLayer that has already been created from a featureSet.</param>
public void Add(IMapLayer layer)
{
base.Add(layer);
}
/// <summary>
/// Adds the elements of the specified collection to the end of the System.Collections.Generic.List<T>.
/// </summary>
/// <param name="collection">collection: The collection whose elements should be added to the end of the
/// System.Collections.Generic.List<T>. The collection itself cannot be null, but it can contain elements that are null,
/// if type T is a reference type.</param>
/// <exception cref="System.ApplicationException">Unable to add while the ReadOnly property is set to true.</exception>
public void AddRange(IEnumerable<IMapLayer> collection)
{
foreach (IMapLayer layer in collection)
{
base.Add(layer);
}
}
/// <summary>
/// Adds the specified fileName to the map as a new layer.
/// </summary>
/// <param name="fileName">The string fileName to add as a layer.</param>
/// <returns>An IMapLayer that is the layer handle for the specified file.</returns>
public virtual IMapLayer Add(string fileName)
{
IDataSet dataSet = DataManager.DefaultDataManager.OpenFile(fileName);
return Add(dataSet);
}
/// <summary>
/// Adds the dataset specified to the file. Depending on whether this is a featureSet,
/// Raster, or ImageData, this will return the appropriate layer for the map.
/// </summary>
/// <param name="dataSet">A dataset.</param>
/// <returns>The IMapLayer to add.</returns>
public virtual IMapLayer Add(IDataSet dataSet)
{
var ss = dataSet as ISelfLoadSet;
if (ss != null) return Add(ss);
var fs = dataSet as IFeatureSet;
if (fs != null) return Add(fs);
var r = dataSet as IRaster;
if (r != null) return Add(r);
var id = dataSet as IImageData;
return id != null ? Add(id) : null;
}
/// <summary>
/// Adds the layers of the given ISelfLoadSet to the map.
/// </summary>
/// <param name="self">The ISelfLoadSet whose layers should be added to the map.</param>
/// <returns>The added group.</returns>
public IMapLayer Add(ISelfLoadSet self)
{
IMapLayer ml = self.GetLayer();
if (ml != null) Add(ml);
return ml;
}
/// <summary>
/// This overload automatically constructs a new MapLayer from the specified
/// feature layer with the default drawing characteristics and returns a valid
/// IMapLayer which can be further cast into a PointLayer, MapLineLayer or
/// a PolygonLayer, depending on the data that is passed in.
/// </summary>
/// <param name="featureSet">Any valid IFeatureSet that does not yet have drawing characteristics.</param>
/// <returns>A newly created valid implementation of FeatureLayer which at least gives a few more common
/// drawing related methods and can also be cast into the appropriate Point, Line or Polygon layer.</returns>
public virtual IMapFeatureLayer Add(IFeatureSet featureSet)
{
if (featureSet == null) return null;
featureSet.ProgressHandler = ProgressHandler;
IMapFeatureLayer res = null;
if (featureSet.FeatureType == FeatureType.Point || featureSet.FeatureType == FeatureType.MultiPoint)
{
res = new MapPointLayer(featureSet);
}
else if (featureSet.FeatureType == FeatureType.Line)
{
res = new MapLineLayer(featureSet);
}
else if (featureSet.FeatureType == FeatureType.Polygon)
{
res = new MapPolygonLayer(featureSet);
}
if (res != null)
{
base.Add(res);
res.ProgressHandler = ProgressHandler;
}
return res;
}
/// <summary>
/// Adds the raster to layer collection.
/// </summary>
/// <param name="raster">Raster that gets added.</param>
/// <returns>The IMapRasterLayer that was created.</returns>
public virtual IMapRasterLayer Add(IRaster raster)
{
if (raster == null) return null;
raster.ProgressHandler = ProgressHandler;
var gr = new MapRasterLayer(raster);
Add(gr);
return gr;
}
/// <summary>
/// Adds the specified image data as a new layer to the map.
/// </summary>
/// <param name="image">The image to add as a layer.</param>
/// <returns>the IMapImageLayer interface for the layer that was added to the map.</returns>
public IMapImageLayer Add(IImageData image)
{
if (image == null) return null;
if (image.Height == 0 || image.Width == 0) return null;
var il = new MapImageLayer(image);
base.Add(il);
return il;
}
/// <summary>
/// This copies the members of this collection to the specified array index, but
/// only if they match the IGeoLayer interface. (Other kinds of layers can be
/// added to this collection by casting it to a LayerCollection).
/// </summary>
/// <param name="inArray">The array of IGeoLayer interfaces to copy values to.</param>
/// <param name="arrayIndex">The zero-based integer index in the output array to start copying values to.</param>
public void CopyTo(IMapLayer[] inArray, int arrayIndex)
{
int index = arrayIndex;
foreach (IMapLayer layer in this)
{
if (layer != null)
{
inArray[index] = layer;
index++;
}
}
}
/// <summary>
/// Tests to see if the specified IMapLayer exists in the current collection.
/// </summary>
/// <param name="item">Layer that gets checked.</param>
/// <returns>True, if its contained.</returns>
public bool Contains(IMapLayer item)
{
return Contains(item as ILayer);
}
/// <summary>
/// Gets the zero-based integer index of the specified IMapLayer in this collection.
/// </summary>
/// <param name="item">Layer whose index should be returned.</param>
/// <returns>-1 if the layer is not contained otherweise the zero-based index.</returns>
public int IndexOf(IMapLayer item)
{
return IndexOf(item as ILayer);
}
/// <summary>
/// Inserts an element into the System.Collections.Generic.List<T> at the specified index.
/// </summary>
/// <param name="index">The zero-based index at which item should be inserted.</param>
/// <param name="item">The object to insert. The value can be null for reference types.</param>
/// <exception cref="System.ArgumentOutOfRangeException">index is less than 0.-or-index is greater than System.Collections.Generic.List<T>.Count.</exception>
/// <exception cref="System.ApplicationException">Unable to insert while the ReadOnly property is set to true.</exception>
public void Insert(int index, IMapLayer item)
{
base.Insert(index, item);
}
/// <summary>
/// Moves the given layer to the given position.
/// </summary>
/// <param name="layer">Layer that gets moved.</param>
/// <param name="newPosition">Position, the layer is moved to.</param>
public void Move(IMapLayer layer, int newPosition)
{
base.Move(layer, newPosition);
}
/// <summary>
/// Removes the first occurrence of a specific object from the System.Collections.Generic.List<T>.
/// </summary>
/// <param name="item">The object to remove from the System.Collections.Generic.List<T>. The value can be null for reference types.</param>
/// <returns>true if item is successfully removed; otherwise, false. This method also returns false if item was not
/// found in the System.Collections.Generic.List<T>.</returns>
/// <exception cref="System.ApplicationException">Unable to remove while the ReadOnly property is set to true.</exception>
public bool Remove(IMapLayer item)
{
return base.Remove(item);
}
/// <summary>
/// Inserts the elements of a collection into the EventList<T> at the specified index.
/// </summary>
/// <param name="index">The zero-based index at which the new elements should be inserted.</param>
/// <param name="collection">The collection whose elements should be inserted into the EventList<T>. The collection itself cannot be null, but it can contain elements that are null, if type T is a reference type.</param>
/// <exception cref="System.ArgumentOutOfRangeException">index is less than 0.-or-index is greater than EventList<T>.Count.</exception>
/// <exception cref="System.ArgumentNullException">collection is null.</exception>
/// <exception cref="System.ApplicationException">Unable to insert while the ReadOnly property is set to true.</exception>
public void InsertRange(int index, IEnumerable<IMapLayer> collection)
{
int i = index;
foreach (IMapLayer gl in collection)
{
Insert(i, (ILayer)gl);
i++;
}
}
/// <inheritdoc />
public new IEnumerator<IMapLayer> GetEnumerator()
{
return new MapLayerEnumerator(base.GetEnumerator());
}
/// <summary>
/// This simply forwards the call from a layer to the container of this collection (like a MapFrame).
/// </summary>
/// <param name="sender">The layer that actually changed.</param>
/// <param name="e">The clip args.</param>
protected virtual void OnBufferChanged(object sender, ClipArgs e)
{
BufferChanged?.Invoke(sender, e);
}
#endregion
#region Classes
private class MapLayerEnumerator : IEnumerator<IMapLayer>
{
private readonly IEnumerator<ILayer> _internalEnumerator;
/// <summary>
/// Initializes a new instance of the <see cref="MapLayerEnumerator"/> class.
/// </summary>
/// <param name="source">Source used as internal enumerator.</param>
public MapLayerEnumerator(IEnumerator<ILayer> source)
{
_internalEnumerator = source;
}
#region IEnumerator<IMapLayer> Members
/// <summary>
/// Gets the current member as an IMapLayer.
/// </summary>
public IMapLayer Current => _internalEnumerator.Current as IMapLayer;
object IEnumerator.Current => _internalEnumerator.Current;
/// <summary>
/// Calls the Dispose method.
/// </summary>
public void Dispose()
{
_internalEnumerator.Dispose();
}
/// <summary>
/// Moves to the next member.
/// </summary>
/// <returns>boolean, true if the enumerator was able to advance.</returns>
public bool MoveNext()
{
while (_internalEnumerator.MoveNext())
{
var result = _internalEnumerator.Current as IMapLayer;
if (result != null) return true;
}
return false;
}
/// <summary>
/// Resets to before the first member.
/// </summary>
public void Reset()
{
_internalEnumerator.Reset();
}
#endregion
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Xml;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, System.Runtime.Serialization.DataContract>;
using System.Diagnostics;
namespace System.Runtime.Serialization.Json
{
#if uapaot
public class XmlObjectSerializerReadContextComplexJson : XmlObjectSerializerReadContextComplex
#else
internal class XmlObjectSerializerReadContextComplexJson : XmlObjectSerializerReadContextComplex
#endif
{
private string _extensionDataValueType;
private DataContractJsonSerializer _jsonSerializer;
private DateTimeFormat _dateTimeFormat;
private bool _useSimpleDictionaryFormat;
public XmlObjectSerializerReadContextComplexJson(DataContractJsonSerializer serializer, DataContract rootTypeDataContract)
: base(null, int.MaxValue, new StreamingContext(), true)
{
this.rootTypeDataContract = rootTypeDataContract;
this.serializerKnownTypeList = serializer.KnownTypes;
_jsonSerializer = serializer;
}
internal XmlObjectSerializerReadContextComplexJson(DataContractJsonSerializerImpl serializer, DataContract rootTypeDataContract)
: base(serializer, serializer.MaxItemsInObjectGraph, new StreamingContext(), false)
{
this.rootTypeDataContract = rootTypeDataContract;
this.serializerKnownTypeList = serializer.knownTypeList;
_dateTimeFormat = serializer.DateTimeFormat;
_useSimpleDictionaryFormat = serializer.UseSimpleDictionaryFormat;
}
internal static XmlObjectSerializerReadContextComplexJson CreateContext(DataContractJsonSerializerImpl serializer, DataContract rootTypeDataContract)
{
return new XmlObjectSerializerReadContextComplexJson(serializer, rootTypeDataContract);
}
protected override object ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader)
{
return DataContractJsonSerializerImpl.ReadJsonValue(dataContract, reader, this);
}
public int GetJsonMemberIndex(XmlReaderDelegator xmlReader, XmlDictionaryString[] memberNames, int memberIndex, ExtensionDataObject extensionData)
{
int length = memberNames.Length;
if (length != 0)
{
for (int i = 0, index = (memberIndex + 1) % length; i < length; i++, index = (index + 1) % length)
{
if (xmlReader.IsStartElement(memberNames[index], XmlDictionaryString.Empty))
{
return index;
}
}
string name;
if (TryGetJsonLocalName(xmlReader, out name))
{
for (int i = 0, index = (memberIndex + 1) % length; i < length; i++, index = (index + 1) % length)
{
if (memberNames[index].Value == name)
{
return index;
}
}
}
}
HandleMemberNotFound(xmlReader, extensionData, memberIndex);
return length;
}
internal IList<Type> SerializerKnownTypeList
{
get
{
return this.serializerKnownTypeList;
}
}
public bool UseSimpleDictionaryFormat
{
get
{
return _useSimpleDictionaryFormat;
}
}
protected override void StartReadExtensionDataValue(XmlReaderDelegator xmlReader)
{
_extensionDataValueType = xmlReader.GetAttribute(JsonGlobals.typeString);
}
protected override IDataNode ReadPrimitiveExtensionDataValue(XmlReaderDelegator xmlReader, string dataContractName, string dataContractNamespace)
{
IDataNode dataNode;
switch (_extensionDataValueType)
{
case null:
case JsonGlobals.stringString:
dataNode = new DataNode<string>(xmlReader.ReadContentAsString());
break;
case JsonGlobals.booleanString:
dataNode = new DataNode<bool>(xmlReader.ReadContentAsBoolean());
break;
case JsonGlobals.numberString:
dataNode = ReadNumericalPrimitiveExtensionDataValue(xmlReader);
break;
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
XmlObjectSerializer.CreateSerializationException(SR.Format(SR.JsonUnexpectedAttributeValue, _extensionDataValueType)));
}
xmlReader.ReadEndElement();
return dataNode;
}
private IDataNode ReadNumericalPrimitiveExtensionDataValue(XmlReaderDelegator xmlReader)
{
TypeCode type;
object numericalValue = JsonObjectDataContract.ParseJsonNumber(xmlReader.ReadContentAsString(), out type);
switch (type)
{
case TypeCode.Byte:
return new DataNode<byte>((byte)numericalValue);
case TypeCode.SByte:
return new DataNode<sbyte>((sbyte)numericalValue);
case TypeCode.Int16:
return new DataNode<short>((short)numericalValue);
case TypeCode.Int32:
return new DataNode<int>((int)numericalValue);
case TypeCode.Int64:
return new DataNode<long>((long)numericalValue);
case TypeCode.UInt16:
return new DataNode<ushort>((ushort)numericalValue);
case TypeCode.UInt32:
return new DataNode<uint>((uint)numericalValue);
case TypeCode.UInt64:
return new DataNode<ulong>((ulong)numericalValue);
case TypeCode.Single:
return new DataNode<float>((float)numericalValue);
case TypeCode.Double:
return new DataNode<double>((double)numericalValue);
case TypeCode.Decimal:
return new DataNode<decimal>((decimal)numericalValue);
default:
throw new InvalidOperationException(SR.ParseJsonNumberReturnInvalidNumber);
}
}
internal override void ReadAttributes(XmlReaderDelegator xmlReader)
{
if (attributes == null)
attributes = new Attributes();
attributes.Reset();
if (xmlReader.MoveToAttribute(JsonGlobals.typeString) && xmlReader.Value == JsonGlobals.nullString)
{
attributes.XsiNil = true;
}
else if (xmlReader.MoveToAttribute(JsonGlobals.serverTypeString))
{
XmlQualifiedName qualifiedTypeName = JsonReaderDelegator.ParseQualifiedName(xmlReader.Value);
attributes.XsiTypeName = qualifiedTypeName.Name;
string serverTypeNamespace = qualifiedTypeName.Namespace;
if (!string.IsNullOrEmpty(serverTypeNamespace))
{
switch (serverTypeNamespace[0])
{
case '#':
serverTypeNamespace = string.Concat(Globals.DataContractXsdBaseNamespace, serverTypeNamespace.Substring(1));
break;
case '\\':
if (serverTypeNamespace.Length >= 2)
{
switch (serverTypeNamespace[1])
{
case '#':
case '\\':
serverTypeNamespace = serverTypeNamespace.Substring(1);
break;
default:
break;
}
}
break;
default:
break;
}
}
attributes.XsiTypeNamespace = serverTypeNamespace;
}
xmlReader.MoveToElement();
}
internal DataContract ResolveDataContractFromType(string typeName, string typeNs, DataContract memberTypeContract)
{
this.PushKnownTypes(this.rootTypeDataContract);
this.PushKnownTypes(memberTypeContract);
XmlQualifiedName qname = ParseQualifiedName(typeName);
DataContract contract = ResolveDataContractFromKnownTypes(qname.Name, TrimNamespace(qname.Namespace), memberTypeContract);
this.PopKnownTypes(this.rootTypeDataContract);
this.PopKnownTypes(memberTypeContract);
return contract;
}
internal void CheckIfTypeNeedsVerifcation(DataContract declaredContract, DataContract runtimeContract)
{
bool verifyType = true;
CollectionDataContract collectionContract = declaredContract as CollectionDataContract;
if (collectionContract != null && collectionContract.UnderlyingType.IsInterface)
{
switch (collectionContract.Kind)
{
case CollectionKind.Dictionary:
case CollectionKind.GenericDictionary:
verifyType = declaredContract.Name == runtimeContract.Name;
break;
default:
Type t = collectionContract.ItemType.MakeArrayType();
verifyType = (t != runtimeContract.UnderlyingType);
break;
}
}
if (verifyType)
{
this.PushKnownTypes(declaredContract);
VerifyType(runtimeContract);
this.PopKnownTypes(declaredContract);
}
}
internal void VerifyType(DataContract dataContract)
{
DataContract knownContract = ResolveDataContractFromKnownTypes(dataContract.StableName.Name, dataContract.StableName.Namespace, null /*memberTypeContract*/);
if (knownContract == null || knownContract.UnderlyingType != dataContract.UnderlyingType)
{
throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.DcTypeNotFoundOnSerialize, DataContract.GetClrTypeFullName(dataContract.UnderlyingType), dataContract.StableName.Name, dataContract.StableName.Namespace)));
}
}
internal string TrimNamespace(string serverTypeNamespace)
{
if (!string.IsNullOrEmpty(serverTypeNamespace))
{
switch (serverTypeNamespace[0])
{
case '#':
serverTypeNamespace = string.Concat(Globals.DataContractXsdBaseNamespace, serverTypeNamespace.Substring(1));
break;
case '\\':
if (serverTypeNamespace.Length >= 2)
{
switch (serverTypeNamespace[1])
{
case '#':
case '\\':
serverTypeNamespace = serverTypeNamespace.Substring(1);
break;
default:
break;
}
}
break;
default:
break;
}
}
return serverTypeNamespace;
}
internal static XmlQualifiedName ParseQualifiedName(string qname)
{
string name, ns;
if (string.IsNullOrEmpty(qname))
{
name = ns = string.Empty;
}
else
{
qname = qname.Trim();
int colon = qname.IndexOf(':');
if (colon >= 0)
{
name = qname.Substring(0, colon);
ns = qname.Substring(colon + 1);
}
else
{
name = qname;
ns = string.Empty;
}
}
return new XmlQualifiedName(name, ns);
}
internal override DataContract GetDataContract(RuntimeTypeHandle typeHandle, Type type)
{
DataContract dataContract = base.GetDataContract(typeHandle, type);
DataContractJsonSerializer.CheckIfTypeIsReference(dataContract);
return dataContract;
}
internal override DataContract GetDataContractSkipValidation(int typeId, RuntimeTypeHandle typeHandle, Type type)
{
DataContract dataContract = base.GetDataContractSkipValidation(typeId, typeHandle, type);
DataContractJsonSerializer.CheckIfTypeIsReference(dataContract);
return dataContract;
}
internal override DataContract GetDataContract(int id, RuntimeTypeHandle typeHandle)
{
DataContract dataContract = base.GetDataContract(id, typeHandle);
DataContractJsonSerializer.CheckIfTypeIsReference(dataContract);
return dataContract;
}
internal static bool TryGetJsonLocalName(XmlReaderDelegator xmlReader, out string name)
{
if (xmlReader.IsStartElement(JsonGlobals.itemDictionaryString, JsonGlobals.itemDictionaryString))
{
if (xmlReader.MoveToAttribute(JsonGlobals.itemString))
{
name = xmlReader.Value;
return true;
}
}
name = null;
return false;
}
public static string GetJsonMemberName(XmlReaderDelegator xmlReader)
{
string name;
if (!TryGetJsonLocalName(xmlReader, out name))
{
name = xmlReader.LocalName;
}
return name;
}
#if !uapaot
public static void ThrowDuplicateMemberException(object obj, XmlDictionaryString[] memberNames, int memberIndex)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(
SR.Format(SR.JsonDuplicateMemberInInput, DataContract.GetClrTypeFullName(obj.GetType()), memberNames[memberIndex])));
}
public static void ThrowMissingRequiredMembers(object obj, XmlDictionaryString[] memberNames, byte[] expectedElements, byte[] requiredElements)
{
StringBuilder stringBuilder = new StringBuilder();
int missingMembersCount = 0;
for (int i = 0; i < memberNames.Length; i++)
{
if (IsBitSet(expectedElements, i) && IsBitSet(requiredElements, i))
{
if (stringBuilder.Length != 0)
stringBuilder.Append(", ");
stringBuilder.Append(memberNames[i]);
missingMembersCount++;
}
}
if (missingMembersCount == 1)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.Format(
SR.JsonOneRequiredMemberNotFound, DataContract.GetClrTypeFullName(obj.GetType()), stringBuilder.ToString())));
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.Format(
SR.JsonRequiredMembersNotFound, DataContract.GetClrTypeFullName(obj.GetType()), stringBuilder.ToString())));
}
}
private static bool IsBitSet(byte[] bytes, int bitIndex)
{
return BitFlagsGenerator.IsBitSet(bytes, bitIndex);
}
#endif
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Tests.Cache.Platform
{
using System;
using System.IO;
using System.Linq;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Configuration;
using Apache.Ignite.Core.Cache.Query;
using Apache.Ignite.Core.Configuration;
using Apache.Ignite.Core.Impl.Cache;
using NUnit.Framework;
/// <summary>
/// Tests platform cache with native persistence.
/// </summary>
public class PlatformCacheWithPersistenceTest
{
/** Cache name. */
private const string CacheName = "persistentCache";
/** Entry count. */
private const int Count = 100;
/** Temp dir for WAL. */
private readonly string _tempDir = PathUtils.GetTempDirectoryName();
/** Cache. */
private ICache<int,int> _cache;
/** Current key. Every test needs a key that was not used before. */
private int _key = 1;
/// <summary>
/// Sets up the test.
/// </summary>
[TestFixtureSetUp]
public void FixtureSetUp()
{
TestUtils.ClearWorkDir();
// Start Ignite, put data, stop.
using (var ignite = StartServer())
{
var cache = ignite.GetCache<int, int>(CacheName);
cache.PutAll(Enumerable.Range(1, Count).ToDictionary(x => x, x => x));
Assert.AreEqual(Count, cache.GetSize());
Assert.AreEqual(Count, cache.GetLocalSize(CachePeekMode.Platform));
}
// Start again to test persistent data restore.
var ignite2 = StartServer();
_cache = ignite2.GetCache<int, int>(CacheName);
// Platform cache is empty initially, because all entries are only on disk.
Assert.AreEqual(Count, _cache.GetSize());
Assert.AreEqual(0, _cache.GetLocalSize(CachePeekMode.Platform));
}
/// <summary>
/// Tears down the test.
/// </summary>
[TestFixtureTearDown]
public void TearDown()
{
Ignition.StopAll(true);
if (Directory.Exists(_tempDir))
{
Directory.Delete(_tempDir, true);
}
TestUtils.ClearWorkDir();
}
/// <summary>
/// Tests get operation.
/// </summary>
[Test]
public void TestGetRestoresPlatformCacheDataFromPersistence()
{
TestCacheOperation(k => _cache.Get(k));
}
/// <summary>
/// Tests getAll operation.
/// </summary>
[Test]
public void TestGetAllRestoresPlatformCacheDataFromPersistence()
{
TestCacheOperation(k => _cache.GetAll(new[] { k }));
}
/// <summary>
/// Tests containsKey operation.
/// </summary>
[Test]
public void TestContainsKeyRestoresPlatformCacheDataFromPersistence()
{
TestCacheOperation(k => _cache.ContainsKey(k));
}
/// <summary>
/// Tests containsKeys operation.
/// </summary>
[Test]
public void TestContainsKeysRestoresPlatformCacheDataFromPersistence()
{
TestCacheOperation(k => _cache.ContainsKeys(new[] { k }));
}
/// <summary>
/// Tests put operation.
/// </summary>
[Test]
public void TestPutUpdatesPlatformCache()
{
TestCacheOperation(k => _cache.Put(k, -k), k => -k);
}
/// <summary>
/// Tests getAndPut operation.
/// </summary>
[Test]
public void TestGetAndPutUpdatesPlatformCache()
{
TestCacheOperation(k => _cache.GetAndPut(k, -k), k => -k);
}
/// <summary>
/// Tests that local partition scan optimization is disabled when persistence is enabled.
/// See <see cref="CacheImpl{TK,TV}.ScanPlatformCache"/>.
/// </summary>
[Test]
public void TestScanQueryLocalPartitionScanOptimizationDisabledWithPersistence()
{
var res = _cache.Query(new ScanQuery<int, int>()).GetAll();
Assert.AreEqual(Count, res.Count);
var resLocal = _cache.Query(new ScanQuery<int, int> { Local = true }).GetAll();
Assert.AreEqual(Count, resLocal.Count);
var resPartition = _cache.Query(new ScanQuery<int, int> { Partition = 99 }).GetAll();
Assert.AreEqual(1, resPartition.Count);
var resLocalPartition = _cache.Query(new ScanQuery<int, int> { Local = true, Partition = 99 }).GetAll();
Assert.AreEqual(1, resLocalPartition.Count);
}
/// <summary>
/// Tests that scan query with filter does not need platform cache data to return correct results.
/// </summary>
[Test]
public void TestScanQueryWithFilterUsesPersistentData()
{
var res = _cache.Query(new ScanQuery<int, int> { Filter = new EvenValueFilter() }).GetAll();
Assert.AreEqual(Count / 2, res.Count);
}
/// <summary>
/// Starts the node.
/// </summary>
private IIgnite StartServer()
{
var ignite = Ignition.Start(GetIgniteConfiguration());
ignite.GetCluster().SetActive(true);
return ignite;
}
/// <summary>
/// Gets the configuration.
/// </summary>
private IgniteConfiguration GetIgniteConfiguration()
{
return new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
DataStorageConfiguration = new DataStorageConfiguration
{
StoragePath = Path.Combine(_tempDir, "Store"),
WalPath = Path.Combine(_tempDir, "WalStore"),
WalArchivePath = Path.Combine(_tempDir, "WalArchive"),
DefaultDataRegionConfiguration = new DataRegionConfiguration
{
Name = DataStorageConfiguration.DefaultDataRegionName,
PersistenceEnabled = true
}
},
CacheConfiguration = new[]
{
new CacheConfiguration
{
Name = CacheName,
PlatformCacheConfiguration = new PlatformCacheConfiguration()
}
}
};
}
/// <summary>
/// Tests that cache operation causes platform cache to be populated for the key.
/// </summary>
private void TestCacheOperation(Action<int> operation, Func<int, int> expectedFunc = null)
{
var k = _key++;
operation(k);
var expected = expectedFunc == null ? k : expectedFunc(k);
Assert.AreEqual(expected, _cache.LocalPeek(k, CachePeekMode.Platform));
}
private class EvenValueFilter : ICacheEntryFilter<int, int>
{
public bool Invoke(ICacheEntry<int, int> entry)
{
return entry.Value % 2 == 0;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Xml.XPath;
using System.Xml.Schema;
using System.Xml.Xsl.Qil;
using System.Xml.Xsl.Runtime;
using System.Xml.Xsl.XPath;
namespace System.Xml.Xsl.Xslt
{
using FunctionInfo = XPathBuilder.FunctionInfo<QilGenerator.FuncId>;
using T = XmlQueryTypeFactory;
internal partial class QilGenerator : IXPathEnvironment
{
// Everywhere in this code in case of error in the stylesheet we should throw XslLoadException.
// This helper IErrorHelper implementation is used to wrap XmlException's into XslLoadException's.
private readonly struct ThrowErrorHelper : IErrorHelper
{
public void ReportError(string res, params string[] args)
{
Debug.Assert(args == null || args.Length == 0, "Error message must already be composed in res");
throw new XslLoadException(SR.Xml_UserException, res);
}
public void ReportWarning(string res, params string[] args)
{
Debug.Fail("Should never get here");
}
}
// -------------------------------- IXPathEnvironment --------------------------------
// IXPathEnvironment represents static context (namespaces, focus) and most naturaly implemented by QilGenerator itself
// $var current() key()
// */@select or */@test + + +
// template/@match - - +
// key/@match - - -
// key/@use - + -
// number/@count + - +
// number/@from + - +
private bool _allowVariables = true;
private bool _allowCurrent = true;
private bool _allowKey = true;
private void SetEnvironmentFlags(bool allowVariables, bool allowCurrent, bool allowKey)
{
_allowVariables = allowVariables;
_allowCurrent = allowCurrent;
_allowKey = allowKey;
}
XPathQilFactory IXPathEnvironment.Factory { get { return _f; } }
// IXPathEnvironment interface
QilNode IFocus.GetCurrent() { return this.GetCurrentNode(); }
QilNode IFocus.GetPosition() { return this.GetCurrentPosition(); }
QilNode IFocus.GetLast() { return this.GetLastPosition(); }
string IXPathEnvironment.ResolvePrefix(string prefix)
{
return ResolvePrefixThrow(true, prefix);
}
QilNode IXPathEnvironment.ResolveVariable(string prefix, string name)
{
if (!_allowVariables)
{
throw new XslLoadException(SR.Xslt_VariablesNotAllowed);
}
string ns = ResolvePrefixThrow(/*ignoreDefaultNs:*/true, prefix);
Debug.Assert(ns != null);
// Look up in params and variables of the current scope and all outer ones
QilNode var = _scope.LookupVariable(name, ns);
if (var == null)
{
throw new XslLoadException(SR.Xslt_InvalidVariable, Compiler.ConstructQName(prefix, name));
}
// All Node* parameters are guaranteed to be in document order with no duplicates, so TypeAssert
// this so that optimizer can use this information to avoid redundant sorts and duplicate removal.
XmlQueryType varType = var.XmlType;
if (var.NodeType == QilNodeType.Parameter && varType.IsNode && varType.IsNotRtf && varType.MaybeMany && !varType.IsDod)
{
var = _f.TypeAssert(var, XmlQueryTypeFactory.NodeSDod);
}
return var;
}
// NOTE: DO NOT call QilNode.Clone() while executing this method since fixup nodes cannot be cloned
QilNode IXPathEnvironment.ResolveFunction(string prefix, string name, IList<QilNode> args, IFocus env)
{
Debug.Assert(!args.IsReadOnly, "Writable collection expected");
if (prefix.Length == 0)
{
FunctionInfo func;
if (FunctionTable.TryGetValue(name, out func))
{
func.CastArguments(args, name, _f);
switch (func.id)
{
case FuncId.Current:
if (!_allowCurrent)
{
throw new XslLoadException(SR.Xslt_CurrentNotAllowed);
}
// NOTE: This is the only place where the current node (and not the context node) must be used
return ((IXPathEnvironment)this).GetCurrent();
case FuncId.Key:
if (!_allowKey)
{
throw new XslLoadException(SR.Xslt_KeyNotAllowed);
}
return CompileFnKey(args[0], args[1], env);
case FuncId.Document: return CompileFnDocument(args[0], args.Count > 1 ? args[1] : null);
case FuncId.FormatNumber: return CompileFormatNumber(args[0], args[1], args.Count > 2 ? args[2] : null);
case FuncId.UnparsedEntityUri: return CompileUnparsedEntityUri(args[0]);
case FuncId.GenerateId: return CompileGenerateId(args.Count > 0 ? args[0] : env.GetCurrent());
case FuncId.SystemProperty: return CompileSystemProperty(args[0]);
case FuncId.ElementAvailable: return CompileElementAvailable(args[0]);
case FuncId.FunctionAvailable: return CompileFunctionAvailable(args[0]);
default:
Debug.Fail(func.id + " is present in the function table, but absent from the switch");
return null;
}
}
else
{
throw new XslLoadException(SR.Xslt_UnknownXsltFunction, Compiler.ConstructQName(prefix, name));
}
}
else
{
string ns = ResolvePrefixThrow(/*ignoreDefaultNs:*/true, prefix);
Debug.Assert(ns != null);
if (ns == XmlReservedNs.NsMsxsl)
{
if (name == "node-set")
{
FunctionInfo.CheckArity(/*minArg:*/1, /*maxArg:*/1, name, args.Count);
return CompileMsNodeSet(args[0]);
}
else if (name == "string-compare")
{
FunctionInfo.CheckArity(/*minArg:*/2, /*maxArg:*/4, name, args.Count);
return _f.InvokeMsStringCompare(
/*x: */_f.ConvertToString(args[0]),
/*y: */_f.ConvertToString(args[1]),
/*lang: */2 < args.Count ? _f.ConvertToString(args[2]) : _f.String(string.Empty),
/*options:*/3 < args.Count ? _f.ConvertToString(args[3]) : _f.String(string.Empty)
);
}
else if (name == "utc")
{
FunctionInfo.CheckArity(/*minArg:*/1, /*maxArg:*/1, name, args.Count);
return _f.InvokeMsUtc(/*datetime:*/_f.ConvertToString(args[0]));
}
else if (name == "format-date" || name == "format-time")
{
FunctionInfo.CheckArity(/*minArg:*/1, /*maxArg:*/3, name, args.Count);
bool fwdCompat = (_xslVersion == XslVersion.ForwardsCompatible);
return _f.InvokeMsFormatDateTime(
/*datetime:*/_f.ConvertToString(args[0]),
/*format: */1 < args.Count ? _f.ConvertToString(args[1]) : _f.String(string.Empty),
/*lang: */2 < args.Count ? _f.ConvertToString(args[2]) : _f.String(string.Empty),
/*isDate: */_f.Boolean(name == "format-date")
);
}
else if (name == "local-name")
{
FunctionInfo.CheckArity(/*minArg:*/1, /*maxArg:*/1, name, args.Count);
return _f.InvokeMsLocalName(_f.ConvertToString(args[0]));
}
else if (name == "namespace-uri")
{
FunctionInfo.CheckArity(/*minArg:*/1, /*maxArg:*/1, name, args.Count);
return _f.InvokeMsNamespaceUri(_f.ConvertToString(args[0]), env.GetCurrent());
}
else if (name == "number")
{
FunctionInfo.CheckArity(/*minArg:*/1, /*maxArg:*/1, name, args.Count);
return _f.InvokeMsNumber(args[0]);
}
}
if (ns == XmlReservedNs.NsExsltCommon)
{
if (name == "node-set")
{
FunctionInfo.CheckArity(/*minArg:*/1, /*maxArg:*/1, name, args.Count);
return CompileMsNodeSet(args[0]);
}
else if (name == "object-type")
{
FunctionInfo.CheckArity(/*minArg:*/1, /*maxArg:*/1, name, args.Count);
return EXslObjectType(args[0]);
}
}
// NOTE: If you add any function here, add it to IsFunctionAvailable as well
// Ensure that all node-set parameters are DocOrderDistinct
for (int i = 0; i < args.Count; i++)
args[i] = _f.SafeDocOrderDistinct(args[i]);
if (_compiler.Settings.EnableScript)
{
XmlExtensionFunction scrFunc = _compiler.Scripts.ResolveFunction(name, ns, args.Count, (IErrorHelper)this);
if (scrFunc != null)
{
return GenerateScriptCall(_f.QName(name, ns, prefix), scrFunc, args);
}
}
else
{
if (_compiler.Scripts.ScriptClasses.ContainsKey(ns))
{
ReportWarning(SR.Xslt_ScriptsProhibited);
return _f.Error(_lastScope.SourceLine, SR.Xslt_ScriptsProhibited);
}
}
return _f.XsltInvokeLateBound(_f.QName(name, ns, prefix), args);
}
}
private QilNode GenerateScriptCall(QilName name, XmlExtensionFunction scrFunc, IList<QilNode> args)
{
XmlQueryType xmlTypeFormalArg;
for (int i = 0; i < args.Count; i++)
{
xmlTypeFormalArg = scrFunc.GetXmlArgumentType(i);
switch (xmlTypeFormalArg.TypeCode)
{
case XmlTypeCode.Boolean: args[i] = _f.ConvertToBoolean(args[i]); break;
case XmlTypeCode.Double: args[i] = _f.ConvertToNumber(args[i]); break;
case XmlTypeCode.String: args[i] = _f.ConvertToString(args[i]); break;
case XmlTypeCode.Node: args[i] = xmlTypeFormalArg.IsSingleton ? _f.ConvertToNode(args[i]) : _f.ConvertToNodeSet(args[i]); break;
case XmlTypeCode.Item: break;
default: Debug.Fail("This XmlTypeCode should never be inferred from a Clr type: " + xmlTypeFormalArg.TypeCode); break;
}
}
return _f.XsltInvokeEarlyBound(name, scrFunc.Method, scrFunc.XmlReturnType, args);
}
private string ResolvePrefixThrow(bool ignoreDefaultNs, string prefix)
{
if (ignoreDefaultNs && prefix.Length == 0)
{
return string.Empty;
}
else
{
string ns = _scope.LookupNamespace(prefix);
if (ns == null)
{
if (prefix.Length != 0)
{
throw new XslLoadException(SR.Xslt_InvalidPrefix, prefix);
}
ns = string.Empty;
}
return ns;
}
}
//------------------------------------------------
// XSLT Functions
//------------------------------------------------
public enum FuncId
{
Current,
Document,
Key,
FormatNumber,
UnparsedEntityUri,
GenerateId,
SystemProperty,
ElementAvailable,
FunctionAvailable,
}
private static readonly XmlTypeCode[] s_argFnDocument = { XmlTypeCode.Item, XmlTypeCode.Node };
private static readonly XmlTypeCode[] s_argFnKey = { XmlTypeCode.String, XmlTypeCode.Item };
private static readonly XmlTypeCode[] s_argFnFormatNumber = { XmlTypeCode.Double, XmlTypeCode.String, XmlTypeCode.String };
public static Dictionary<string, FunctionInfo> FunctionTable = CreateFunctionTable();
private static Dictionary<string, FunctionInfo> CreateFunctionTable()
{
Dictionary<string, FunctionInfo> table = new Dictionary<string, FunctionInfo>(16);
table.Add("current", new FunctionInfo(FuncId.Current, 0, 0, null));
table.Add("document", new FunctionInfo(FuncId.Document, 1, 2, s_argFnDocument));
table.Add("key", new FunctionInfo(FuncId.Key, 2, 2, s_argFnKey));
table.Add("format-number", new FunctionInfo(FuncId.FormatNumber, 2, 3, s_argFnFormatNumber));
table.Add("unparsed-entity-uri", new FunctionInfo(FuncId.UnparsedEntityUri, 1, 1, XPathBuilder.argString));
table.Add("generate-id", new FunctionInfo(FuncId.GenerateId, 0, 1, XPathBuilder.argNodeSet));
table.Add("system-property", new FunctionInfo(FuncId.SystemProperty, 1, 1, XPathBuilder.argString));
table.Add("element-available", new FunctionInfo(FuncId.ElementAvailable, 1, 1, XPathBuilder.argString));
table.Add("function-available", new FunctionInfo(FuncId.FunctionAvailable, 1, 1, XPathBuilder.argString));
return table;
}
public static bool IsFunctionAvailable(string localName, string nsUri)
{
if (XPathBuilder.IsFunctionAvailable(localName, nsUri))
{
return true;
}
if (nsUri.Length == 0)
{
return FunctionTable.ContainsKey(localName) && localName != "unparsed-entity-uri";
}
if (nsUri == XmlReservedNs.NsMsxsl)
{
return (
localName == "node-set" ||
localName == "format-date" ||
localName == "format-time" ||
localName == "local-name" ||
localName == "namespace-uri" ||
localName == "number" ||
localName == "string-compare" ||
localName == "utc"
);
}
if (nsUri == XmlReservedNs.NsExsltCommon)
{
return localName == "node-set" || localName == "object-type";
}
return false;
}
public static bool IsElementAvailable(XmlQualifiedName name)
{
if (name.Namespace == XmlReservedNs.NsXslt)
{
string localName = name.Name;
return (
localName == "apply-imports" ||
localName == "apply-templates" ||
localName == "attribute" ||
localName == "call-template" ||
localName == "choose" ||
localName == "comment" ||
localName == "copy" ||
localName == "copy-of" ||
localName == "element" ||
localName == "fallback" ||
localName == "for-each" ||
localName == "if" ||
localName == "message" ||
localName == "number" ||
localName == "processing-instruction" ||
localName == "text" ||
localName == "value-of" ||
localName == "variable"
);
}
// NOTE: msxsl:script is not an "instruction", so we return false for it
return false;
}
private QilNode CompileFnKey(QilNode name, QilNode keys, IFocus env)
{
QilNode result;
QilIterator i, n, k;
if (keys.XmlType.IsNode)
{
if (keys.XmlType.IsSingleton)
{
result = CompileSingleKey(name, _f.ConvertToString(keys), env);
}
else
{
result = _f.Loop(i = _f.For(keys), CompileSingleKey(name, _f.ConvertToString(i), env));
}
}
else if (keys.XmlType.IsAtomicValue)
{
result = CompileSingleKey(name, _f.ConvertToString(keys), env);
}
else
{
result = _f.Loop(n = _f.Let(name), _f.Loop(k = _f.Let(keys),
_f.Conditional(_f.Not(_f.IsType(k, T.AnyAtomicType)),
_f.Loop(i = _f.For(_f.TypeAssert(k, T.NodeS)), CompileSingleKey(n, _f.ConvertToString(i), env)),
CompileSingleKey(n, _f.XsltConvert(k, T.StringX), env)
)
));
}
return _f.DocOrderDistinct(result);
}
private QilNode CompileSingleKey(QilNode name, QilNode key, IFocus env)
{
Debug.Assert(name.XmlType == T.StringX && key.XmlType == T.StringX);
QilNode result;
if (name.NodeType == QilNodeType.LiteralString)
{
string keyName = (string)(QilLiteral)name;
string prefix, local, nsUri;
_compiler.ParseQName(keyName, out prefix, out local, new ThrowErrorHelper());
nsUri = ResolvePrefixThrow(/*ignoreDefaultNs:*/true, prefix);
QilName qname = _f.QName(local, nsUri, prefix);
if (!_compiler.Keys.Contains(qname))
{
throw new XslLoadException(SR.Xslt_UndefinedKey, keyName);
}
result = CompileSingleKey(_compiler.Keys[qname], key, env);
}
else
{
if (_generalKey == null)
{
_generalKey = CreateGeneralKeyFunction();
}
QilIterator i = _f.Let(name);
QilNode resolvedName = ResolveQNameDynamic(/*ignoreDefaultNs:*/true, i);
result = _f.Invoke(_generalKey, _f.ActualParameterList(i, resolvedName, key, env.GetCurrent()));
result = _f.Loop(i, result);
}
return result;
}
private QilNode CompileSingleKey(List<Key> defList, QilNode key, IFocus env)
{
Debug.Assert(defList != null && defList.Count > 0);
if (defList.Count == 1)
{
return _f.Invoke(defList[0].Function, _f.ActualParameterList(env.GetCurrent(), key));
}
QilIterator i = _f.Let(key);
QilNode result = _f.Sequence();
foreach (Key keyDef in defList)
{
result.Add(_f.Invoke(keyDef.Function, _f.ActualParameterList(env.GetCurrent(), i)));
}
return _f.Loop(i, result);
}
private QilNode CompileSingleKey(List<Key> defList, QilIterator key, QilIterator context)
{
Debug.Assert(defList != null && defList.Count > 0);
QilList result = _f.BaseFactory.Sequence();
QilNode keyRef = null;
foreach (Key keyDef in defList)
{
keyRef = _f.Invoke(keyDef.Function, _f.ActualParameterList(context, key));
result.Add(keyRef);
}
return defList.Count == 1 ? keyRef : result;
}
private QilFunction CreateGeneralKeyFunction()
{
QilIterator name = _f.Parameter(T.StringX);
QilIterator resolvedName = _f.Parameter(T.QNameX);
QilIterator key = _f.Parameter(T.StringX);
QilIterator context = _f.Parameter(T.NodeNotRtf);
QilNode fdef = _f.Error(SR.Xslt_UndefinedKey, name);
for (int idx = 0; idx < _compiler.Keys.Count; idx++)
{
fdef = _f.Conditional(_f.Eq(resolvedName, _compiler.Keys[idx][0].Name.DeepClone(_f.BaseFactory)),
CompileSingleKey(_compiler.Keys[idx], key, context),
fdef
);
}
QilFunction result = _f.Function(_f.FormalParameterList(name, resolvedName, key, context), fdef, _f.False());
result.DebugName = "key";
_functions.Add(result);
return result;
}
private QilNode CompileFnDocument(QilNode uris, QilNode baseNode)
{
QilNode result;
QilIterator i, j, u;
if (!_compiler.Settings.EnableDocumentFunction)
{
ReportWarning(SR.Xslt_DocumentFuncProhibited);
return _f.Error(_lastScope.SourceLine, SR.Xslt_DocumentFuncProhibited);
}
if (uris.XmlType.IsNode)
{
result = _f.DocOrderDistinct(_f.Loop(i = _f.For(uris),
CompileSingleDocument(_f.ConvertToString(i), baseNode ?? i)
));
}
else if (uris.XmlType.IsAtomicValue)
{
result = CompileSingleDocument(_f.ConvertToString(uris), baseNode);
}
else
{
u = _f.Let(uris);
j = (baseNode != null) ? _f.Let(baseNode) : null;
result = _f.Conditional(_f.Not(_f.IsType(u, T.AnyAtomicType)),
_f.DocOrderDistinct(_f.Loop(i = _f.For(_f.TypeAssert(u, T.NodeS)),
CompileSingleDocument(_f.ConvertToString(i), j ?? i)
)),
CompileSingleDocument(_f.XsltConvert(u, T.StringX), j)
);
result = (baseNode != null) ? _f.Loop(j, result) : result;
result = _f.Loop(u, result);
}
return result;
}
private QilNode CompileSingleDocument(QilNode uri, QilNode baseNode)
{
_f.CheckString(uri);
QilNode baseUri;
if (baseNode == null)
{
baseUri = _f.String(_lastScope.SourceLine.Uri);
}
else
{
_f.CheckNodeSet(baseNode);
if (baseNode.XmlType.IsSingleton)
{
baseUri = _f.InvokeBaseUri(baseNode);
}
else
{
// According to errata E14, it is an error if the second argument node-set is empty
// and the URI reference is relative. We pass an empty string as a baseUri to indicate
// that case.
QilIterator i;
baseUri = _f.StrConcat(_f.Loop(i = _f.FirstNode(baseNode), _f.InvokeBaseUri(i)));
}
}
_f.CheckString(baseUri);
return _f.DataSource(uri, baseUri);
}
private QilNode CompileFormatNumber(QilNode value, QilNode formatPicture, QilNode formatName)
{
_f.CheckDouble(value);
_f.CheckString(formatPicture);
XmlQualifiedName resolvedName;
if (formatName == null)
{
resolvedName = new XmlQualifiedName();
// formatName must be non-null in the f.InvokeFormatNumberDynamic() call below
formatName = _f.String(string.Empty);
}
else
{
_f.CheckString(formatName);
if (formatName.NodeType == QilNodeType.LiteralString)
{
resolvedName = ResolveQNameThrow(/*ignoreDefaultNs:*/true, formatName);
}
else
{
resolvedName = null;
}
}
if (resolvedName != null)
{
DecimalFormatDecl format;
if (_compiler.DecimalFormats.Contains(resolvedName))
{
format = _compiler.DecimalFormats[resolvedName];
}
else
{
if (resolvedName != DecimalFormatDecl.Default.Name)
{
throw new XslLoadException(SR.Xslt_NoDecimalFormat, (string)(QilLiteral)formatName);
}
format = DecimalFormatDecl.Default;
}
// If both formatPicture and formatName are literal strings, there is no need to reparse
// formatPicture on every execution of this format-number(). Instead, we create a DecimalFormatter
// object on the first execution, save its index into a global variable, and reuse that object
// on all subsequent executions.
if (formatPicture.NodeType == QilNodeType.LiteralString)
{
QilIterator fmtIdx = _f.Let(_f.InvokeRegisterDecimalFormatter(formatPicture, format));
fmtIdx.DebugName = _f.QName("formatter" + _formatterCnt++, XmlReservedNs.NsXslDebug).ToString();
_gloVars.Add(fmtIdx);
return _f.InvokeFormatNumberStatic(value, fmtIdx);
}
_formatNumberDynamicUsed = true;
QilNode name = _f.QName(resolvedName.Name, resolvedName.Namespace);
return _f.InvokeFormatNumberDynamic(value, formatPicture, name, formatName);
}
else
{
_formatNumberDynamicUsed = true;
QilIterator i = _f.Let(formatName);
QilNode name = ResolveQNameDynamic(/*ignoreDefaultNs:*/true, i);
return _f.Loop(i, _f.InvokeFormatNumberDynamic(value, formatPicture, name, i));
}
}
private QilNode CompileUnparsedEntityUri(QilNode n)
{
_f.CheckString(n);
return _f.Error(_lastScope.SourceLine, SR.Xslt_UnsupportedXsltFunction, "unparsed-entity-uri");
}
private QilNode CompileGenerateId(QilNode n)
{
_f.CheckNodeSet(n);
if (n.XmlType.IsSingleton)
{
return _f.XsltGenerateId(n);
}
else
{
QilIterator i;
return _f.StrConcat(_f.Loop(i = _f.FirstNode(n), _f.XsltGenerateId(i)));
}
}
private XmlQualifiedName ResolveQNameThrow(bool ignoreDefaultNs, QilNode qilName)
{
string name = (string)(QilLiteral)qilName;
string prefix, local, nsUri;
_compiler.ParseQName(name, out prefix, out local, new ThrowErrorHelper());
nsUri = ResolvePrefixThrow(/*ignoreDefaultNs:*/ignoreDefaultNs, prefix);
return new XmlQualifiedName(local, nsUri);
}
private QilNode CompileSystemProperty(QilNode name)
{
_f.CheckString(name);
if (name.NodeType == QilNodeType.LiteralString)
{
XmlQualifiedName qname = ResolveQNameThrow(/*ignoreDefaultNs:*/true, name);
if (EvaluateFuncCalls)
{
XPathItem propValue = XsltFunctions.SystemProperty(qname);
if (propValue.ValueType == XsltConvert.StringType)
{
return _f.String(propValue.Value);
}
else
{
Debug.Assert(propValue.ValueType == XsltConvert.DoubleType);
return _f.Double((double)propValue.ValueAsDouble);
}
}
name = _f.QName(qname.Name, qname.Namespace);
}
else
{
name = ResolveQNameDynamic(/*ignoreDefaultNs:*/true, name);
}
return _f.InvokeSystemProperty(name);
}
private QilNode CompileElementAvailable(QilNode name)
{
_f.CheckString(name);
if (name.NodeType == QilNodeType.LiteralString)
{
XmlQualifiedName qname = ResolveQNameThrow(/*ignoreDefaultNs:*/false, name);
if (EvaluateFuncCalls)
{
return _f.Boolean(IsElementAvailable(qname));
}
name = _f.QName(qname.Name, qname.Namespace);
}
else
{
name = ResolveQNameDynamic(/*ignoreDefaultNs:*/false, name);
}
return _f.InvokeElementAvailable(name);
}
private QilNode CompileFunctionAvailable(QilNode name)
{
_f.CheckString(name);
if (name.NodeType == QilNodeType.LiteralString)
{
XmlQualifiedName qname = ResolveQNameThrow(/*ignoreDefaultNs:*/true, name);
if (EvaluateFuncCalls)
{
// Script blocks and extension objects cannot implement neither null nor XSLT namespace
if (qname.Namespace.Length == 0 || qname.Namespace == XmlReservedNs.NsXslt)
{
return _f.Boolean(QilGenerator.IsFunctionAvailable(qname.Name, qname.Namespace));
}
// We might precalculate the result for script namespaces as well
}
name = _f.QName(qname.Name, qname.Namespace);
}
else
{
name = ResolveQNameDynamic(/*ignoreDefaultNs:*/true, name);
}
return _f.InvokeFunctionAvailable(name);
}
private QilNode CompileMsNodeSet(QilNode n)
{
if (n.XmlType.IsNode && n.XmlType.IsNotRtf)
{
return n;
}
return _f.XsltConvert(n, T.NodeSDod);
}
//------------------------------------------------
// EXSLT Functions
//------------------------------------------------
private QilNode EXslObjectType(QilNode n)
{
if (EvaluateFuncCalls)
{
switch (n.XmlType.TypeCode)
{
case XmlTypeCode.Boolean: return _f.String("boolean");
case XmlTypeCode.Double: return _f.String("number");
case XmlTypeCode.String: return _f.String("string");
default:
if (n.XmlType.IsNode && n.XmlType.IsNotRtf)
{
return _f.String("node-set");
}
break;
}
}
return _f.InvokeEXslObjectType(n);
}
}
}
| |
#if !LOCALTEST
using System.Runtime.CompilerServices;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
namespace System {
public class String : ICloneable, IEnumerable, IEnumerable<char>,
IComparable, IComparable<string>, IEquatable<string> {
public static readonly string Empty = "";
public static bool IsNullOrEmpty(string value) {
return (value == null) || (value.length == 0);
}
// This field must be the only field, to tie up with C code
private int length;
//public int Length{get{return length;}}
[MethodImpl(MethodImplOptions.InternalCall)]
extern public String(char c, int count);
[MethodImpl(MethodImplOptions.InternalCall)]
extern public String(char[] chars);
[MethodImpl(MethodImplOptions.InternalCall)]
extern public String(char[] chars, int startIndex, int length);
#region Private Internal Calls
[MethodImpl(MethodImplOptions.InternalCall)]
extern private String(string str, int startIndex, int length);
[MethodImpl(MethodImplOptions.InternalCall)]
extern private static string InternalConcat(string str0, string str1);
[MethodImpl(MethodImplOptions.InternalCall)]
extern private string InternalReplace(string oldValue, string newValue);
// trimType: bit 0 = start; bit 1 = end
[MethodImpl(MethodImplOptions.InternalCall)]
extern private string InternalTrim(char[] trimChars, int trimType);
[MethodImpl(MethodImplOptions.InternalCall)]
extern private int InternalIndexOf(char value, int startIndex, int count, bool forwards);
[MethodImpl(MethodImplOptions.InternalCall)]
extern private int InternalIndexOfAny(char[] anyOf, int startIndex, int count, bool forward);
#endregion
public int Length {
get {
return this.length;
}
}
[IndexerName("Chars")]
extern public char this[int index] {
[MethodImpl(MethodImplOptions.InternalCall)]
get;
}
#region Misc Methods
public static string Join(string separator, string[] value) {
return Join(separator, value, 0, value.Length);
}
//public override int GetHashCode(){
// if(Length==0) return 0;
// return (int)Chars[0] + 13*(int)Chars[Length-1];
//}
public static string Join(string separator, string[] value, int startIndex, int count) {
StringBuilder sb = new StringBuilder();
for (int i = startIndex; i < count; i++) {
sb.Append(value[i]);
sb.Append(separator);
}
return sb.ToString(0, sb.Length - separator.Length);
}
public string[] Split(params char[] separator) {
return this.Split(separator, int.MaxValue);
}
public string[] Split(char[] separator, int count) {
if (count < 0) {
throw new ArgumentException("count");
}
if (count == 0) {
return new string[0];
}
if (separator == null || separator.Length == 0) {
separator = char.WhiteChars;
}
List<string> ret = new List<string>();
int pos = 0;
for (; count > 0; count--) {
int sepPos = this.IndexOfAny(separator, pos);
if (sepPos < 0) {
ret.Add(new string(this, pos, this.length - pos));
break;
}
ret.Add(new string(this, pos, sepPos - pos));
pos = sepPos + 1;
}
return ret.ToArray();
}
public bool StartsWith(string str) {
if(str.length > this.length) return false;
return this.Substring(0, str.length) == str;
}
public bool EndsWith(string str) {
if(str.length > this.length) return false;
return this.Substring(this.length - str.length, str.length) == str;
}
#endregion
#region Concat Methods
public static string Concat(string str0, string str1) {
if (str0 == null) {
return str1 ?? string.Empty;
}
if (str1 == null) {
return str0;
}
return InternalConcat(str0, str1);
}
public static string Concat(string str0, string str1, string str2) {
return Concat(Concat(str0, str1), str2);
}
public static string Concat(string str0, string str1, string str2, string str3) {
return Concat(Concat(str0, str1), Concat(str2, str3));
}
public static string Concat(params string[] values) {
if (values == null) {
throw new ArgumentNullException("args");
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < values.Length; i++) {
sb.Append(values[i]);
}
return sb.ToString();
}
public static string Concat(object obj0) {
return obj0.ToString();
}
public static string Concat(object obj0, object obj1) {
string str0 = (obj0 == null) ? null : obj0.ToString();
string str1 = (obj1 == null) ? null : obj1.ToString();
if (str0 == null) {
return str1 ?? string.Empty;
}
if (str1 == null) {
return str0;
}
return InternalConcat(str0, str1);
}
public static string Concat(object obj0, object obj1, object obj2) {
return Concat(new object[] { obj0, obj1, obj2 });
}
public static string Concat(object obj0, object obj1, object obj2, object obj3) {
return Concat(new object[] { obj0, obj1, obj2, obj3 });
}
public static string Concat(params object[] objs) {
if (objs == null) {
throw new ArgumentNullException("args");
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < objs.Length; i++) {
sb.Append(objs[i]);
}
return sb.ToString();
}
#endregion
#region Trim Methods
public string Trim(params char[] trimChars) {
if (trimChars == null || trimChars.Length == 0) {
trimChars = char.WhiteChars;
}
return InternalTrim(trimChars, 3);
}
public string Trim() {
return InternalTrim(char.WhiteChars, 3);
}
public string TrimStart(params char[] trimChars) {
if (trimChars == null || trimChars.Length == 0) {
trimChars = char.WhiteChars;
}
return InternalTrim(trimChars, 1);
}
public string TrimEnd(params char[] trimChars) {
if (trimChars == null || trimChars.Length == 0) {
trimChars = char.WhiteChars;
}
return InternalTrim(trimChars, 2);
}
#endregion
#region Substring Methods
public string Substring(int startIndex) {
if (startIndex < 0 || startIndex > this.length) {
throw new ArgumentOutOfRangeException();
}
return new string(this, startIndex, this.length - startIndex);
}
public string Substring(int startIndex, int length) {
if (startIndex < 0 || length < 0 || startIndex + length > this.length) {
throw new ArgumentOutOfRangeException();
}
return new string(this, startIndex, length);
}
#endregion
#region Format Methods
public static string Format(string format, object obj0) {
return Format(null, format, new object[] { obj0 });
}
public static string Format(string format, object obj0, object obj1) {
return Format(null, format, new object[] { obj0, obj1 });
}
public static string Format(string format, object obj0, object obj1, object obj2) {
return Format(null, format, new object[] { obj0, obj1, obj2 });
}
public static string Format(string format, params object[] args) {
return Format(null, format, args);
}
public static string Format(IFormatProvider provider, string format, params object[] args) {
StringBuilder sb = new StringBuilder();
StringHelper.FormatHelper(sb, provider, format, args);
return sb.ToString();
}
#endregion
#region Replace & Remove Methods
public string Replace(char oldChar, char newChar) {
StringBuilder sb = new StringBuilder(this);
return sb.Replace(oldChar, newChar).ToString();
}
public string Replace(string oldValue, string newValue) {
if (oldValue == null) {
throw new ArgumentNullException("oldValue");
}
if (oldValue.Length == 0) {
throw new ArgumentException("oldValue is an empty string.");
}
if (this.length == 0) {
return this;
}
if (newValue == null) {
newValue = string.Empty;
}
return InternalReplace(oldValue, newValue);
}
public string Remove(int startIndex) {
if (startIndex < 0 || startIndex >= this.length) {
throw new ArgumentOutOfRangeException("startIndex");
}
return new string(this, 0, startIndex);
}
public string Remove(int startIndex, int count) {
if (startIndex < 0 || count < 0 || startIndex + count >= this.length) {
throw new ArgumentOutOfRangeException();
}
int pos2 = startIndex+count;
return (new string(this, 0, startIndex)) + (new string(this, pos2, this.length - pos2));
}
#endregion
#region Compare and CompareOrdinal Methods
public static int Compare(string strA, string strB) {
return CompareOrdinal(strA, strB);
}
public static int Compare(string strA, string strB, bool IgnoreCase) {
if(IgnoreCase)
{//HACK: Horribly inefficient.
strA = strA.ToLower();
strB = strB.ToLower();
}
return CompareOrdinal(strA, strB);
}
public static int Compare(string strA, string strB, StringComparison type) {
return Compare(strA, 0, strB, 0, Math.Max(strA.Length,strB.Length), type);
}
public static int Compare(string strA, int indexA, string strB, int indexB, int length) {
return CompareOrdinal(strA.Substring(indexA, length), strB.Substring(indexB, length));
}
public static int CompareOrdinal(string strA, string strB) {
if (strA == null) {
if (strB == null) {
return 0;
}
return -1;
}
if (strB == null) {
return 1;
}
int top = Math.Min(strA.Length, strB.Length);
for (int i = 0; i < top; i++) {
if (strA[i] != strB[i]) {
return (strA[i] - strB[i]);
}
}
return strA.Length - strB.Length;
}
public static int CompareOrdinal (String strA, int indexA, String strB, int indexB, int length)
{
if ((indexA > strA.Length) || (indexB > strB.Length) || (indexA < 0) || (indexB < 0) || (length < 0))
throw new ArgumentOutOfRangeException ();
return CompareOrdinalUnchecked (strA, indexA, length, strB, indexB, length);
}
public static int CompareOrdinalCaseInsensitive (String strA, int indexA, String strB, int indexB, int length)
{
//HACK:Horribly inefficient
strA = strA.ToLower();
strB = strB.ToLower();
return CompareOrdinal (strA, indexA, strB, indexB, length);
}
public static int Compare (string strA, int indexA, string strB, int indexB, int length, StringComparison comparisonType)
{
switch (comparisonType) {
case StringComparison.CurrentCulture:
case StringComparison.InvariantCulture:
case StringComparison.Ordinal:
return CompareOrdinal (strA, indexA, strB, indexB, length);
case StringComparison.CurrentCultureIgnoreCase:
case StringComparison.InvariantCultureIgnoreCase:
case StringComparison.OrdinalIgnoreCase:
return CompareOrdinalCaseInsensitive (strA, indexA, strB, indexB, length);
default:
string msg = String.Format ("Invalid value '{0}' for StringComparison", comparisonType);
throw new ArgumentException (msg, "comparisonType");
}
}
internal static /*unsafe*/ int CompareOrdinalUnchecked (String strA, int indexA, int lenA, String strB, int indexB, int lenB)
{
if (strA == null) {
if (strB == null)
return 0;
else
return -1;
} else if (strB == null) {
return 1;
}
int lengthA = Math.Min (lenA, strA.Length - indexA);
int lengthB = Math.Min (lenB, strB.Length - indexB);
if (lengthA == lengthB && Object.ReferenceEquals (strA, strB))
return 0;
//fixed (char* aptr = strA, bptr = strB) {
int ap = 0/*aptr*/ + indexA;
int end = ap + Math.Min (lengthA, lengthB);
int bp = 0/*bptr*/ + indexB;
while (ap < end) {
if (strA[ap] != strB[bp])
return strA[ap] - strB[bp];
ap++;
bp++;
}
return lengthA - lengthB;
//}
}
#endregion
#region IndexOf... Methods
public int IndexOf(string value) {
return IndexOf(value, 0, this.length);
}
public int IndexOf(string value, int startIndex) {
return IndexOf(value, startIndex, this.length - startIndex);
}
public int IndexOf(string value, int startIndex, int count) {
if (value == null) {
throw new ArgumentNullException("value");
}
if (startIndex < 0 || count < 0 || startIndex + count > this.length) {
throw new ArgumentOutOfRangeException();
}
if (value.length == 0) {
return startIndex;
}
int valueLen = value.length;
int finalIndex = startIndex + count - valueLen + 1;
char char0 = value[0];
for (int i = startIndex; i < finalIndex; i++) {
if (this[i] == char0) {
bool ok = true;
for (int j = 1; j < valueLen; j++) {
if (this[i + j] != value[j]) {
ok = false;
break;
}
}
if (ok) {
return i;
}
}
}
return -1;
}
public int IndexOf(char value) {
return this.IndexOf(value, 0, this.length, true);
}
public int IndexOf(char value, int startIndex) {
return this.IndexOf(value, startIndex, this.length - startIndex, true);
}
public int IndexOf(char value, int startIndex, int count) {
return this.IndexOf(value, startIndex, count, true);
}
public int LastIndexOf(char value) {
return this.IndexOf(value, 0, this.length, false);
}
public int LastIndexOf(char value, int startIndex) {
return this.IndexOf(value, startIndex, this.length - startIndex, false);
}
public int LastIndexOf(char value, int startIndex, int count) {
return this.IndexOf(value, startIndex, count, false);
}
private int IndexOf(char value, int startIndex, int count, bool forwards) {
if (startIndex < 0 || count < 0 || startIndex + count > this.length) {
throw new ArgumentOutOfRangeException();
}
return this.InternalIndexOf(value, startIndex, count, forwards);
}
public int IndexOfAny(char[] anyOf) {
return this.IndexOfAny(anyOf, 0, this.length, true);
}
public int IndexOfAny(char[] anyOf, int startIndex) {
return this.IndexOfAny(anyOf, startIndex, this.length - startIndex, true);
}
public int IndexOfAny(char[] anyOf, int startIndex, int count) {
return this.IndexOfAny(anyOf, startIndex, count, true);
}
public int LastIndexOfAny(char[] anyOf) {
return this.IndexOfAny(anyOf, 0, this.length, false);
}
public int LastIndexOfAny(char[] anyOf, int startIndex) {
return this.IndexOfAny(anyOf, startIndex, this.length - startIndex, false);
}
public int LastIndexOfAny(char[] anyOf, int startIndex, int count) {
return this.IndexOfAny(anyOf, startIndex, count, false);
}
private int IndexOfAny(char[] anyOf, int startIndex, int count, bool forward) {
if (startIndex < 0 || count < 0 || startIndex + count > this.length) {
throw new ArgumentOutOfRangeException();
}
/*int anyOfLen = anyOf.Length;
int finIndex = (forward) ? (startIndex + count) : (startIndex - 1);
int inc = (forward) ? 1 : -1;
for (int i = (forward) ? startIndex : (startIndex + count - 1); i != finIndex; i += inc) {
char c = this[i];
for (int j = 0; j < anyOfLen; j++) {
if (c == anyOf[j]) {
return i;
}
}
}
return -1;*/
return this.InternalIndexOfAny(anyOf, startIndex, count, forward);
}
#endregion
#region Case methods
public string ToLower() {
return ToLower(CultureInfo.CurrentCulture);
}
public string ToLower(CultureInfo culture) {
if (culture == null) {
throw new ArgumentNullException("culture");
}
if (culture.LCID == 0x007f) {
return ToLowerInvariant();
}
return culture.TextInfo.ToLower(this);
}
public string ToLowerInvariant() {
int len = this.length;
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < len; i++) {
sb.Append(char.ToLowerInvariant(this[i]));
}
return sb.ToString();
}
public string ToUpper() {
return ToLower(CultureInfo.CurrentCulture);
}
public string ToUpper(CultureInfo culture) {
if (culture == null) {
throw new ArgumentNullException("culture");
}
if (culture.LCID == 0x007f) {
return ToUpperInvariant();
}
return culture.TextInfo.ToUpper(this);
}
public string ToUpperInvariant() {
int len = this.length;
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < len; i++) {
sb.Append(char.ToUpperInvariant(this[i]));
}
return sb.ToString();
}
#endregion
#region Overrides and Operators
public override string ToString() {
return this;
}
public override bool Equals(object obj) {
return Equals(this, obj as string);
}
public static bool operator ==(string a, string b) {
return Equals(a, b);
}
public static bool operator !=(string a, string b) {
return !Equals(a, b);
}
[MethodImpl(MethodImplOptions.InternalCall)]
extern public static bool Equals(string a, string b);
[MethodImpl(MethodImplOptions.InternalCall)]
extern public override int GetHashCode();
#endregion
#region IClonable Members
public object Clone() {
return this;
}
#endregion
#region IComparable Members
public int CompareTo(object value) {
if (value == null) {
return 1;
}
if (!(value is string)) {
throw new ArgumentException();
}
return string.Compare(this, (string)value);
}
public int CompareTo(string value) {
if (value == null)
return 1;
return string.Compare(this, value);
}
#endregion
#region IEquatable<string> Members
public bool Equals(string other) {
return Equals(this, other);
}
#endregion
#region IEnumerable Members
public IEnumerator GetEnumerator() {
return new CharEnumerator(this);
}
IEnumerator<char> IEnumerable<char>.GetEnumerator() {
return new CharEnumerator(this);
}
#endregion
public char [] ToCharArray()
{
char[] chars = new char[Length];
for(int i=0;i<Length;i++)
{
chars[i] = this[i];
}
return chars;
}
}
}
#endif
| |
using EncompassRest.Loans.Enums;
using EncompassRest.Schema;
namespace EncompassRest.Loans
{
/// <summary>
/// Hmda
/// </summary>
public sealed partial class Hmda : DirtyExtensibleObject, IIdentifiable
{
private DirtyValue<StringEnumValue<ActionTaken>>? _actionTaken;
private DirtyValue<string?>? _applicationDate;
private DirtyValue<StringEnumValue<AUS>>? _aUS1;
private DirtyValue<StringEnumValue<AUS>>? _aUS2;
private DirtyValue<StringEnumValue<AUS>>? _aUS3;
private DirtyValue<StringEnumValue<AUS>>? _aUS4;
private DirtyValue<StringEnumValue<AUS>>? _aUS5;
private DirtyValue<StringEnumValue<AUSRecommendation>>? _aUSRecommendation1;
private DirtyValue<StringEnumValue<AUSRecommendation>>? _aUSRecommendation2;
private DirtyValue<StringEnumValue<AUSRecommendation>>? _aUSRecommendation3;
private DirtyValue<StringEnumValue<AUSRecommendation>>? _aUSRecommendation4;
private DirtyValue<StringEnumValue<AUSRecommendation>>? _aUSRecommendation5;
private DirtyValue<StringEnumValue<YNOrExempt>>? _balloonIndicator;
private DirtyValue<StringEnumValue<BusinessOrCommercialPurpose>>? _businessOrCommercialPurpose;
private DirtyValue<bool?>? _cDRequired;
private DirtyValue<string?>? _censusTrack;
private DirtyValue<NA<decimal>>? _cLTV;
private DirtyValue<string?>? _contactEmailAddress;
private DirtyValue<string?>? _contactFaxNumber;
private DirtyValue<string?>? _contactName;
private DirtyValue<string?>? _contactOfficeCity;
private DirtyValue<StringEnumValue<State>>? _contactOfficeState;
private DirtyValue<string?>? _contactOfficeStreetAddress;
private DirtyValue<string?>? _contactOfficeZIPCode;
private DirtyValue<string?>? _contactPhoneNumber;
private DirtyValue<string?>? _countyCode;
private DirtyValue<NA<decimal>>? _debtToIncomeRatio;
private DirtyValue<StringEnumValue<DenialReason>>? _denialReason1;
private DirtyValue<StringEnumValue<DenialReason>>? _denialReason2;
private DirtyValue<StringEnumValue<DenialReason>>? _denialReason3;
private DirtyValue<StringEnumValue<DenialReason>>? _denialReason4;
private DirtyValue<NA<decimal>>? _discountPoints;
private DirtyValue<bool?>? _excludeLoanFromHMDAReportIndicator;
private DirtyValue<StringEnumValue<FederalAgency>>? _federalAgency;
private DirtyValue<string?>? _federalTaxpayerIdNumber;
private DirtyValue<string?>? _financialInstitutionName;
private DirtyValue<StringEnumValue<YNOrExempt>>? _hmda2InterestOnlyIndicator;
private DirtyValue<string?>? _hMDACensusTrack;
private DirtyValue<bool?>? _hmdaCltvIndicator;
private DirtyValue<string?>? _hMDACountyCode;
private DirtyValue<bool?>? _hmdaDtiIndicator;
private DirtyValue<bool?>? _hmdaIncomeIndicator;
private DirtyValue<bool?>? _hmdaInterestOnlyIndicator;
private DirtyValue<StringEnumValue<HmdaLoanPurpose>>? _hMDALoanPurpose;
private DirtyValue<string?>? _hMDAProfileApplicationDateValue;
private DirtyValue<string?>? _hMDAProfileCLTVValue;
private DirtyValue<string?>? _hMDAProfileDTIValue;
private DirtyValue<string?>? _hMDAProfileID;
private DirtyValue<string?>? _hMDAProfileIncomeValue;
private DirtyValue<string?>? _hmdaPropertyAddress;
private DirtyValue<string?>? _hmdaPropertyCity;
private DirtyValue<StringEnumValue<State>>? _hmdaPropertyState;
private DirtyValue<bool?>? _hmdaPropertyValueNotReliedUponIndicator;
private DirtyValue<string?>? _hmdaPropertyZipCode;
private DirtyValue<bool?>? _hmdaSyncAddressIndicator;
private DirtyValue<StringEnumValue<HOEPAStatus>>? _hOEPAStatus;
private DirtyValue<string?>? _id;
private DirtyValue<NA<decimal>>? _income;
private DirtyValue<decimal?>? _incomeExcludedFromHmda;
private DirtyValue<StringEnumValue<InitiallyPayableToYourInstitution>>? _initiallyPayableToYourInstitution;
private DirtyValue<NA<decimal>>? _interestRate;
private DirtyValue<string?>? _introRatePeriod;
private DirtyValue<string?>? _legalEntityIdentifier;
private DirtyValue<string?>? _legalEntityIdentifierReporting;
private DirtyValue<StringEnumValue<LegalEntityIdentifierUsed>>? _legalEntityIdentifierUsed;
private DirtyValue<NA<decimal>>? _lenderCredits;
private DirtyValue<StringEnumValue<LienStatus>>? _lienStatus;
private DirtyValue<decimal?>? _loanAmount;
private DirtyValue<StringEnumValue<YNOrExempt>>? _loanBalanceRiseIndicator;
private DirtyValue<StringEnumValue<HmdaLoanPurpose>>? _loanPurpose;
private DirtyValue<string?>? _loanTerm;
private DirtyValue<StringEnumValue<HmdaLoanType>>? _loanType;
private DirtyValue<StringEnumValue<ManufacturedHomeLandPropertyInterest>>? _manufacturedHomeLandPropertyInterest;
private DirtyValue<StringEnumValue<ManufacturedSecuredProperyType>>? _manufacturedSecuredProperyType;
private DirtyValue<string?>? _mSANumber;
private DirtyValue<string?>? _multifamilyNoUnits;
private DirtyValue<string?>? _nMLSLoanOriginatorID;
private DirtyValue<StringEnumValue<OpenEndLineOfCredit>>? _openEndLineOfCredit;
private DirtyValue<string?>? _originationCharges;
private DirtyValue<string?>? _otherAUS;
private DirtyValue<string?>? _otherAUSRecommendations;
private DirtyValue<string?>? _otherDenialReason;
private DirtyValue<StringEnumValue<OtherNonAmortization>>? _otherNonAmortization;
private DirtyValue<string?>? _parentAddress;
private DirtyValue<string?>? _parentCity;
private DirtyValue<string?>? _parentName;
private DirtyValue<StringEnumValue<State>>? _parentState;
private DirtyValue<string?>? _parentZip;
private DirtyValue<bool?>? _partiallyExemptLoanIndicator;
private DirtyValue<StringEnumValue<Preapprovals>>? _preapprovals;
private DirtyValue<string?>? _prepaymentPenaltyPeriod;
private DirtyValue<StringEnumValue<HmdaPropertyType>>? _propertyType;
private DirtyValue<NA<decimal>>? _propertyValue;
private DirtyValue<StringEnumValue<QMStatus>>? _qMStatus;
private DirtyValue<NA<decimal>>? _rateSpread;
private DirtyValue<int?>? _reportingYear;
private DirtyValue<bool?>? _reportPurposeOfLoanIndicator;
private DirtyValue<string?>? _repurchasedActionDate;
private DirtyValue<StringEnumValue<ActionTaken>>? _repurchasedActionTaken;
private DirtyValue<decimal?>? _repurchasedLoanAmount;
private DirtyValue<int?>? _repurchasedReportingYear;
private DirtyValue<StringEnumValue<TypeOfPurchaser>>? _repurchasedTypeOfPurchaser;
private DirtyValue<string?>? _respondentID;
private DirtyValue<StringEnumValue<ReverseMortgage>>? _reverseMortgage;
private DirtyValue<string?>? _stateCode;
private DirtyValue<StringEnumValue<SubmissionOfApplication>>? _submissionOfApplication;
private DirtyValue<string?>? _totalLoanCosts;
private DirtyValue<string?>? _totalPointsAndFees;
private DirtyValue<StringEnumValue<TypeOfPurchaser>>? _typeOfPurchaser;
private DirtyValue<string?>? _universalLoanId;
/// <summary>
/// Trans Details Current Loan Status [1393]
/// </summary>
public StringEnumValue<ActionTaken> ActionTaken { get => _actionTaken; set => SetField(ref _actionTaken, value); }
/// <summary>
/// Application Date [HMDA.X29]
/// </summary>
public string? ApplicationDate { get => _applicationDate; set => SetField(ref _applicationDate, value); }
/// <summary>
/// AUS #1 [HMDA.X44]
/// </summary>
public StringEnumValue<AUS> AUS1 { get => _aUS1; set => SetField(ref _aUS1, value); }
/// <summary>
/// AUS #2 [HMDA.X45]
/// </summary>
[LoanFieldProperty(MissingOptionsJson = "[\"Not applicable\",\"Exempt\"]")]
public StringEnumValue<AUS> AUS2 { get => _aUS2; set => SetField(ref _aUS2, value); }
/// <summary>
/// AUS #3 [HMDA.X46]
/// </summary>
[LoanFieldProperty(MissingOptionsJson = "[\"Not applicable\",\"Exempt\"]")]
public StringEnumValue<AUS> AUS3 { get => _aUS3; set => SetField(ref _aUS3, value); }
/// <summary>
/// AUS #4 [HMDA.X47]
/// </summary>
[LoanFieldProperty(MissingOptionsJson = "[\"Not applicable\",\"Exempt\"]")]
public StringEnumValue<AUS> AUS4 { get => _aUS4; set => SetField(ref _aUS4, value); }
/// <summary>
/// AUS #5 [HMDA.X48]
/// </summary>
[LoanFieldProperty(MissingOptionsJson = "[\"Not applicable\",\"Exempt\"]")]
public StringEnumValue<AUS> AUS5 { get => _aUS5; set => SetField(ref _aUS5, value); }
/// <summary>
/// AUS Recommendation #1 [HMDA.X50]
/// </summary>
public StringEnumValue<AUSRecommendation> AUSRecommendation1 { get => _aUSRecommendation1; set => SetField(ref _aUSRecommendation1, value); }
/// <summary>
/// AUS Recommendation #2 [HMDA.X51]
/// </summary>
[LoanFieldProperty(MissingOptionsJson = "[\"Not applicable\",\"Exempt\"]")]
public StringEnumValue<AUSRecommendation> AUSRecommendation2 { get => _aUSRecommendation2; set => SetField(ref _aUSRecommendation2, value); }
/// <summary>
/// AUS Recommendation #3 [HMDA.X52]
/// </summary>
[LoanFieldProperty(MissingOptionsJson = "[\"Not applicable\",\"Exempt\"]")]
public StringEnumValue<AUSRecommendation> AUSRecommendation3 { get => _aUSRecommendation3; set => SetField(ref _aUSRecommendation3, value); }
/// <summary>
/// AUS Recommendation #4 [HMDA.X53]
/// </summary>
[LoanFieldProperty(MissingOptionsJson = "[\"Not applicable\",\"Exempt\"]")]
public StringEnumValue<AUSRecommendation> AUSRecommendation4 { get => _aUSRecommendation4; set => SetField(ref _aUSRecommendation4, value); }
/// <summary>
/// AUS Recommendation #5 [HMDA.X54]
/// </summary>
[LoanFieldProperty(MissingOptionsJson = "[\"Not applicable\",\"Exempt\"]")]
public StringEnumValue<AUSRecommendation> AUSRecommendation5 { get => _aUSRecommendation5; set => SetField(ref _aUSRecommendation5, value); }
/// <summary>
/// Trans Details Amort Type Balloon [HMDA.X114]
/// </summary>
public StringEnumValue<YNOrExempt> BalloonIndicator { get => _balloonIndicator; set => SetField(ref _balloonIndicator, value); }
/// <summary>
/// Business or Commercial Purpose [HMDA.X58]
/// </summary>
public StringEnumValue<BusinessOrCommercialPurpose> BusinessOrCommercialPurpose { get => _businessOrCommercialPurpose; set => SetField(ref _businessOrCommercialPurpose, value); }
/// <summary>
/// CD Required [HMDA.X121]
/// </summary>
public bool? CDRequired { get => _cDRequired; set => SetField(ref _cDRequired, value); }
/// <summary>
/// Subject Property Census Tract [700]
/// </summary>
public string? CensusTrack { get => _censusTrack; set => SetField(ref _censusTrack, value); }
/// <summary>
/// CLTV [HMDA.X37]
/// </summary>
public NA<decimal> CLTV { get => _cLTV; set => SetField(ref _cLTV, value); }
/// <summary>
/// HMDA Contact Person Email [HMDA.X62]
/// </summary>
public string? ContactEmailAddress { get => _contactEmailAddress; set => SetField(ref _contactEmailAddress, value); }
/// <summary>
/// HMDA Contact Person Fax # [HMDA.X67]
/// </summary>
public string? ContactFaxNumber { get => _contactFaxNumber; set => SetField(ref _contactFaxNumber, value); }
/// <summary>
/// HMDA Contact Person Name [HMDA.X60]
/// </summary>
public string? ContactName { get => _contactName; set => SetField(ref _contactName, value); }
/// <summary>
/// HMDA Contact Person City [HMDA.X64]
/// </summary>
public string? ContactOfficeCity { get => _contactOfficeCity; set => SetField(ref _contactOfficeCity, value); }
/// <summary>
/// HMDA Contact Person State [HMDA.X65]
/// </summary>
public StringEnumValue<State> ContactOfficeState { get => _contactOfficeState; set => SetField(ref _contactOfficeState, value); }
/// <summary>
/// HMDA Contact Person Street Address [HMDA.X63]
/// </summary>
public string? ContactOfficeStreetAddress { get => _contactOfficeStreetAddress; set => SetField(ref _contactOfficeStreetAddress, value); }
/// <summary>
/// HMDA Contact Person ZIP [HMDA.X66]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.ZIPCODE)]
public string? ContactOfficeZIPCode { get => _contactOfficeZIPCode; set => SetField(ref _contactOfficeZIPCode, value); }
/// <summary>
/// HMDA Contact Person Phone # [HMDA.X61]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.PHONE)]
public string? ContactPhoneNumber { get => _contactPhoneNumber; set => SetField(ref _contactPhoneNumber, value); }
/// <summary>
/// Subject Property County Code [1396]
/// </summary>
public string? CountyCode { get => _countyCode; set => SetField(ref _countyCode, value); }
/// <summary>
/// Debt to Income Ratio [HMDA.X36]
/// </summary>
public NA<decimal> DebtToIncomeRatio { get => _debtToIncomeRatio; set => SetField(ref _debtToIncomeRatio, value); }
/// <summary>
/// Denial Reason 1 [HMDA.X21]
/// </summary>
public StringEnumValue<DenialReason> DenialReason1 { get => _denialReason1; set => SetField(ref _denialReason1, value); }
/// <summary>
/// Denial Reason 2 [HMDA.X22]
/// </summary>
[LoanFieldProperty(MissingOptionsJson = "[\"Not applicable\",\"Exempt\"]")]
public StringEnumValue<DenialReason> DenialReason2 { get => _denialReason2; set => SetField(ref _denialReason2, value); }
/// <summary>
/// Denial Reason 3 [HMDA.X23]
/// </summary>
[LoanFieldProperty(MissingOptionsJson = "[\"Not applicable\",\"Exempt\"]")]
public StringEnumValue<DenialReason> DenialReason3 { get => _denialReason3; set => SetField(ref _denialReason3, value); }
/// <summary>
/// Denial Reason 4 [HMDA.X33]
/// </summary>
[LoanFieldProperty(MissingOptionsJson = "[\"Not applicable\",\"Exempt\"]")]
public StringEnumValue<DenialReason> DenialReason4 { get => _denialReason4; set => SetField(ref _denialReason4, value); }
/// <summary>
/// Discount Points [HMDA.X35]
/// </summary>
public NA<decimal> DiscountPoints { get => _discountPoints; set => SetField(ref _discountPoints, value); }
/// <summary>
/// Subject Property Exclude from HMDA Report [HMDA.X24]
/// </summary>
[LoanFieldProperty(OptionsJson = "{\"Y\":\"Exclude loan from HMDA report\"}")]
public bool? ExcludeLoanFromHMDAReportIndicator { get => _excludeLoanFromHMDAReportIndicator; set => SetField(ref _excludeLoanFromHMDAReportIndicator, value); }
/// <summary>
/// HMDA Federal Agency [HMDA.X68]
/// </summary>
public StringEnumValue<FederalAgency> FederalAgency { get => _federalAgency; set => SetField(ref _federalAgency, value); }
/// <summary>
/// HMDA Fedral Tax ID [HMDA.X69]
/// </summary>
public string? FederalTaxpayerIdNumber { get => _federalTaxpayerIdNumber; set => SetField(ref _federalTaxpayerIdNumber, value); }
/// <summary>
/// HMDA Company Name [HMDA.X59]
/// </summary>
public string? FinancialInstitutionName { get => _financialInstitutionName; set => SetField(ref _financialInstitutionName, value); }
/// <summary>
/// Trans Details Interest Only Indicator [HMDA.X120]
/// </summary>
public StringEnumValue<YNOrExempt> Hmda2InterestOnlyIndicator { get => _hmda2InterestOnlyIndicator; set => SetField(ref _hmda2InterestOnlyIndicator, value); }
/// <summary>
/// CFPB HMDA Census Tract [HMDA.X112]
/// </summary>
public string? HMDACensusTrack { get => _hMDACensusTrack; set => SetField(ref _hMDACensusTrack, value); }
/// <summary>
/// HMDA CLTV [HMDA.X98]
/// </summary>
[LoanFieldProperty(OptionsJson = "{\"Y\":\"HMDA CLTV\"}")]
public bool? HmdaCltvIndicator { get => _hmdaCltvIndicator; set => SetField(ref _hmdaCltvIndicator, value); }
/// <summary>
/// CFPB HMDA County Code [HMDA.X111]
/// </summary>
public string? HMDACountyCode { get => _hMDACountyCode; set => SetField(ref _hMDACountyCode, value); }
/// <summary>
/// HMDA DTI [HMDA.X97]
/// </summary>
[LoanFieldProperty(OptionsJson = "{\"Y\":\"HMDA DTI\"}")]
public bool? HmdaDtiIndicator { get => _hmdaDtiIndicator; set => SetField(ref _hmdaDtiIndicator, value); }
/// <summary>
/// HMDA Income [HMDA.X99]
/// </summary>
[LoanFieldProperty(OptionsJson = "{\"Y\":\"HMDA Income\"}")]
public bool? HmdaIncomeIndicator { get => _hmdaIncomeIndicator; set => SetField(ref _hmdaIncomeIndicator, value); }
/// <summary>
/// Trans Details Interest Only Indicator [HMDA.X109]
/// </summary>
public bool? HmdaInterestOnlyIndicator { get => _hmdaInterestOnlyIndicator; set => SetField(ref _hmdaInterestOnlyIndicator, value); }
/// <summary>
/// HMDA Loan Purpose [HMDA.X107]
/// </summary>
[LoanFieldProperty(OptionsJson = "{\"Home Purchase\":\"1. Home purchase\",\"Home Improvement\":\"2. Home improvement\",\"Cash-out refinancing\":\"32. Cash-out refinancing (consumer only)\",\"Other purpose\":\"4. Other purpose (consumer only)\"}")]
public StringEnumValue<HmdaLoanPurpose> HMDALoanPurpose { get => _hMDALoanPurpose; set => SetField(ref _hMDALoanPurpose, value); }
/// <summary>
/// HMDA Profile - Application Date value from Setting [HMDA.X104]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? HMDAProfileApplicationDateValue { get => _hMDAProfileApplicationDateValue; set => SetField(ref _hMDAProfileApplicationDateValue, value); }
/// <summary>
/// HMDA Profile - CLTV value from Setting [HMDA.X102]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? HMDAProfileCLTVValue { get => _hMDAProfileCLTVValue; set => SetField(ref _hMDAProfileCLTVValue, value); }
/// <summary>
/// HMDA Profile - DTI value from Setting [HMDA.X101]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? HMDAProfileDTIValue { get => _hMDAProfileDTIValue; set => SetField(ref _hMDAProfileDTIValue, value); }
/// <summary>
/// HMDA Profile ID [HMDA.X100]
/// </summary>
public string? HMDAProfileID { get => _hMDAProfileID; set => SetField(ref _hMDAProfileID, value); }
/// <summary>
/// HMDA Profile - Income value from Setting [HMDA.X103]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? HMDAProfileIncomeValue { get => _hMDAProfileIncomeValue; set => SetField(ref _hMDAProfileIncomeValue, value); }
/// <summary>
/// HMDA Property Address [HMDA.X88]
/// </summary>
public string? HmdaPropertyAddress { get => _hmdaPropertyAddress; set => SetField(ref _hmdaPropertyAddress, value); }
/// <summary>
/// HMDA Property City [HMDA.X89]
/// </summary>
public string? HmdaPropertyCity { get => _hmdaPropertyCity; set => SetField(ref _hmdaPropertyCity, value); }
/// <summary>
/// HMDA Property State [HMDA.X90]
/// </summary>
public StringEnumValue<State> HmdaPropertyState { get => _hmdaPropertyState; set => SetField(ref _hmdaPropertyState, value); }
/// <summary>
/// Property Value Not Relied Upon [HMDA.X108]
/// </summary>
[LoanFieldProperty(OptionsJson = "{\"Y\":\"Property Value Not Relied Upon\"}")]
public bool? HmdaPropertyValueNotReliedUponIndicator { get => _hmdaPropertyValueNotReliedUponIndicator; set => SetField(ref _hmdaPropertyValueNotReliedUponIndicator, value); }
/// <summary>
/// HMDA Property Zip Code [HMDA.X87]
/// </summary>
public string? HmdaPropertyZipCode { get => _hmdaPropertyZipCode; set => SetField(ref _hmdaPropertyZipCode, value); }
/// <summary>
/// HMDA Sync address fields with subject property address [HMDA.X91]
/// </summary>
[LoanFieldProperty(OptionsJson = "{\"Y\":\"HMDA Sync Address Indicator\"}")]
public bool? HmdaSyncAddressIndicator { get => _hmdaSyncAddressIndicator; set => SetField(ref _hmdaSyncAddressIndicator, value); }
/// <summary>
/// Trans Details HOEPA Status [HMDA.X13]
/// </summary>
public StringEnumValue<HOEPAStatus> HOEPAStatus { get => _hOEPAStatus; set => SetField(ref _hOEPAStatus, value); }
/// <summary>
/// Hmda Id
/// </summary>
public string? Id { get => _id; set => SetField(ref _id, value); }
/// <summary>
/// HMDA Income [HMDA.X32]
/// </summary>
public NA<decimal> Income { get => _income; set => SetField(ref _income, value); }
/// <summary>
/// Income Excluded From HMDA [HMDA.X110]
/// </summary>
public decimal? IncomeExcludedFromHmda { get => _incomeExcludedFromHmda; set => SetField(ref _incomeExcludedFromHmda, value); }
/// <summary>
/// Initially Payable to Your Institution [HMDA.X43]
/// </summary>
public StringEnumValue<InitiallyPayableToYourInstitution> InitiallyPayableToYourInstitution { get => _initiallyPayableToYourInstitution; set => SetField(ref _initiallyPayableToYourInstitution, value); }
/// <summary>
/// Interest Rate [HMDA.X81]
/// </summary>
public NA<decimal> InterestRate { get => _interestRate; set => SetField(ref _interestRate, value); }
/// <summary>
/// Intro Rate Period [HMDA.X84]
/// </summary>
public string? IntroRatePeriod { get => _introRatePeriod; set => SetField(ref _introRatePeriod, value); }
/// <summary>
/// HMDA LEI [HMDA.X70]
/// </summary>
public string? LegalEntityIdentifier { get => _legalEntityIdentifier; set => SetField(ref _legalEntityIdentifier, value); }
/// <summary>
/// HMDA LEI Reporting [HMDA.X106]
/// </summary>
public string? LegalEntityIdentifierReporting { get => _legalEntityIdentifierReporting; set => SetField(ref _legalEntityIdentifierReporting, value); }
/// <summary>
/// HMDA LEI Used [HMDA.X105]
/// </summary>
public StringEnumValue<LegalEntityIdentifierUsed> LegalEntityIdentifierUsed { get => _legalEntityIdentifierUsed; set => SetField(ref _legalEntityIdentifierUsed, value); }
/// <summary>
/// Lender Credits [HMDA.X80]
/// </summary>
public NA<decimal> LenderCredits { get => _lenderCredits; set => SetField(ref _lenderCredits, value); }
/// <summary>
/// Trans Details Lien Status [HMDA.X14]
/// </summary>
public StringEnumValue<LienStatus> LienStatus { get => _lienStatus; set => SetField(ref _lienStatus, value); }
/// <summary>
/// HMDA Loan Amount [HMDA.X31]
/// </summary>
public decimal? LoanAmount { get => _loanAmount; set => SetField(ref _loanAmount, value); }
/// <summary>
/// Can Your Loan Balance Rise [HMDA.X115]
/// </summary>
public StringEnumValue<YNOrExempt> LoanBalanceRiseIndicator { get => _loanBalanceRiseIndicator; set => SetField(ref _loanBalanceRiseIndicator, value); }
/// <summary>
/// Trans Details Loan Purpose [384]
/// </summary>
public StringEnumValue<HmdaLoanPurpose> LoanPurpose { get => _loanPurpose; set => SetField(ref _loanPurpose, value); }
/// <summary>
/// Loan Term [HMDA.X83]
/// </summary>
public string? LoanTerm { get => _loanTerm; set => SetField(ref _loanTerm, value); }
/// <summary>
/// HMDA Loan Type [HMDA.X30]
/// </summary>
public StringEnumValue<HmdaLoanType> LoanType { get => _loanType; set => SetField(ref _loanType, value); }
/// <summary>
/// Manufactured Home Land Property Interest [HMDA.X40]
/// </summary>
public StringEnumValue<ManufacturedHomeLandPropertyInterest> ManufacturedHomeLandPropertyInterest { get => _manufacturedHomeLandPropertyInterest; set => SetField(ref _manufacturedHomeLandPropertyInterest, value); }
/// <summary>
/// Manufactured Secured Property Type [HMDA.X39]
/// </summary>
public StringEnumValue<ManufacturedSecuredProperyType> ManufacturedSecuredProperyType { get => _manufacturedSecuredProperyType; set => SetField(ref _manufacturedSecuredProperyType, value); }
/// <summary>
/// Subject Property MSA # [699]
/// </summary>
public string? MSANumber { get => _mSANumber; set => SetField(ref _mSANumber, value); }
/// <summary>
/// Multifamily No Units [HMDA.X41]
/// </summary>
public string? MultifamilyNoUnits { get => _multifamilyNoUnits; set => SetField(ref _multifamilyNoUnits, value); }
/// <summary>
/// NMLS Loan Originator ID [HMDA.X86]
/// </summary>
public string? NMLSLoanOriginatorID { get => _nMLSLoanOriginatorID; set => SetField(ref _nMLSLoanOriginatorID, value); }
/// <summary>
/// Open-End Line of Credit [HMDA.X57]
/// </summary>
public StringEnumValue<OpenEndLineOfCredit> OpenEndLineOfCredit { get => _openEndLineOfCredit; set => SetField(ref _openEndLineOfCredit, value); }
/// <summary>
/// Origination Charges [HMDA.X79]
/// </summary>
public string? OriginationCharges { get => _originationCharges; set => SetField(ref _originationCharges, value); }
/// <summary>
/// Other AUX(s) [HMDA.X49]
/// </summary>
public string? OtherAUS { get => _otherAUS; set => SetField(ref _otherAUS, value); }
/// <summary>
/// Other AUS Recommendation(s) [HMDA.X55]
/// </summary>
public string? OtherAUSRecommendations { get => _otherAUSRecommendations; set => SetField(ref _otherAUSRecommendations, value); }
/// <summary>
/// Other Denial Reason [HMDA.X34]
/// </summary>
public string? OtherDenialReason { get => _otherDenialReason; set => SetField(ref _otherDenialReason, value); }
/// <summary>
/// Other Non-Amortization [HMDA.X38]
/// </summary>
public StringEnumValue<OtherNonAmortization> OtherNonAmortization { get => _otherNonAmortization; set => SetField(ref _otherNonAmortization, value); }
/// <summary>
/// HMDA Parent Address [HMDA.X73]
/// </summary>
public string? ParentAddress { get => _parentAddress; set => SetField(ref _parentAddress, value); }
/// <summary>
/// HMDA Parent City [HMDA.X74]
/// </summary>
public string? ParentCity { get => _parentCity; set => SetField(ref _parentCity, value); }
/// <summary>
/// HMDA Parent Contact Name [HMDA.X72]
/// </summary>
public string? ParentName { get => _parentName; set => SetField(ref _parentName, value); }
/// <summary>
/// HMDA Parent State [HMDA.X75]
/// </summary>
public StringEnumValue<State> ParentState { get => _parentState; set => SetField(ref _parentState, value); }
/// <summary>
/// HMDA Parent Zipcode [HMDA.X76]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.ZIPCODE)]
public string? ParentZip { get => _parentZip; set => SetField(ref _parentZip, value); }
/// <summary>
/// Report loan as Partially Exempt [HMDA.X113]
/// </summary>
[LoanFieldProperty(OptionsJson = "{\"Y\":\"Loan is Partially Exempt\"}")]
public bool? PartiallyExemptLoanIndicator { get => _partiallyExemptLoanIndicator; set => SetField(ref _partiallyExemptLoanIndicator, value); }
/// <summary>
/// Trans Details Preapprovals [HMDA.X12]
/// </summary>
public StringEnumValue<Preapprovals> Preapprovals { get => _preapprovals; set => SetField(ref _preapprovals, value); }
/// <summary>
/// Prepayment Penalty Period [HMDA.X82]
/// </summary>
public string? PrepaymentPenaltyPeriod { get => _prepaymentPenaltyPeriod; set => SetField(ref _prepaymentPenaltyPeriod, value); }
/// <summary>
/// Subject Property Type [HMDA.X11]
/// </summary>
public StringEnumValue<HmdaPropertyType> PropertyType { get => _propertyType; set => SetField(ref _propertyType, value); }
/// <summary>
/// Property Value [HMDA.X85]
/// </summary>
public NA<decimal> PropertyValue { get => _propertyValue; set => SetField(ref _propertyValue, value); }
/// <summary>
/// QM Status [HMDA.X26]
/// </summary>
public StringEnumValue<QMStatus> QMStatus { get => _qMStatus; set => SetField(ref _qMStatus, value); }
/// <summary>
/// Trans Details Rate Spread [HMDA.X15]
/// </summary>
public NA<decimal> RateSpread { get => _rateSpread; set => SetField(ref _rateSpread, value); }
/// <summary>
/// HMDA Reporting Year [HMDA.X27]
/// </summary>
public int? ReportingYear { get => _reportingYear; set => SetField(ref _reportingYear, value); }
/// <summary>
/// Loan Purpose is Home Improvement [HMDA.X25]
/// </summary>
[LoanFieldProperty(OptionsJson = "{\"Y\":\"Report the purpose of this loan as Home Improvement (one to four family)\"}")]
public bool? ReportPurposeOfLoanIndicator { get => _reportPurposeOfLoanIndicator; set => SetField(ref _reportPurposeOfLoanIndicator, value); }
/// <summary>
/// Repurchased Action Date [HMDA.X96]
/// </summary>
public string? RepurchasedActionDate { get => _repurchasedActionDate; set => SetField(ref _repurchasedActionDate, value); }
/// <summary>
/// HMDA Repurchased Trans Details Current Loan Status [HMDA.X95]
/// </summary>
public StringEnumValue<ActionTaken> RepurchasedActionTaken { get => _repurchasedActionTaken; set => SetField(ref _repurchasedActionTaken, value); }
/// <summary>
/// HMDA Repurchased Loan Amount [HMDA.X93]
/// </summary>
public decimal? RepurchasedLoanAmount { get => _repurchasedLoanAmount; set => SetField(ref _repurchasedLoanAmount, value); }
/// <summary>
/// HMDA Repurchased Reporting Year [HMDA.X92]
/// </summary>
public int? RepurchasedReportingYear { get => _repurchasedReportingYear; set => SetField(ref _repurchasedReportingYear, value); }
/// <summary>
/// HMDA Repurchased Trans Details Purchaser Type [HMDA.X94]
/// </summary>
public StringEnumValue<TypeOfPurchaser> RepurchasedTypeOfPurchaser { get => _repurchasedTypeOfPurchaser; set => SetField(ref _repurchasedTypeOfPurchaser, value); }
/// <summary>
/// HMDA Respondent ID [HMDA.X71]
/// </summary>
public string? RespondentID { get => _respondentID; set => SetField(ref _respondentID, value); }
/// <summary>
/// Reverse Mortgage [HMDA.X56]
/// </summary>
public StringEnumValue<ReverseMortgage> ReverseMortgage { get => _reverseMortgage; set => SetField(ref _reverseMortgage, value); }
/// <summary>
/// Subject Property State Code [1395]
/// </summary>
public string? StateCode { get => _stateCode; set => SetField(ref _stateCode, value); }
/// <summary>
/// Submission of Application [HMDA.X42]
/// </summary>
public StringEnumValue<SubmissionOfApplication> SubmissionOfApplication { get => _submissionOfApplication; set => SetField(ref _submissionOfApplication, value); }
/// <summary>
/// Total Loan Costs [HMDA.X77]
/// </summary>
public string? TotalLoanCosts { get => _totalLoanCosts; set => SetField(ref _totalLoanCosts, value); }
/// <summary>
/// Total Points and Fees [HMDA.X78]
/// </summary>
public string? TotalPointsAndFees { get => _totalPointsAndFees; set => SetField(ref _totalPointsAndFees, value); }
/// <summary>
/// Trans Details Purchaser Type [1397]
/// </summary>
public StringEnumValue<TypeOfPurchaser> TypeOfPurchaser { get => _typeOfPurchaser; set => SetField(ref _typeOfPurchaser, value); }
/// <summary>
/// Universal Loan Id [HMDA.X28]
/// </summary>
public string? UniversalLoanId { get => _universalLoanId; set => SetField(ref _universalLoanId, 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.
using System.ServiceModel.Channels;
using System.IdentityModel.Tokens;
using System.IdentityModel.Selectors;
using System.Runtime.Serialization;
using System.Xml;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Globalization;
using System.ServiceModel.Dispatcher;
using System.Security.Authentication.ExtendedProtection;
namespace System.ServiceModel.Security
{
internal class RequestSecurityToken : BodyWriter
{
private string _context;
private string _tokenType;
private string _requestType;
private BinaryNegotiation _negotiationData;
private XmlElement _rstXml;
private IList<XmlElement> _requestProperties;
private ArraySegment<byte> _cachedWriteBuffer;
private int _cachedWriteBufferLength;
private int _keySize;
private Message _message;
private SecurityKeyIdentifierClause _renewTarget;
private SecurityKeyIdentifierClause _closeTarget;
private OnGetBinaryNegotiationCallback _onGetBinaryNegotiation;
private SecurityStandardsManager _standardsManager;
private bool _isReceiver;
private bool _isReadOnly;
private object _appliesTo;
private DataContractSerializer _appliesToSerializer;
private Type _appliesToType;
private object _thisLock = new Object();
public RequestSecurityToken()
: this(SecurityStandardsManager.DefaultInstance)
{
}
public RequestSecurityToken(MessageSecurityVersion messageSecurityVersion, SecurityTokenSerializer securityTokenSerializer)
: this(SecurityUtils.CreateSecurityStandardsManager(messageSecurityVersion, securityTokenSerializer))
{
}
public RequestSecurityToken(MessageSecurityVersion messageSecurityVersion,
SecurityTokenSerializer securityTokenSerializer,
XmlElement requestSecurityTokenXml,
string context,
string tokenType,
string requestType,
int keySize,
SecurityKeyIdentifierClause renewTarget,
SecurityKeyIdentifierClause closeTarget)
: this(SecurityUtils.CreateSecurityStandardsManager(messageSecurityVersion, securityTokenSerializer),
requestSecurityTokenXml,
context,
tokenType,
requestType,
keySize,
renewTarget,
closeTarget)
{
}
public RequestSecurityToken(XmlElement requestSecurityTokenXml,
string context,
string tokenType,
string requestType,
int keySize,
SecurityKeyIdentifierClause renewTarget,
SecurityKeyIdentifierClause closeTarget)
: this(SecurityStandardsManager.DefaultInstance,
requestSecurityTokenXml,
context,
tokenType,
requestType,
keySize,
renewTarget,
closeTarget)
{
}
internal RequestSecurityToken(SecurityStandardsManager standardsManager,
XmlElement rstXml,
string context,
string tokenType,
string requestType,
int keySize,
SecurityKeyIdentifierClause renewTarget,
SecurityKeyIdentifierClause closeTarget)
: base(true)
{
if (standardsManager == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("standardsManager"));
}
_standardsManager = standardsManager;
if (rstXml == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("rstXml");
_rstXml = rstXml;
_context = context;
_tokenType = tokenType;
_keySize = keySize;
_requestType = requestType;
_renewTarget = renewTarget;
_closeTarget = closeTarget;
_isReceiver = true;
_isReadOnly = true;
}
internal RequestSecurityToken(SecurityStandardsManager standardsManager)
: this(standardsManager, true)
{
// no op
}
internal RequestSecurityToken(SecurityStandardsManager standardsManager, bool isBuffered)
: base(isBuffered)
{
if (standardsManager == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("standardsManager"));
}
_standardsManager = standardsManager;
_requestType = _standardsManager.TrustDriver.RequestTypeIssue;
_requestProperties = null;
_isReceiver = false;
_isReadOnly = false;
}
public ChannelBinding GetChannelBinding()
{
if (_message == null)
{
return null;
}
ChannelBindingMessageProperty channelBindingMessageProperty = null;
ChannelBindingMessageProperty.TryGet(_message, out channelBindingMessageProperty);
ChannelBinding channelBinding = null;
if (channelBindingMessageProperty != null)
{
channelBinding = channelBindingMessageProperty.ChannelBinding;
}
return channelBinding;
}
/// <summary>
/// Will hold a reference to the outbound message from which we will fish the ChannelBinding out of.
/// </summary>
public Message Message
{
get { return _message; }
set { _message = value; }
}
public string Context
{
get
{
return _context;
}
set
{
if (this.IsReadOnly)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.ObjectIsReadOnly));
_context = value;
}
}
public string TokenType
{
get
{
return _tokenType;
}
set
{
if (this.IsReadOnly)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.ObjectIsReadOnly));
_tokenType = value;
}
}
public int KeySize
{
get
{
return _keySize;
}
set
{
if (this.IsReadOnly)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.ObjectIsReadOnly));
if (value < 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", SR.ValueMustBeNonNegative));
_keySize = value;
}
}
public bool IsReadOnly
{
get
{
return _isReadOnly;
}
}
public delegate void OnGetBinaryNegotiationCallback(ChannelBinding channelBinding);
public OnGetBinaryNegotiationCallback OnGetBinaryNegotiation
{
get
{
return _onGetBinaryNegotiation;
}
set
{
if (this.IsReadOnly)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.ObjectIsReadOnly));
}
_onGetBinaryNegotiation = value;
}
}
public IEnumerable<XmlElement> RequestProperties
{
get
{
if (_isReceiver)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.ItemNotAvailableInDeserializedRST, "RequestProperties")));
}
return _requestProperties;
}
set
{
if (this.IsReadOnly)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.ObjectIsReadOnly));
if (value != null)
{
int index = 0;
Collection<XmlElement> coll = new Collection<XmlElement>();
foreach (XmlElement property in value)
{
if (property == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(String.Format(CultureInfo.InvariantCulture, "value[{0}]", index)));
coll.Add(property);
++index;
}
_requestProperties = coll;
}
else
{
_requestProperties = null;
}
}
}
public string RequestType
{
get
{
return _requestType;
}
set
{
if (this.IsReadOnly)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.ObjectIsReadOnly));
if (value == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value");
_requestType = value;
}
}
public SecurityKeyIdentifierClause RenewTarget
{
get
{
return _renewTarget;
}
set
{
if (this.IsReadOnly)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.ObjectIsReadOnly));
_renewTarget = value;
}
}
public SecurityKeyIdentifierClause CloseTarget
{
get
{
return _closeTarget;
}
set
{
if (this.IsReadOnly)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.ObjectIsReadOnly));
_closeTarget = value;
}
}
public XmlElement RequestSecurityTokenXml
{
get
{
if (!_isReceiver)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.ItemAvailableInDeserializedRSTOnly, "RequestSecurityTokenXml")));
}
return _rstXml;
}
}
internal SecurityStandardsManager StandardsManager
{
get
{
return _standardsManager;
}
set
{
if (this.IsReadOnly)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.ObjectIsReadOnly));
if (value == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("value"));
}
_standardsManager = value;
}
}
internal bool IsReceiver
{
get
{
return _isReceiver;
}
}
internal object AppliesTo
{
get
{
if (_isReceiver)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.ItemNotAvailableInDeserializedRST, "AppliesTo")));
}
return _appliesTo;
}
}
internal DataContractSerializer AppliesToSerializer
{
get
{
if (_isReceiver)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.ItemNotAvailableInDeserializedRST, "AppliesToSerializer")));
}
return _appliesToSerializer;
}
}
internal Type AppliesToType
{
get
{
if (_isReceiver)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.ItemNotAvailableInDeserializedRST, "AppliesToType")));
}
return _appliesToType;
}
}
protected Object ThisLock
{
get
{
return _thisLock;
}
}
internal void SetBinaryNegotiation(BinaryNegotiation negotiation)
{
if (negotiation == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("negotiation");
if (this.IsReadOnly)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.ObjectIsReadOnly));
_negotiationData = negotiation;
}
internal BinaryNegotiation GetBinaryNegotiation()
{
if (_isReceiver)
{
return _standardsManager.TrustDriver.GetBinaryNegotiation(this);
}
else if (_negotiationData == null && _onGetBinaryNegotiation != null)
{
_onGetBinaryNegotiation(this.GetChannelBinding());
}
return _negotiationData;
}
public SecurityToken GetRequestorEntropy()
{
return this.GetRequestorEntropy(null);
}
internal SecurityToken GetRequestorEntropy(SecurityTokenResolver resolver)
{
if (_isReceiver)
{
return _standardsManager.TrustDriver.GetEntropy(this, resolver);
}
else
return null;
}
public void SetAppliesTo<T>(T appliesTo, DataContractSerializer serializer)
{
if (this.IsReadOnly)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.ObjectIsReadOnly));
if (appliesTo != null && serializer == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("serializer");
}
_appliesTo = appliesTo;
_appliesToSerializer = serializer;
_appliesToType = typeof(T);
}
public void GetAppliesToQName(out string localName, out string namespaceUri)
{
if (!_isReceiver)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.ItemAvailableInDeserializedRSTOnly, "MatchesAppliesTo")));
_standardsManager.TrustDriver.GetAppliesToQName(this, out localName, out namespaceUri);
}
public T GetAppliesTo<T>()
{
return this.GetAppliesTo<T>(DataContractSerializerDefaults.CreateSerializer(typeof(T), DataContractSerializerDefaults.MaxItemsInObjectGraph));
}
public T GetAppliesTo<T>(XmlObjectSerializer serializer)
{
if (_isReceiver)
{
if (serializer == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("serializer");
}
return _standardsManager.TrustDriver.GetAppliesTo<T>(this, serializer);
}
else
{
return (T)_appliesTo;
}
}
private void OnWriteTo(XmlWriter writer)
{
if (_isReceiver)
{
_rstXml.WriteTo(writer);
}
else
{
_standardsManager.TrustDriver.WriteRequestSecurityToken(this, writer);
}
}
public void WriteTo(XmlWriter writer)
{
if (writer == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
if (this.IsReadOnly)
{
// cache the serialized bytes to ensure repeatability
if (_cachedWriteBuffer.Array == null)
{
MemoryStream stream = new MemoryStream();
using (XmlDictionaryWriter binaryWriter = XmlDictionaryWriter.CreateBinaryWriter(stream, XD.Dictionary))
{
this.OnWriteTo(binaryWriter);
binaryWriter.Flush();
stream.Flush();
stream.Seek(0, SeekOrigin.Begin);
bool gotBuffer = stream.TryGetBuffer(out _cachedWriteBuffer);
if (!gotBuffer)
{
throw new UnauthorizedAccessException(SR.UnauthorizedAccess_MemStreamBuffer);
}
_cachedWriteBufferLength = (int)stream.Length;
}
}
writer.WriteNode(XmlDictionaryReader.CreateBinaryReader(_cachedWriteBuffer.Array, 0, _cachedWriteBufferLength, XD.Dictionary, XmlDictionaryReaderQuotas.Max), false);
}
else
this.OnWriteTo(writer);
}
public static RequestSecurityToken CreateFrom(XmlReader reader)
{
return CreateFrom(SecurityStandardsManager.DefaultInstance, reader);
}
public static RequestSecurityToken CreateFrom(XmlReader reader, MessageSecurityVersion messageSecurityVersion, SecurityTokenSerializer securityTokenSerializer)
{
return CreateFrom(SecurityUtils.CreateSecurityStandardsManager(messageSecurityVersion, securityTokenSerializer), reader);
}
internal static RequestSecurityToken CreateFrom(SecurityStandardsManager standardsManager, XmlReader reader)
{
return standardsManager.TrustDriver.CreateRequestSecurityToken(reader);
}
public void MakeReadOnly()
{
if (!_isReadOnly)
{
_isReadOnly = true;
if (_requestProperties != null)
{
_requestProperties = new ReadOnlyCollection<XmlElement>(_requestProperties);
}
this.OnMakeReadOnly();
}
}
internal protected virtual void OnWriteCustomAttributes(XmlWriter writer) { }
internal protected virtual void OnWriteCustomElements(XmlWriter writer) { }
internal protected virtual void OnMakeReadOnly() { }
protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
{
WriteTo(writer);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using Internal.TypeSystem;
using Internal.Runtime;
using Debug = System.Diagnostics.Debug;
namespace ILCompiler.DependencyAnalysis
{
public struct ObjectDataBuilder : Internal.Runtime.ITargetBinaryWriter
{
public ObjectDataBuilder(NodeFactory factory, bool relocsOnly)
{
_target = factory.Target;
_data = new ArrayBuilder<byte>();
_relocs = new ArrayBuilder<Relocation>();
Alignment = 1;
_definedSymbols = new ArrayBuilder<ISymbolDefinitionNode>();
#if DEBUG
_numReservations = 0;
_checkAllSymbolDependenciesMustBeMarked = !relocsOnly;
#endif
}
private TargetDetails _target;
private ArrayBuilder<Relocation> _relocs;
private ArrayBuilder<byte> _data;
public int Alignment { get; private set; }
private ArrayBuilder<ISymbolDefinitionNode> _definedSymbols;
#if DEBUG
private int _numReservations;
private bool _checkAllSymbolDependenciesMustBeMarked;
#endif
public int CountBytes
{
get
{
return _data.Count;
}
}
public int TargetPointerSize
{
get
{
return _target.PointerSize;
}
}
/// <summary>
/// Raise the alignment requirement of this object to <paramref name="align"/>. This has no effect
/// if the alignment requirement is already larger than <paramref name="align"/>.
/// </summary>
public void RequireInitialAlignment(int align)
{
Alignment = Math.Max(align, Alignment);
}
/// <summary>
/// Raise the alignment requirement of this object to the target pointer size. This has no effect
/// if the alignment requirement is already larger than a pointer size.
/// </summary>
public void RequireInitialPointerAlignment()
{
RequireInitialAlignment(_target.PointerSize);
}
public void EmitByte(byte emit)
{
_data.Add(emit);
}
public void EmitShort(short emit)
{
EmitByte((byte)(emit & 0xFF));
EmitByte((byte)((emit >> 8) & 0xFF));
}
public void EmitInt(int emit)
{
EmitByte((byte)(emit & 0xFF));
EmitByte((byte)((emit >> 8) & 0xFF));
EmitByte((byte)((emit >> 16) & 0xFF));
EmitByte((byte)((emit >> 24) & 0xFF));
}
public void EmitUInt(uint emit)
{
EmitByte((byte)(emit & 0xFF));
EmitByte((byte)((emit >> 8) & 0xFF));
EmitByte((byte)((emit >> 16) & 0xFF));
EmitByte((byte)((emit >> 24) & 0xFF));
}
public void EmitLong(long emit)
{
EmitByte((byte)(emit & 0xFF));
EmitByte((byte)((emit >> 8) & 0xFF));
EmitByte((byte)((emit >> 16) & 0xFF));
EmitByte((byte)((emit >> 24) & 0xFF));
EmitByte((byte)((emit >> 32) & 0xFF));
EmitByte((byte)((emit >> 40) & 0xFF));
EmitByte((byte)((emit >> 48) & 0xFF));
EmitByte((byte)((emit >> 56) & 0xFF));
}
public void EmitNaturalInt(int emit)
{
if (_target.PointerSize == 8)
{
EmitLong(emit);
}
else
{
Debug.Assert(_target.PointerSize == 4);
EmitInt(emit);
}
}
public void EmitHalfNaturalInt(short emit)
{
if (_target.PointerSize == 8)
{
EmitInt(emit);
}
else
{
Debug.Assert(_target.PointerSize == 4);
EmitShort(emit);
}
}
public void EmitCompressedUInt(uint emit)
{
if (emit < 128)
{
EmitByte((byte)(emit * 2 + 0));
}
else if (emit < 128 * 128)
{
EmitByte((byte)(emit * 4 + 1));
EmitByte((byte)(emit >> 6));
}
else if (emit < 128 * 128 * 128)
{
EmitByte((byte)(emit * 8 + 3));
EmitByte((byte)(emit >> 5));
EmitByte((byte)(emit >> 13));
}
else if (emit < 128 * 128 * 128 * 128)
{
EmitByte((byte)(emit * 16 + 7));
EmitByte((byte)(emit >> 4));
EmitByte((byte)(emit >> 12));
EmitByte((byte)(emit >> 20));
}
else
{
EmitByte((byte)15);
EmitInt((int)emit);
}
}
public void EmitBytes(byte[] bytes)
{
_data.Append(bytes);
}
public void EmitBytes(byte[] bytes, int offset, int length)
{
_data.Append(bytes, offset, length);
}
internal void EmitBytes(ArrayBuilder<byte> bytes)
{
_data.Append(bytes);
}
public void EmitZeroPointer()
{
_data.ZeroExtend(_target.PointerSize);
}
public void EmitZeros(int numBytes)
{
_data.ZeroExtend(numBytes);
}
private Reservation GetReservationTicket(int size)
{
#if DEBUG
_numReservations++;
#endif
Reservation ticket = (Reservation)_data.Count;
_data.ZeroExtend(size);
return ticket;
}
private int ReturnReservationTicket(Reservation reservation)
{
#if DEBUG
Debug.Assert(_numReservations > 0);
_numReservations--;
#endif
return (int)reservation;
}
public Reservation ReserveByte()
{
return GetReservationTicket(1);
}
public void EmitByte(Reservation reservation, byte emit)
{
int offset = ReturnReservationTicket(reservation);
_data[offset] = emit;
}
public Reservation ReserveShort()
{
return GetReservationTicket(2);
}
public void EmitShort(Reservation reservation, short emit)
{
int offset = ReturnReservationTicket(reservation);
_data[offset] = (byte)(emit & 0xFF);
_data[offset + 1] = (byte)((emit >> 8) & 0xFF);
}
public Reservation ReserveInt()
{
return GetReservationTicket(4);
}
public void EmitInt(Reservation reservation, int emit)
{
int offset = ReturnReservationTicket(reservation);
_data[offset] = (byte)(emit & 0xFF);
_data[offset + 1] = (byte)((emit >> 8) & 0xFF);
_data[offset + 2] = (byte)((emit >> 16) & 0xFF);
_data[offset + 3] = (byte)((emit >> 24) & 0xFF);
}
public void EmitReloc(ISymbolNode symbol, RelocType relocType, int delta = 0)
{
#if DEBUG
if (_checkAllSymbolDependenciesMustBeMarked)
{
var node = symbol as ILCompiler.DependencyAnalysisFramework.DependencyNodeCore<NodeFactory>;
if (node != null)
Debug.Assert(node.Marked);
}
#endif
_relocs.Add(new Relocation(relocType, _data.Count, symbol));
// And add space for the reloc
switch (relocType)
{
case RelocType.IMAGE_REL_BASED_REL32:
case RelocType.IMAGE_REL_BASED_RELPTR32:
case RelocType.IMAGE_REL_BASED_ABSOLUTE:
case RelocType.IMAGE_REL_BASED_HIGHLOW:
case RelocType.IMAGE_REL_SECREL:
case RelocType.IMAGE_REL_BASED_ADDR32NB:
EmitInt(delta);
break;
case RelocType.IMAGE_REL_BASED_DIR64:
EmitLong(delta);
break;
case RelocType.IMAGE_REL_BASED_THUMB_BRANCH24:
case RelocType.IMAGE_REL_BASED_ARM64_BRANCH26:
case RelocType.IMAGE_REL_BASED_THUMB_MOV32:
// Do not vacate space for this kind of relocation, because
// the space is embedded in the instruction.
break;
default:
throw new NotImplementedException();
}
}
public void EmitPointerReloc(ISymbolNode symbol, int delta = 0)
{
EmitReloc(symbol, (_target.PointerSize == 8) ? RelocType.IMAGE_REL_BASED_DIR64 : RelocType.IMAGE_REL_BASED_HIGHLOW, delta);
}
/// <summary>
/// Use this api to generate a reloc to a symbol that may be an indirection cell or not as a pointer
/// </summary>
/// <param name="symbol">symbol to reference</param>
/// <param name="indirectionBit">value to OR in to the reloc to represent to runtime code that this pointer is an indirection. Defaults to IndirectionConstants.IndirectionCellPointer</param>
/// <param name="delta">Delta from symbol start for value</param>
public void EmitPointerRelocOrIndirectionReference(ISymbolNode symbol, int indirectionBit = IndirectionConstants.IndirectionCellPointer, int delta = 0)
{
if (symbol.RepresentsIndirectionCell)
delta |= indirectionBit;
EmitReloc(symbol, (_target.PointerSize == 8) ? RelocType.IMAGE_REL_BASED_DIR64 : RelocType.IMAGE_REL_BASED_HIGHLOW, delta);
}
public ObjectNode.ObjectData ToObjectData()
{
#if DEBUG
Debug.Assert(_numReservations == 0);
#endif
ObjectNode.ObjectData returnData = new ObjectNode.ObjectData(_data.ToArray(),
_relocs.ToArray(),
Alignment,
_definedSymbols.ToArray());
return returnData;
}
public enum Reservation { }
public void AddSymbol(ISymbolDefinitionNode node)
{
_definedSymbols.Add(node);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Globalization
{
public abstract class EastAsianLunisolarCalendar : Calendar
{
internal const int LeapMonth = 0;
internal const int Jan1Month = 1;
internal const int Jan1Date = 2;
internal const int nDaysPerMonth = 3;
// # of days so far in the solar year
internal static readonly int[] DaysToMonth365 =
{
0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
};
internal static readonly int[] DaysToMonth366 =
{
0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335
};
internal const int DatePartYear = 0;
internal const int DatePartDayOfYear = 1;
internal const int DatePartMonth = 2;
internal const int DatePartDay = 3;
public override CalendarAlgorithmType AlgorithmType
{
get
{
return CalendarAlgorithmType.LunisolarCalendar;
}
}
// Return the year number in the 60-year cycle.
//
public virtual int GetSexagenaryYear(DateTime time)
{
CheckTicksRange(time.Ticks);
int year = 0, month = 0, day = 0;
TimeToLunar(time, ref year, ref month, ref day);
return ((year - 4) % 60) + 1;
}
// Return the celestial year from the 60-year cycle.
// The returned value is from 1 ~ 10.
//
public int GetCelestialStem(int sexagenaryYear)
{
if ((sexagenaryYear < 1) || (sexagenaryYear > 60))
{
throw new ArgumentOutOfRangeException(
nameof(sexagenaryYear),
SR.Format(SR.ArgumentOutOfRange_Range, 1, 60));
}
return ((sexagenaryYear - 1) % 10) + 1;
}
// Return the Terrestial Branch from the 60-year cycle.
// The returned value is from 1 ~ 12.
//
public int GetTerrestrialBranch(int sexagenaryYear)
{
if ((sexagenaryYear < 1) || (sexagenaryYear > 60))
{
throw new ArgumentOutOfRangeException(
nameof(sexagenaryYear),
SR.Format(SR.ArgumentOutOfRange_Range, 1, 60));
}
return ((sexagenaryYear - 1) % 12) + 1;
}
internal abstract int GetYearInfo(int LunarYear, int Index);
internal abstract int GetYear(int year, DateTime time);
internal abstract int GetGregorianYear(int year, int era);
internal abstract int MinCalendarYear { get; }
internal abstract int MaxCalendarYear { get; }
internal abstract EraInfo[] CalEraInfo { get; }
internal abstract DateTime MinDate { get; }
internal abstract DateTime MaxDate { get; }
internal const int MaxCalendarMonth = 13;
internal const int MaxCalendarDay = 30;
internal int MinEraCalendarYear(int era)
{
EraInfo[] mEraInfo = CalEraInfo;
//ChineseLunisolarCalendar does not has m_EraInfo it is going to retuen null
if (mEraInfo == null)
{
return MinCalendarYear;
}
if (era == Calendar.CurrentEra)
{
era = CurrentEraValue;
}
//era has to be in the supported range otherwise we will throw exception in CheckEraRange()
if (era == GetEra(MinDate))
{
return (GetYear(MinCalendarYear, MinDate));
}
for (int i = 0; i < mEraInfo.Length; i++)
{
if (era == mEraInfo[i].era)
{
return (mEraInfo[i].minEraYear);
}
}
throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue);
}
internal int MaxEraCalendarYear(int era)
{
EraInfo[] mEraInfo = CalEraInfo;
//ChineseLunisolarCalendar does not has m_EraInfo it is going to retuen null
if (mEraInfo == null)
{
return MaxCalendarYear;
}
if (era == Calendar.CurrentEra)
{
era = CurrentEraValue;
}
//era has to be in the supported range otherwise we will throw exception in CheckEraRange()
if (era == GetEra(MaxDate))
{
return (GetYear(MaxCalendarYear, MaxDate));
}
for (int i = 0; i < mEraInfo.Length; i++)
{
if (era == mEraInfo[i].era)
{
return (mEraInfo[i].maxEraYear);
}
}
throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue);
}
internal EastAsianLunisolarCalendar()
{
}
internal void CheckTicksRange(long ticks)
{
if (ticks < MinSupportedDateTime.Ticks || ticks > MaxSupportedDateTime.Ticks)
{
throw new ArgumentOutOfRangeException(
"time",
string.Format(CultureInfo.InvariantCulture, SR.ArgumentOutOfRange_CalendarRange,
MinSupportedDateTime, MaxSupportedDateTime));
}
}
internal void CheckEraRange(int era)
{
if (era == Calendar.CurrentEra)
{
era = CurrentEraValue;
}
if ((era < GetEra(MinDate)) || (era > GetEra(MaxDate)))
{
throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue);
}
}
internal int CheckYearRange(int year, int era)
{
CheckEraRange(era);
year = GetGregorianYear(year, era);
if ((year < MinCalendarYear) || (year > MaxCalendarYear))
{
throw new ArgumentOutOfRangeException(
nameof(year),
SR.Format(SR.ArgumentOutOfRange_Range, MinEraCalendarYear(era), MaxEraCalendarYear(era)));
}
return year;
}
internal int CheckYearMonthRange(int year, int month, int era)
{
year = CheckYearRange(year, era);
if (month == 13)
{
//Reject if there is no leap month this year
if (GetYearInfo(year, LeapMonth) == 0)
throw new ArgumentOutOfRangeException(nameof(month), SR.ArgumentOutOfRange_Month);
}
if (month < 1 || month > 13)
{
throw new ArgumentOutOfRangeException(nameof(month), SR.ArgumentOutOfRange_Month);
}
return year;
}
internal int InternalGetDaysInMonth(int year, int month)
{
int nDays;
int mask; // mask for extracting bits
mask = 0x8000;
// convert the lunar day into a lunar month/date
mask >>= (month - 1);
if ((GetYearInfo(year, nDaysPerMonth) & mask) == 0)
nDays = 29;
else
nDays = 30;
return nDays;
}
// Returns the number of days in the month given by the year and
// month arguments.
//
public override int GetDaysInMonth(int year, int month, int era)
{
year = CheckYearMonthRange(year, month, era);
return InternalGetDaysInMonth(year, month);
}
private static int GregorianIsLeapYear(int y)
{
return ((((y) % 4) != 0) ? 0 : ((((y) % 100) != 0) ? 1 : ((((y) % 400) != 0) ? 0 : 1)));
}
// Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid.
//
public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era)
{
year = CheckYearMonthRange(year, month, era);
int daysInMonth = InternalGetDaysInMonth(year, month);
if (day < 1 || day > daysInMonth)
{
throw new ArgumentOutOfRangeException(
nameof(day),
SR.Format(SR.ArgumentOutOfRange_Day, daysInMonth, month));
}
int gy = 0; int gm = 0; int gd = 0;
if (LunarToGregorian(year, month, day, ref gy, ref gm, ref gd))
{
return new DateTime(gy, gm, gd, hour, minute, second, millisecond);
}
else
{
throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadYearMonthDay);
}
}
//
// GregorianToLunar calculates lunar calendar info for the given gregorian year, month, date.
// The input date should be validated before calling this method.
//
internal void GregorianToLunar(int nSYear, int nSMonth, int nSDate, ref int nLYear, ref int nLMonth, ref int nLDate)
{
// unsigned int nLYear, nLMonth, nLDate; // lunar ymd
int nSolarDay; // day # in solar year
int nLunarDay; // day # in lunar year
int fLeap; // is it a solar leap year?
int LDpM; // lunar days/month bitfield
int mask; // mask for extracting bits
int nDays; // # days this lunar month
int nJan1Month, nJan1Date;
// calc the solar day of year
fLeap = GregorianIsLeapYear(nSYear);
nSolarDay = (fLeap == 1) ? DaysToMonth366[nSMonth - 1] : DaysToMonth365[nSMonth - 1];
nSolarDay += nSDate;
// init lunar year info
nLunarDay = nSolarDay;
nLYear = nSYear;
if (nLYear == (MaxCalendarYear + 1))
{
nLYear--;
nLunarDay += ((GregorianIsLeapYear(nLYear) == 1) ? 366 : 365);
nJan1Month = GetYearInfo(nLYear, Jan1Month);
nJan1Date = GetYearInfo(nLYear, Jan1Date);
}
else
{
nJan1Month = GetYearInfo(nLYear, Jan1Month);
nJan1Date = GetYearInfo(nLYear, Jan1Date);
// check if this solar date is actually part of the previous
// lunar year
if ((nSMonth < nJan1Month) ||
(nSMonth == nJan1Month && nSDate < nJan1Date))
{
// the corresponding lunar day is actually part of the previous
// lunar year
nLYear--;
// add a solar year to the lunar day #
nLunarDay += ((GregorianIsLeapYear(nLYear) == 1) ? 366 : 365);
// update the new start of year
nJan1Month = GetYearInfo(nLYear, Jan1Month);
nJan1Date = GetYearInfo(nLYear, Jan1Date);
}
}
// convert solar day into lunar day.
// subtract off the beginning part of the solar year which is not
// part of the lunar year. since this part is always in Jan or Feb,
// we don't need to handle Leap Year (LY only affects March
// and later).
nLunarDay -= DaysToMonth365[nJan1Month - 1];
nLunarDay -= (nJan1Date - 1);
// convert the lunar day into a lunar month/date
mask = 0x8000;
LDpM = GetYearInfo(nLYear, nDaysPerMonth);
nDays = ((LDpM & mask) != 0) ? 30 : 29;
nLMonth = 1;
while (nLunarDay > nDays)
{
nLunarDay -= nDays;
nLMonth++;
mask >>= 1;
nDays = ((LDpM & mask) != 0) ? 30 : 29;
}
nLDate = nLunarDay;
}
/*
//Convert from Lunar to Gregorian
//Highly inefficient, but it works based on the forward conversion
*/
internal bool LunarToGregorian(int nLYear, int nLMonth, int nLDate, ref int nSolarYear, ref int nSolarMonth, ref int nSolarDay)
{
int numLunarDays;
if (nLDate < 1 || nLDate > 30)
return false;
numLunarDays = nLDate - 1;
//Add previous months days to form the total num of days from the first of the month.
for (int i = 1; i < nLMonth; i++)
{
numLunarDays += InternalGetDaysInMonth(nLYear, i);
}
//Get Gregorian First of year
int nJan1Month = GetYearInfo(nLYear, Jan1Month);
int nJan1Date = GetYearInfo(nLYear, Jan1Date);
// calc the solar day of year of 1 Lunar day
int fLeap = GregorianIsLeapYear(nLYear);
int[] days = (fLeap == 1) ? DaysToMonth366 : DaysToMonth365;
nSolarDay = nJan1Date;
if (nJan1Month > 1)
nSolarDay += days[nJan1Month - 1];
// Add the actual lunar day to get the solar day we want
nSolarDay = nSolarDay + numLunarDays;// - 1;
if (nSolarDay > (fLeap + 365))
{
nSolarYear = nLYear + 1;
nSolarDay -= (fLeap + 365);
}
else
{
nSolarYear = nLYear;
}
for (nSolarMonth = 1; nSolarMonth < 12; nSolarMonth++)
{
if (days[nSolarMonth] >= nSolarDay)
break;
}
nSolarDay -= days[nSolarMonth - 1];
return true;
}
internal DateTime LunarToTime(DateTime time, int year, int month, int day)
{
int gy = 0; int gm = 0; int gd = 0;
LunarToGregorian(year, month, day, ref gy, ref gm, ref gd);
return (GregorianCalendar.GetDefaultInstance().ToDateTime(gy, gm, gd, time.Hour, time.Minute, time.Second, time.Millisecond));
}
internal void TimeToLunar(DateTime time, ref int year, ref int month, ref int day)
{
int gy = 0; int gm = 0; int gd = 0;
Calendar Greg = GregorianCalendar.GetDefaultInstance();
gy = Greg.GetYear(time);
gm = Greg.GetMonth(time);
gd = Greg.GetDayOfMonth(time);
GregorianToLunar(gy, gm, gd, ref year, ref month, ref day);
}
// Returns the DateTime resulting from adding the given number of
// months to the specified DateTime. The result is computed by incrementing
// (or decrementing) the year and month parts of the specified DateTime by
// value months, and, if required, adjusting the day part of the
// resulting date downwards to the last day of the resulting month in the
// resulting year. The time-of-day part of the result is the same as the
// time-of-day part of the specified DateTime.
//
public override DateTime AddMonths(DateTime time, int months)
{
if (months < -120000 || months > 120000)
{
throw new ArgumentOutOfRangeException(
nameof(months),
SR.Format(SR.ArgumentOutOfRange_Range, -120000, 120000));
}
CheckTicksRange(time.Ticks);
int y = 0; int m = 0; int d = 0;
TimeToLunar(time, ref y, ref m, ref d);
int i = m + months;
if (i > 0)
{
int monthsInYear = InternalIsLeapYear(y) ? 13 : 12;
while (i - monthsInYear > 0)
{
i -= monthsInYear;
y++;
monthsInYear = InternalIsLeapYear(y) ? 13 : 12;
}
m = i;
}
else
{
int monthsInYear;
while (i <= 0)
{
monthsInYear = InternalIsLeapYear(y - 1) ? 13 : 12;
i += monthsInYear;
y--;
}
m = i;
}
int days = InternalGetDaysInMonth(y, m);
if (d > days)
{
d = days;
}
DateTime dt = LunarToTime(time, y, m, d);
CheckAddResult(dt.Ticks, MinSupportedDateTime, MaxSupportedDateTime);
return (dt);
}
public override DateTime AddYears(DateTime time, int years)
{
CheckTicksRange(time.Ticks);
int y = 0; int m = 0; int d = 0;
TimeToLunar(time, ref y, ref m, ref d);
y += years;
if (m == 13 && !InternalIsLeapYear(y))
{
m = 12;
d = InternalGetDaysInMonth(y, m);
}
int DaysInMonths = InternalGetDaysInMonth(y, m);
if (d > DaysInMonths)
{
d = DaysInMonths;
}
DateTime dt = LunarToTime(time, y, m, d);
CheckAddResult(dt.Ticks, MinSupportedDateTime, MaxSupportedDateTime);
return (dt);
}
// Returns the day-of-year part of the specified DateTime. The returned value
// is an integer between 1 and [354|355 |383|384].
//
public override int GetDayOfYear(DateTime time)
{
CheckTicksRange(time.Ticks);
int y = 0; int m = 0; int d = 0;
TimeToLunar(time, ref y, ref m, ref d);
for (int i = 1; i < m; i++)
{
d = d + InternalGetDaysInMonth(y, i);
}
return d;
}
// Returns the day-of-month part of the specified DateTime. The returned
// value is an integer between 1 and 29 or 30.
//
public override int GetDayOfMonth(DateTime time)
{
CheckTicksRange(time.Ticks);
int y = 0; int m = 0; int d = 0;
TimeToLunar(time, ref y, ref m, ref d);
return d;
}
// Returns the number of days in the year given by the year argument for the current era.
//
public override int GetDaysInYear(int year, int era)
{
year = CheckYearRange(year, era);
int Days = 0;
int monthsInYear = InternalIsLeapYear(year) ? 13 : 12;
while (monthsInYear != 0)
Days += InternalGetDaysInMonth(year, monthsInYear--);
return Days;
}
// Returns the month part of the specified DateTime. The returned value is an
// integer between 1 and 13.
//
public override int GetMonth(DateTime time)
{
CheckTicksRange(time.Ticks);
int y = 0; int m = 0; int d = 0;
TimeToLunar(time, ref y, ref m, ref d);
return m;
}
// Returns the year part of the specified DateTime. The returned value is an
// integer between 1 and MaxCalendarYear.
//
public override int GetYear(DateTime time)
{
CheckTicksRange(time.Ticks);
int y = 0; int m = 0; int d = 0;
TimeToLunar(time, ref y, ref m, ref d);
return GetYear(y, time);
}
// Returns the day-of-week part of the specified DateTime. The returned value
// is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates
// Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates
// Thursday, 5 indicates Friday, and 6 indicates Saturday.
//
public override DayOfWeek GetDayOfWeek(DateTime time)
{
CheckTicksRange(time.Ticks);
return ((DayOfWeek)((int)(time.Ticks / Calendar.TicksPerDay + 1) % 7));
}
// Returns the number of months in the specified year and era.
public override int GetMonthsInYear(int year, int era)
{
year = CheckYearRange(year, era);
return (InternalIsLeapYear(year) ? 13 : 12);
}
// Checks whether a given day in the specified era is a leap day. This method returns true if
// the date is a leap day, or false if not.
//
public override bool IsLeapDay(int year, int month, int day, int era)
{
year = CheckYearMonthRange(year, month, era);
int daysInMonth = InternalGetDaysInMonth(year, month);
if (day < 1 || day > daysInMonth)
{
throw new ArgumentOutOfRangeException(
nameof(day),
SR.Format(SR.ArgumentOutOfRange_Day, daysInMonth, month));
}
int m = GetYearInfo(year, LeapMonth);
return ((m != 0) && (month == (m + 1)));
}
// Checks whether a given month in the specified era is a leap month. This method returns true if
// month is a leap month, or false if not.
//
public override bool IsLeapMonth(int year, int month, int era)
{
year = CheckYearMonthRange(year, month, era);
int m = GetYearInfo(year, LeapMonth);
return ((m != 0) && (month == (m + 1)));
}
// Returns the leap month in a calendar year of the specified era. This method returns 0
// if this this year is not a leap year.
//
public override int GetLeapMonth(int year, int era)
{
year = CheckYearRange(year, era);
int month = GetYearInfo(year, LeapMonth);
if (month > 0)
{
return (month + 1);
}
return 0;
}
internal bool InternalIsLeapYear(int year)
{
return (GetYearInfo(year, LeapMonth) != 0);
}
// Checks whether a given year in the specified era is a leap year. This method returns true if
// year is a leap year, or false if not.
//
public override bool IsLeapYear(int year, int era)
{
year = CheckYearRange(year, era);
return InternalIsLeapYear(year);
}
private const int DEFAULT_GREGORIAN_TWO_DIGIT_YEAR_MAX = 2029;
public override int TwoDigitYearMax
{
get
{
if (twoDigitYearMax == -1)
{
twoDigitYearMax = GetSystemTwoDigitYearSetting(BaseCalendarID, GetYear(new DateTime(DEFAULT_GREGORIAN_TWO_DIGIT_YEAR_MAX, 1, 1)));
}
return (twoDigitYearMax);
}
set
{
VerifyWritable();
if (value < 99 || value > MaxCalendarYear)
{
throw new ArgumentOutOfRangeException(
nameof(value),
SR.Format(SR.ArgumentOutOfRange_Range, 99, MaxCalendarYear));
}
twoDigitYearMax = value;
}
}
public override int ToFourDigitYear(int year)
{
if (year < 0)
{
throw new ArgumentOutOfRangeException(nameof(year),
SR.ArgumentOutOfRange_NeedNonNegNum);
}
year = base.ToFourDigitYear(year);
CheckYearRange(year, CurrentEra);
return (year);
}
}
}
| |
// Unzip class for .NET 3.5 Client Profile or Mono 2.10
// Written by Alexey Yakovlev <yallie@yandex.ru>
// https://github.com/yallie/unzip
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
namespace RiseSharp.Tests.Internals
{
/// <summary>
/// Unzip helper class.
/// </summary>
internal class Unzip : IDisposable
{
/// <summary>
/// Zip archive entry.
/// </summary>
public class Entry
{
/// <summary>
/// Gets or sets the name of a file or a directory.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets or sets the comment.
/// </summary>
public string Comment { get; set; }
/// <summary>
/// Gets or sets the CRC32.
/// </summary>
public uint Crc32 { get; set; }
/// <summary>
/// Gets or sets the compressed size of the file.
/// </summary>
public int CompressedSize { get; set; }
/// <summary>
/// Gets or sets the original size of the file.
/// </summary>
public int OriginalSize { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this <see cref="Entry" /> is deflated.
/// </summary>
public bool Deflated { get; set; }
/// <summary>
/// Gets a value indicating whether this <see cref="Entry" /> is a directory.
/// </summary>
public bool IsDirectory { get { return Name.EndsWith("/"); } }
/// <summary>
/// Gets or sets the timestamp.
/// </summary>
public DateTime Timestamp { get; set; }
/// <summary>
/// Gets a value indicating whether this <see cref="Entry" /> is a file.
/// </summary>
public bool IsFile { get { return !IsDirectory; } }
[EditorBrowsable(EditorBrowsableState.Never)]
public int HeaderOffset { get; set; }
[EditorBrowsable(EditorBrowsableState.Never)]
public int DataOffset { get; set; }
}
/// <summary>
/// CRC32 calculation helper.
/// </summary>
public class Crc32Calculator
{
private static readonly uint[] Crc32Table =
{
0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3,
0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91,
0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5,
0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,
0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f,
0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d,
0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,
0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457,
0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb,
0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9,
0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad,
0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683,
0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7,
0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,
0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79,
0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f,
0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,
0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21,
0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45,
0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db,
0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf,
0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d,
};
private uint crcValue = 0xffffffff;
public uint Crc32 { get { return crcValue ^ 0xffffffff; } }
public void UpdateWithBlock(byte[] buffer, int numberOfBytes)
{
for (var i = 0; i < numberOfBytes; i++)
{
crcValue = (crcValue >> 8) ^ Crc32Table[buffer[i] ^ crcValue & 0xff];
}
}
}
/// <summary>
/// Provides data for the ExtractProgress event.
/// </summary>
public class FileProgressEventArgs : ProgressChangedEventArgs
{
/// <summary>
/// Initializes a new instance of the <see cref="FileProgressEventArgs"/> class.
/// </summary>
/// <param name="currentFile">The current file.</param>
/// <param name="totalFiles">The total files.</param>
/// <param name="fileName">Name of the file.</param>
public FileProgressEventArgs(int currentFile, int totalFiles, string fileName)
: base(totalFiles != 0 ? currentFile * 100 / totalFiles : 100, fileName)
{
CurrentFile = currentFile;
TotalFiles = totalFiles;
FileName = fileName;
}
/// <summary>
/// Gets the current file.
/// </summary>
public int CurrentFile { get; private set; }
/// <summary>
/// Gets the total files.
/// </summary>
public int TotalFiles { get; private set; }
/// <summary>
/// Gets the name of the file.
/// </summary>
public string FileName { get; private set; }
}
private const int EntrySignature = 0x02014B50;
private const int FileSignature = 0x04034b50;
private const int DirectorySignature = 0x06054B50;
private const int BufferSize = 16 * 1024;
/// <summary>
/// Occurs when a file or a directory is extracted from an archive.
/// </summary>
public event EventHandler<FileProgressEventArgs> ExtractProgress;
/// <summary>
/// Initializes a new instance of the <see cref="Unzip" /> class.
/// </summary>
/// <param name="fileName">Name of the file.</param>
public Unzip(string fileName)
: this(File.OpenRead(fileName))
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Unzip" /> class.
/// </summary>
/// <param name="stream">The stream.</param>
public Unzip(Stream stream)
{
Stream = stream;
Reader = new BinaryReader(Stream);
}
private Stream Stream { get; set; }
private BinaryReader Reader { get; set; }
/// <summary>
/// Performs application-defined tasks associated with
/// freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
if (Stream != null)
{
Stream.Dispose();
Stream = null;
}
if (Reader != null)
{
Reader.Close();
Reader = null;
}
}
/// <summary>
/// Extracts the contents of the zip file to the given directory.
/// </summary>
/// <param name="directoryName">Name of the directory.</param>
public void ExtractToDirectory(string directoryName)
{
for (int index = 0; index < Entries.Length; index++)
{
var entry = Entries[index];
// create target directory for the file
var fileName = Path.Combine(directoryName, entry.Name);
var dirName = Path.GetDirectoryName(fileName);
Directory.CreateDirectory(dirName);
// save file if it is not only a directory
if (!entry.IsDirectory)
{
Extract(entry.Name, fileName);
}
var extractProgress = ExtractProgress;
if (extractProgress != null)
{
extractProgress(this, new FileProgressEventArgs(index + 1, Entries.Length, entry.Name));
}
}
}
/// <summary>
/// Extracts the specified file to the specified name.
/// </summary>
/// <param name="fileName">Name of the file in zip archive.</param>
/// <param name="outputFileName">Name of the output file.</param>
public void Extract(string fileName, string outputFileName)
{
var entry = GetEntry(fileName);
using (var outStream = File.Create(outputFileName))
{
Extract(entry, outStream);
}
var fileInfo = new FileInfo(outputFileName);
if (fileInfo.Length != entry.OriginalSize)
{
throw new InvalidDataException(string.Format(
"Corrupted archive: {0} has an uncompressed size {1} which does not match its expected size {2}",
outputFileName, fileInfo.Length, entry.OriginalSize));
}
File.SetLastWriteTime(outputFileName, entry.Timestamp);
}
private Entry GetEntry(string fileName)
{
fileName = fileName.Replace("\\", "/").Trim().TrimStart('/');
var entry = Entries.FirstOrDefault(e => e.Name == fileName);
if (entry == null)
{
throw new FileNotFoundException("File not found in the archive: " + fileName);
}
return entry;
}
/// <summary>
/// Extracts the specified file to the output <see cref="Stream"/>.
/// </summary>
/// <param name="fileName">Name of the file in zip archive.</param>
/// <param name="outputStream">The output stream.</param>
public void Extract(string fileName, Stream outputStream)
{
Extract(GetEntry(fileName), outputStream);
}
/// <summary>
/// Extracts the specified entry.
/// </summary>
/// <param name="entry">Zip file entry to extract.</param>
/// <param name="outputStream">The stream to write the data to.</param>
/// <exception cref="System.InvalidOperationException"> is thrown when the file header signature doesn't match.</exception>
public void Extract(Entry entry, Stream outputStream)
{
// check file signature
Stream.Seek(entry.HeaderOffset, SeekOrigin.Begin);
if (Reader.ReadInt32() != FileSignature)
{
throw new InvalidDataException("File signature doesn't match.");
}
// move to file data
Stream.Seek(entry.DataOffset, SeekOrigin.Begin);
var inputStream = Stream;
if (entry.Deflated)
{
inputStream = new DeflateStream(Stream, CompressionMode.Decompress, true);
}
// allocate buffer, prepare for CRC32 calculation
var count = entry.OriginalSize;
var bufferSize = Math.Min(BufferSize, entry.OriginalSize);
var buffer = new byte[bufferSize];
var crc32Calculator = new Crc32Calculator();
while (count > 0)
{
// decompress data
var read = inputStream.Read(buffer, 0, bufferSize);
if (read == 0)
{
break;
}
crc32Calculator.UpdateWithBlock(buffer, read);
// copy to the output stream
outputStream.Write(buffer, 0, read);
count -= read;
}
if (crc32Calculator.Crc32 != entry.Crc32)
{
throw new InvalidDataException(string.Format(
"Corrupted archive: CRC32 doesn't match on file {0}: expected {1:x8}, got {2:x8}.",
entry.Name, entry.Crc32, crc32Calculator.Crc32));
}
}
/// <summary>
/// Gets the file names.
/// </summary>
public IEnumerable<string> FileNames
{
get
{
return Entries.Select(e => e.Name).Where(f => !f.EndsWith("/")).OrderBy(f => f);
}
}
private Entry[] entries;
/// <summary>
/// Gets zip file entries.
/// </summary>
public Entry[] Entries
{
get
{
if (entries == null)
{
entries = ReadZipEntries().ToArray();
}
return entries;
}
}
private IEnumerable<Entry> ReadZipEntries()
{
if (Stream.Length < 22)
{
yield break;
}
Stream.Seek(-22, SeekOrigin.End);
// find directory signature
while (Reader.ReadInt32() != DirectorySignature)
{
if (Stream.Position <= 5)
{
yield break;
}
// move 1 byte back
Stream.Seek(-5, SeekOrigin.Current);
}
// read directory properties
Stream.Seek(6, SeekOrigin.Current);
var entries = Reader.ReadUInt16();
var difSize = Reader.ReadInt32();
var dirOffset = Reader.ReadUInt32();
Stream.Seek(dirOffset, SeekOrigin.Begin);
// read directory entries
for (int i = 0; i < entries; i++)
{
if (Reader.ReadInt32() != EntrySignature)
{
continue;
}
// read file properties
// TODO: Replace with a proper class to make this method a lot shorter.
Reader.ReadInt32();
bool utf8 = (Reader.ReadInt16() & 0x0800) != 0;
short method = Reader.ReadInt16();
int timestamp = Reader.ReadInt32();
uint crc32 = Reader.ReadUInt32();
int compressedSize = Reader.ReadInt32();
int fileSize = Reader.ReadInt32();
short fileNameSize = Reader.ReadInt16();
short extraSize = Reader.ReadInt16();
short commentSize = Reader.ReadInt16();
int headerOffset = Reader.ReadInt32();
Reader.ReadInt32();
int fileHeaderOffset = Reader.ReadInt32();
var fileNameBytes = Reader.ReadBytes(fileNameSize);
Stream.Seek(extraSize, SeekOrigin.Current);
var fileCommentBytes = Reader.ReadBytes(commentSize);
var fileDataOffset = CalculateFileDataOffset(fileHeaderOffset);
// decode zip file entry
var encoder = utf8 ? Encoding.UTF8 : Encoding.Default;
yield return new Entry
{
Name = encoder.GetString(fileNameBytes),
Comment = encoder.GetString(fileCommentBytes),
Crc32 = crc32,
CompressedSize = compressedSize,
OriginalSize = fileSize,
HeaderOffset = fileHeaderOffset,
DataOffset = fileDataOffset,
Deflated = method == 8,
Timestamp = ConvertToDateTime(timestamp)
};
}
}
private int CalculateFileDataOffset(int fileHeaderOffset)
{
var position = Stream.Position;
Stream.Seek(fileHeaderOffset + 26, SeekOrigin.Begin);
var fileNameSize = Reader.ReadInt16();
var extraSize = Reader.ReadInt16();
var fileOffset = (int)Stream.Position + fileNameSize + extraSize;
Stream.Seek(position, SeekOrigin.Begin);
return fileOffset;
}
/// <summary>
/// Converts DOS timestamp to a <see cref="DateTime"/> instance.
/// </summary>
/// <param name="dosTimestamp">The dos timestamp.</param>
/// <returns>The <see cref="DateTime"/> instance.</returns>
public static DateTime ConvertToDateTime(int dosTimestamp)
{
return new DateTime((dosTimestamp >> 25) + 1980, (dosTimestamp >> 21) & 15, (dosTimestamp >> 16) & 31,
(dosTimestamp >> 11) & 31, (dosTimestamp >> 5) & 63, (dosTimestamp & 31) * 2);
}
}
}
| |
// Copyright 2016, Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using Google.Api.Gax;
using Google.Api.Gax.Grpc;
using Google.Iam.V1;
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using Google.Pubsub.V1;
using Grpc.Core;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Google.Pubsub.V1.Snippets
{
public class GeneratedSubscriberClientSnippets
{
public async Task CreateSubscriptionAsync()
{
// Snippet: CreateSubscriptionAsync(string,string,PushConfig,int,CallSettings)
// Additional: CreateSubscriptionAsync(string,string,PushConfig,int,CancellationToken)
// Create client
SubscriberClient subscriberClient = SubscriberClient.Create();
// Initialize request argument(s)
string formattedName = SubscriberClient.FormatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
string formattedTopic = SubscriberClient.FormatTopicName("[PROJECT]", "[TOPIC]");
PushConfig pushConfig = new PushConfig();
int ackDeadlineSeconds = 0;
// Make the request
Subscription response = await subscriberClient.CreateSubscriptionAsync(formattedName, formattedTopic, pushConfig, ackDeadlineSeconds);
// End snippet
}
public void CreateSubscription()
{
// Snippet: CreateSubscription(string,string,PushConfig,int,CallSettings)
// Create client
SubscriberClient subscriberClient = SubscriberClient.Create();
// Initialize request argument(s)
string formattedName = SubscriberClient.FormatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
string formattedTopic = SubscriberClient.FormatTopicName("[PROJECT]", "[TOPIC]");
PushConfig pushConfig = new PushConfig();
int ackDeadlineSeconds = 0;
// Make the request
Subscription response = subscriberClient.CreateSubscription(formattedName, formattedTopic, pushConfig, ackDeadlineSeconds);
// End snippet
}
public async Task GetSubscriptionAsync()
{
// Snippet: GetSubscriptionAsync(string,CallSettings)
// Additional: GetSubscriptionAsync(string,CancellationToken)
// Create client
SubscriberClient subscriberClient = SubscriberClient.Create();
// Initialize request argument(s)
string formattedSubscription = SubscriberClient.FormatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
// Make the request
Subscription response = await subscriberClient.GetSubscriptionAsync(formattedSubscription);
// End snippet
}
public void GetSubscription()
{
// Snippet: GetSubscription(string,CallSettings)
// Create client
SubscriberClient subscriberClient = SubscriberClient.Create();
// Initialize request argument(s)
string formattedSubscription = SubscriberClient.FormatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
// Make the request
Subscription response = subscriberClient.GetSubscription(formattedSubscription);
// End snippet
}
public async Task ListSubscriptionsAsync()
{
// Snippet: ListSubscriptionsAsync(string,string,int?,CallSettings)
// Create client
SubscriberClient subscriberClient = SubscriberClient.Create();
// Initialize request argument(s)
string formattedProject = SubscriberClient.FormatProjectName("[PROJECT]");
// Make the request
IPagedAsyncEnumerable<ListSubscriptionsResponse,Subscription> response =
subscriberClient.ListSubscriptionsAsync(formattedProject);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Subscription item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over fixed-sized pages, lazily performing RPCs as required
int pageSize = 10;
IAsyncEnumerable<FixedSizePage<Subscription>> fixedSizePages = response.AsPages().WithFixedSize(pageSize);
await fixedSizePages.ForEachAsync((FixedSizePage<Subscription> page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Subscription item in page)
{
Console.WriteLine(item);
}
});
// End snippet
}
public void ListSubscriptions()
{
// Snippet: ListSubscriptions(string,string,int?,CallSettings)
// Create client
SubscriberClient subscriberClient = SubscriberClient.Create();
// Initialize request argument(s)
string formattedProject = SubscriberClient.FormatProjectName("[PROJECT]");
// Make the request
IPagedEnumerable<ListSubscriptionsResponse,Subscription> response =
subscriberClient.ListSubscriptions(formattedProject);
// Iterate over all response items, lazily performing RPCs as required
foreach (Subscription item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over fixed-sized pages, lazily performing RPCs as required
int pageSize = 10;
foreach (FixedSizePage<Subscription> page in response.AsPages().WithFixedSize(pageSize))
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Subscription item in page)
{
Console.WriteLine(item);
}
}
// End snippet
}
public async Task DeleteSubscriptionAsync()
{
// Snippet: DeleteSubscriptionAsync(string,CallSettings)
// Additional: DeleteSubscriptionAsync(string,CancellationToken)
// Create client
SubscriberClient subscriberClient = SubscriberClient.Create();
// Initialize request argument(s)
string formattedSubscription = SubscriberClient.FormatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
// Make the request
await subscriberClient.DeleteSubscriptionAsync(formattedSubscription);
// End snippet
}
public void DeleteSubscription()
{
// Snippet: DeleteSubscription(string,CallSettings)
// Create client
SubscriberClient subscriberClient = SubscriberClient.Create();
// Initialize request argument(s)
string formattedSubscription = SubscriberClient.FormatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
// Make the request
subscriberClient.DeleteSubscription(formattedSubscription);
// End snippet
}
public async Task ModifyAckDeadlineAsync()
{
// Snippet: ModifyAckDeadlineAsync(string,IEnumerable<string>,int,CallSettings)
// Additional: ModifyAckDeadlineAsync(string,IEnumerable<string>,int,CancellationToken)
// Create client
SubscriberClient subscriberClient = SubscriberClient.Create();
// Initialize request argument(s)
string formattedSubscription = SubscriberClient.FormatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
IEnumerable<string> ackIds = new List<string>();
int ackDeadlineSeconds = 0;
// Make the request
await subscriberClient.ModifyAckDeadlineAsync(formattedSubscription, ackIds, ackDeadlineSeconds);
// End snippet
}
public void ModifyAckDeadline()
{
// Snippet: ModifyAckDeadline(string,IEnumerable<string>,int,CallSettings)
// Create client
SubscriberClient subscriberClient = SubscriberClient.Create();
// Initialize request argument(s)
string formattedSubscription = SubscriberClient.FormatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
IEnumerable<string> ackIds = new List<string>();
int ackDeadlineSeconds = 0;
// Make the request
subscriberClient.ModifyAckDeadline(formattedSubscription, ackIds, ackDeadlineSeconds);
// End snippet
}
public async Task AcknowledgeAsync()
{
// Snippet: AcknowledgeAsync(string,IEnumerable<string>,CallSettings)
// Additional: AcknowledgeAsync(string,IEnumerable<string>,CancellationToken)
// Create client
SubscriberClient subscriberClient = SubscriberClient.Create();
// Initialize request argument(s)
string formattedSubscription = SubscriberClient.FormatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
IEnumerable<string> ackIds = new List<string>();
// Make the request
await subscriberClient.AcknowledgeAsync(formattedSubscription, ackIds);
// End snippet
}
public void Acknowledge()
{
// Snippet: Acknowledge(string,IEnumerable<string>,CallSettings)
// Create client
SubscriberClient subscriberClient = SubscriberClient.Create();
// Initialize request argument(s)
string formattedSubscription = SubscriberClient.FormatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
IEnumerable<string> ackIds = new List<string>();
// Make the request
subscriberClient.Acknowledge(formattedSubscription, ackIds);
// End snippet
}
public async Task PullAsync()
{
// Snippet: PullAsync(string,bool,int,CallSettings)
// Additional: PullAsync(string,bool,int,CancellationToken)
// Create client
SubscriberClient subscriberClient = SubscriberClient.Create();
// Initialize request argument(s)
string formattedSubscription = SubscriberClient.FormatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
bool returnImmediately = false;
int maxMessages = 0;
// Make the request
PullResponse response = await subscriberClient.PullAsync(formattedSubscription, returnImmediately, maxMessages);
// End snippet
}
public void Pull()
{
// Snippet: Pull(string,bool,int,CallSettings)
// Create client
SubscriberClient subscriberClient = SubscriberClient.Create();
// Initialize request argument(s)
string formattedSubscription = SubscriberClient.FormatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
bool returnImmediately = false;
int maxMessages = 0;
// Make the request
PullResponse response = subscriberClient.Pull(formattedSubscription, returnImmediately, maxMessages);
// End snippet
}
public async Task ModifyPushConfigAsync()
{
// Snippet: ModifyPushConfigAsync(string,PushConfig,CallSettings)
// Additional: ModifyPushConfigAsync(string,PushConfig,CancellationToken)
// Create client
SubscriberClient subscriberClient = SubscriberClient.Create();
// Initialize request argument(s)
string formattedSubscription = SubscriberClient.FormatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
PushConfig pushConfig = new PushConfig();
// Make the request
await subscriberClient.ModifyPushConfigAsync(formattedSubscription, pushConfig);
// End snippet
}
public void ModifyPushConfig()
{
// Snippet: ModifyPushConfig(string,PushConfig,CallSettings)
// Create client
SubscriberClient subscriberClient = SubscriberClient.Create();
// Initialize request argument(s)
string formattedSubscription = SubscriberClient.FormatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
PushConfig pushConfig = new PushConfig();
// Make the request
subscriberClient.ModifyPushConfig(formattedSubscription, pushConfig);
// End snippet
}
public async Task SetIamPolicyAsync()
{
// Snippet: SetIamPolicyAsync(string,Policy,CallSettings)
// Additional: SetIamPolicyAsync(string,Policy,CancellationToken)
// Create client
SubscriberClient subscriberClient = SubscriberClient.Create();
// Initialize request argument(s)
string formattedResource = SubscriberClient.FormatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
Policy policy = new Policy();
// Make the request
Policy response = await subscriberClient.SetIamPolicyAsync(formattedResource, policy);
// End snippet
}
public void SetIamPolicy()
{
// Snippet: SetIamPolicy(string,Policy,CallSettings)
// Create client
SubscriberClient subscriberClient = SubscriberClient.Create();
// Initialize request argument(s)
string formattedResource = SubscriberClient.FormatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
Policy policy = new Policy();
// Make the request
Policy response = subscriberClient.SetIamPolicy(formattedResource, policy);
// End snippet
}
public async Task GetIamPolicyAsync()
{
// Snippet: GetIamPolicyAsync(string,CallSettings)
// Additional: GetIamPolicyAsync(string,CancellationToken)
// Create client
SubscriberClient subscriberClient = SubscriberClient.Create();
// Initialize request argument(s)
string formattedResource = SubscriberClient.FormatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
// Make the request
Policy response = await subscriberClient.GetIamPolicyAsync(formattedResource);
// End snippet
}
public void GetIamPolicy()
{
// Snippet: GetIamPolicy(string,CallSettings)
// Create client
SubscriberClient subscriberClient = SubscriberClient.Create();
// Initialize request argument(s)
string formattedResource = SubscriberClient.FormatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
// Make the request
Policy response = subscriberClient.GetIamPolicy(formattedResource);
// End snippet
}
public async Task TestIamPermissionsAsync()
{
// Snippet: TestIamPermissionsAsync(string,IEnumerable<string>,CallSettings)
// Additional: TestIamPermissionsAsync(string,IEnumerable<string>,CancellationToken)
// Create client
SubscriberClient subscriberClient = SubscriberClient.Create();
// Initialize request argument(s)
string formattedResource = SubscriberClient.FormatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
IEnumerable<string> permissions = new List<string>();
// Make the request
TestIamPermissionsResponse response = await subscriberClient.TestIamPermissionsAsync(formattedResource, permissions);
// End snippet
}
public void TestIamPermissions()
{
// Snippet: TestIamPermissions(string,IEnumerable<string>,CallSettings)
// Create client
SubscriberClient subscriberClient = SubscriberClient.Create();
// Initialize request argument(s)
string formattedResource = SubscriberClient.FormatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
IEnumerable<string> permissions = new List<string>();
// Make the request
TestIamPermissionsResponse response = subscriberClient.TestIamPermissions(formattedResource, permissions);
// End snippet
}
}
}
| |
namespace System.Web.Services.Protocols {
using System;
using System.Reflection;
using System.Collections;
using System.Text.RegularExpressions;
using System.Security.Permissions;
/// <include file='doc\PatternMatcher.uex' path='docs/doc[@for="PatternMatcher"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")]
public sealed class PatternMatcher {
MatchType matchType;
/// <include file='doc\PatternMatcher.uex' path='docs/doc[@for="PatternMatcher.PatternMatcher"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public PatternMatcher(Type type) {
matchType = MatchType.Reflect(type);
}
/// <include file='doc\PatternMatcher.uex' path='docs/doc[@for="PatternMatcher.Match"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public object Match(string text) {
return matchType.Match(text);
}
}
internal class MatchType {
Type type;
MatchMember[] fields;
internal Type Type {
get { return type; }
}
internal static MatchType Reflect(Type type) {
MatchType matchType = new MatchType();
matchType.type = type;
MemberInfo[] memberInfos = type.GetMembers(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance);
ArrayList list = new ArrayList();
for (int i = 0; i < memberInfos.Length; i++) {
MatchMember member = MatchMember.Reflect(memberInfos[i]);
if (member != null) list.Add(member);
}
matchType.fields = (MatchMember[])list.ToArray(typeof(MatchMember));
return matchType;
}
internal object Match(string text) {
object target = Activator.CreateInstance(type);
for (int i = 0; i < fields.Length; i++)
fields[i].Match(target, text);
return target;
}
}
internal class MatchMember {
MemberInfo memberInfo;
Regex regex;
int group;
int capture;
int maxRepeats;
MatchType matchType;
internal void Match(object target, string text) {
if (memberInfo is FieldInfo)
((FieldInfo)memberInfo).SetValue(target, matchType == null ? MatchString(text) : MatchClass(text));
else if (memberInfo is PropertyInfo) {
((PropertyInfo)memberInfo).SetValue(target, matchType == null ? MatchString(text) : MatchClass(text), new object[0]);
}
}
object MatchString(string text) {
Match m = regex.Match(text);
Type fieldType = memberInfo is FieldInfo ? ((FieldInfo)memberInfo).FieldType : ((PropertyInfo)memberInfo).PropertyType;
if (fieldType.IsArray) {
ArrayList matches = new ArrayList();
int matchCount = 0;
while (m.Success && matchCount < maxRepeats) {
if (m.Groups.Count <= group)
throw BadGroupIndexException(group, memberInfo.Name, m.Groups.Count - 1);
Group g = m.Groups[group];
foreach (Capture c in g.Captures) {
matches.Add(text.Substring(c.Index, c.Length));
}
m = m.NextMatch();
matchCount++;
}
return matches.ToArray(typeof(string));
}
else {
if (m.Success) {
if (m.Groups.Count <= group)
throw BadGroupIndexException(group, memberInfo.Name, m.Groups.Count - 1);
Group g = m.Groups[group];
if (g.Captures.Count > 0) {
if (g.Captures.Count <= capture)
throw BadCaptureIndexException(capture, memberInfo.Name, g.Captures.Count - 1);
Capture c = g.Captures[capture];
return text.Substring(c.Index, c.Length);
}
}
return null;
}
}
object MatchClass(string text) {
Match m = regex.Match(text);
Type fieldType = memberInfo is FieldInfo ? ((FieldInfo)memberInfo).FieldType : ((PropertyInfo)memberInfo).PropertyType;
if (fieldType.IsArray) {
ArrayList matches = new ArrayList();
int matchCount = 0;
while (m.Success && matchCount < maxRepeats) {
if (m.Groups.Count <= group)
throw BadGroupIndexException(group, memberInfo.Name, m.Groups.Count - 1);
Group g = m.Groups[group];
foreach (Capture c in g.Captures) {
matches.Add(matchType.Match(text.Substring(c.Index, c.Length)));
}
m = m.NextMatch();
matchCount++;
}
return matches.ToArray(matchType.Type);
}
else {
if (m.Success) {
if (m.Groups.Count <= group)
throw BadGroupIndexException(group, memberInfo.Name, m.Groups.Count - 1);
Group g = m.Groups[group];
if (g.Captures.Count > 0) {
if (g.Captures.Count <= capture)
throw BadCaptureIndexException(capture, memberInfo.Name, g.Captures.Count - 1);
Capture c = g.Captures[capture];
return matchType.Match(text.Substring(c.Index, c.Length));
}
}
return null;
}
}
static Exception BadCaptureIndexException(int index, string matchName, int highestIndex) {
return new Exception(Res.GetString(Res.WebTextMatchBadCaptureIndex, index, matchName, highestIndex));
}
static Exception BadGroupIndexException(int index, string matchName, int highestIndex) {
return new Exception(Res.GetString(Res.WebTextMatchBadGroupIndex, index, matchName, highestIndex));
}
internal static MatchMember Reflect(MemberInfo memberInfo) {
Type memberType = null;
if (memberInfo is PropertyInfo) {
PropertyInfo propertyInfo = (PropertyInfo)memberInfo;
if (!propertyInfo.CanRead)
return null;
//
if (!propertyInfo.CanWrite)
return null;
MethodInfo getMethod = propertyInfo.GetGetMethod();
if (getMethod.IsStatic)
return null;
ParameterInfo[] parameters = getMethod.GetParameters();
if (parameters.Length > 0)
return null;
memberType = propertyInfo.PropertyType;
}
if (memberInfo is FieldInfo) {
FieldInfo fieldInfo = (FieldInfo)memberInfo;
if (!fieldInfo.IsPublic)
return null;
if (fieldInfo.IsStatic)
return null;
if (fieldInfo.IsSpecialName)
return null;
memberType = fieldInfo.FieldType;
}
object[] attrs = memberInfo.GetCustomAttributes(typeof(MatchAttribute), false);
if (attrs.Length == 0) return null;
MatchAttribute attr = (MatchAttribute)attrs[0];
MatchMember member = new MatchMember();
member.regex = new Regex(attr.Pattern, RegexOptions.Singleline | (attr.IgnoreCase ? RegexOptions.IgnoreCase | RegexOptions.CultureInvariant : 0));
member.group = attr.Group;
member.capture = attr.Capture;
member.maxRepeats = attr.MaxRepeats;
member.memberInfo = memberInfo;
if (member.maxRepeats < 0) // unspecified
member.maxRepeats = memberType.IsArray ? int.MaxValue : 1;
if (memberType.IsArray) {
memberType = memberType.GetElementType();
}
if (memberType != typeof(string)) {
member.matchType = MatchType.Reflect(memberType);
}
return member;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
using System;
using System.Runtime;
using System.Security;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using Internal.Runtime.CompilerServices;
namespace System.Runtime.InteropServices.WindowsRuntime
{
// This is a set of stub methods implementing the support for the IList interface on WinRT
// objects that support IBindableVector. Used by the interop mashaling infrastructure.
//
// The methods on this class must be written VERY carefully to avoid introducing security holes.
// That's because they are invoked with special "this"! The "this" object
// for all of these methods are not BindableVectorToListAdapter objects. Rather, they are
// of type IBindableVector. No actual BindableVectorToListAdapter object is ever instantiated.
// Thus, you will see a lot of expressions that cast "this" to "IBindableVector".
internal sealed class BindableVectorToListAdapter
{
private BindableVectorToListAdapter()
{
Debug.Fail("This class is never instantiated");
}
// object this[int index] { get }
internal object Indexer_Get(int index)
{
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index));
IBindableVector _this = Unsafe.As<IBindableVector>(this);
return GetAt(_this, (uint)index);
}
// object this[int index] { set }
internal void Indexer_Set(int index, object value)
{
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index));
IBindableVector _this = Unsafe.As<IBindableVector>(this);
SetAt(_this, (uint)index, value);
}
// int Add(object value)
internal int Add(object value)
{
IBindableVector _this = Unsafe.As<IBindableVector>(this);
_this.Append(value);
uint size = _this.Size;
if (((uint)Int32.MaxValue) < size)
{
throw new InvalidOperationException(SR.InvalidOperation_CollectionBackingListTooLarge);
}
return (int)(size - 1);
}
// bool Contains(object item)
internal bool Contains(object item)
{
IBindableVector _this = Unsafe.As<IBindableVector>(this);
uint index;
return _this.IndexOf(item, out index);
}
// void Clear()
internal void Clear()
{
IBindableVector _this = Unsafe.As<IBindableVector>(this);
_this.Clear();
}
// bool IsFixedSize { get }
internal bool IsFixedSize()
{
return false;
}
// bool IsReadOnly { get }
internal bool IsReadOnly()
{
return false;
}
// int IndexOf(object item)
internal int IndexOf(object item)
{
IBindableVector _this = Unsafe.As<IBindableVector>(this);
uint index;
bool exists = _this.IndexOf(item, out index);
if (!exists)
return -1;
if (((uint)Int32.MaxValue) < index)
{
throw new InvalidOperationException(SR.InvalidOperation_CollectionBackingListTooLarge);
}
return (int)index;
}
// void Insert(int index, object item)
internal void Insert(int index, object item)
{
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index));
IBindableVector _this = Unsafe.As<IBindableVector>(this);
InsertAtHelper(_this, (uint)index, item);
}
// bool Remove(object item)
internal void Remove(object item)
{
IBindableVector _this = Unsafe.As<IBindableVector>(this);
uint index;
bool exists = _this.IndexOf(item, out index);
if (exists)
{
if (((uint)Int32.MaxValue) < index)
{
throw new InvalidOperationException(SR.InvalidOperation_CollectionBackingListTooLarge);
}
RemoveAtHelper(_this, index);
}
}
// void RemoveAt(int index)
internal void RemoveAt(int index)
{
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index));
IBindableVector _this = Unsafe.As<IBindableVector>(this);
RemoveAtHelper(_this, (uint)index);
}
// Helpers:
private static object GetAt(IBindableVector _this, uint index)
{
try
{
return _this.GetAt(index);
// We delegate bounds checking to the underlying collection and if it detected a fault,
// we translate it to the right exception:
}
catch (Exception ex)
{
if (HResults.E_BOUNDS == ex._HResult)
throw new ArgumentOutOfRangeException(nameof(index));
throw;
}
}
private static void SetAt(IBindableVector _this, uint index, object value)
{
try
{
_this.SetAt(index, value);
// We delegate bounds checking to the underlying collection and if it detected a fault,
// we translate it to the right exception:
}
catch (Exception ex)
{
if (HResults.E_BOUNDS == ex._HResult)
throw new ArgumentOutOfRangeException(nameof(index));
throw;
}
}
private static void InsertAtHelper(IBindableVector _this, uint index, object item)
{
try
{
_this.InsertAt(index, item);
// We delegate bounds checking to the underlying collection and if it detected a fault,
// we translate it to the right exception:
}
catch (Exception ex)
{
if (HResults.E_BOUNDS == ex._HResult)
throw new ArgumentOutOfRangeException(nameof(index));
throw;
}
}
private static void RemoveAtHelper(IBindableVector _this, uint index)
{
try
{
_this.RemoveAt(index);
// We delegate bounds checking to the underlying collection and if it detected a fault,
// we translate it to the right exception:
}
catch (Exception ex)
{
if (HResults.E_BOUNDS == ex._HResult)
throw new ArgumentOutOfRangeException(nameof(index));
throw;
}
}
}
}
| |
// Copyright (c) 2012, Event Store LLP
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// Neither the name of the Event Store LLP nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
using System;
using EventStore.Common.Utils;
using EventStore.Core.Data;
using EventStore.Core.Messages;
using EventStore.Core.Services.Transport.Http.Controllers;
using EventStore.Core.TransactionLog.LogRecords;
using EventStore.Transport.Http.Atom;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace EventStore.Core.Services.Transport.Http
{
public static class Convert
{
private static readonly string AllEscaped = Uri.EscapeDataString("$all");
public static FeedElement ToStreamEventForwardFeed(ClientMessage.ReadStreamEventsForwardCompleted msg, Uri requestedUrl, EmbedLevel embedContent)
{
Ensure.NotNull(msg, "msg");
string escapedStreamId = Uri.EscapeDataString(msg.EventStreamId);
var self = HostName.Combine(requestedUrl, "/streams/{0}", escapedStreamId);
var feed = new FeedElement();
feed.SetTitle(string.Format("Event stream '{0}'", msg.EventStreamId));
feed.StreamId = msg.EventStreamId;
feed.SetId(self);
feed.SetUpdated(msg.Events.Length > 0 ? msg.Events[0].Event.TimeStamp : DateTime.MinValue.ToUniversalTime());
feed.SetAuthor(AtomSpecs.Author);
var prevEventNumber = Math.Min(msg.FromEventNumber + msg.MaxCount - 1, msg.LastEventNumber) + 1;
var nextEventNumber = msg.FromEventNumber - 1;
feed.AddLink("self", self);
feed.AddLink("first", HostName.Combine(requestedUrl, "/streams/{0}/head/backward/{1}", escapedStreamId, msg.MaxCount));
if (nextEventNumber >= 0)
{
feed.AddLink("last", HostName.Combine(requestedUrl, "/streams/{0}/{1}/forward/{2}", escapedStreamId, 0, msg.MaxCount));
feed.AddLink("next", HostName.Combine(requestedUrl, "/streams/{0}/{1}/backward/{2}", escapedStreamId, nextEventNumber, msg.MaxCount));
}
if (!msg.IsEndOfStream || msg.Events.Length > 0)
feed.AddLink("previous", HostName.Combine(requestedUrl, "/streams/{0}/{1}/forward/{2}", escapedStreamId, prevEventNumber, msg.MaxCount));
feed.AddLink("metadata", HostName.Combine(requestedUrl, "/streams/{0}/metadata", escapedStreamId));
for (int i = msg.Events.Length - 1; i >= 0; --i)
{
feed.AddEntry(ToEntry(msg.Events[i], requestedUrl, embedContent));
}
return feed;
}
public static FeedElement ToStreamEventBackwardFeed(ClientMessage.ReadStreamEventsBackwardCompleted msg, Uri requestedUrl, EmbedLevel embedContent, bool headOfStream)
{
Ensure.NotNull(msg, "msg");
string escapedStreamId = Uri.EscapeDataString(msg.EventStreamId);
var self = HostName.Combine(requestedUrl, "/streams/{0}", escapedStreamId);
var feed = new FeedElement();
feed.SetTitle(string.Format("Event stream '{0}'", msg.EventStreamId));
feed.StreamId = msg.EventStreamId;
feed.SetId(self);
feed.SetUpdated(msg.Events.Length > 0 ? msg.Events[0].Event.TimeStamp : DateTime.MinValue.ToUniversalTime());
feed.SetAuthor(AtomSpecs.Author);
feed.SetHeadOfStream(headOfStream); //TODO AN: remove this ?
feed.SetSelfUrl(self);
var prevEventNumber = Math.Min(msg.FromEventNumber, msg.LastEventNumber) + 1;
var nextEventNumber = msg.FromEventNumber - msg.MaxCount;
feed.AddLink("self", self);
feed.AddLink("first", HostName.Combine(requestedUrl, "/streams/{0}/head/backward/{1}", escapedStreamId, msg.MaxCount));
if (!msg.IsEndOfStream)
{
if (nextEventNumber < 0) throw new Exception(string.Format("nextEventNumber is negative: {0} while IsEndOfStream", nextEventNumber));
feed.AddLink("last", HostName.Combine(requestedUrl, "/streams/{0}/{1}/forward/{2}", escapedStreamId, 0, msg.MaxCount));
feed.AddLink("next", HostName.Combine(requestedUrl, "/streams/{0}/{1}/backward/{2}", escapedStreamId, nextEventNumber, msg.MaxCount));
}
feed.AddLink("previous", HostName.Combine(requestedUrl, "/streams/{0}/{1}/forward/{2}", escapedStreamId, prevEventNumber, msg.MaxCount));
feed.AddLink("metadata", HostName.Combine(requestedUrl, "/streams/{0}/metadata", escapedStreamId));
for (int i = 0; i < msg.Events.Length; ++i)
{
feed.AddEntry(ToEntry(msg.Events[i], requestedUrl, embedContent));
}
return feed;
}
public static FeedElement ToAllEventsForwardFeed(ClientMessage.ReadAllEventsForwardCompleted msg, Uri requestedUrl, EmbedLevel embedContent)
{
var self = HostName.Combine(requestedUrl, "/streams/{0}", AllEscaped);
var feed = new FeedElement();
feed.SetTitle("All events");
feed.SetId(self);
feed.SetUpdated(msg.Events.Length > 0 ? msg.Events[msg.Events.Length - 1].Event.TimeStamp : DateTime.MinValue.ToUniversalTime());
feed.SetAuthor(AtomSpecs.Author);
feed.AddLink("self", self);
feed.AddLink("first", HostName.Combine(requestedUrl, "/streams/{0}/head/backward/{1}", AllEscaped, msg.MaxCount));
if (msg.CurrentPos.CommitPosition != 0)
{
feed.AddLink("last", HostName.Combine(requestedUrl, "/streams/{0}/{1}/forward/{2}", AllEscaped, new TFPos(0, 0).AsString(), msg.MaxCount));
feed.AddLink("next", HostName.Combine(requestedUrl, "/streams/{0}/{1}/backward/{2}", AllEscaped, msg.PrevPos.AsString(), msg.MaxCount));
}
if (!msg.IsEndOfStream || msg.Events.Length > 0)
feed.AddLink("previous", HostName.Combine(requestedUrl, "/streams/{0}/{1}/forward/{2}", AllEscaped, msg.NextPos.AsString(), msg.MaxCount));
feed.AddLink("metadata", HostName.Combine(requestedUrl, "/streams/{0}/metadata", AllEscaped));
for (int i = msg.Events.Length - 1; i >= 0; --i)
{
feed.AddEntry(
ToEntry(
new ResolvedEvent(msg.Events[i].Event, msg.Events[i].Link, msg.Events[i].ResolveResult),
requestedUrl, embedContent));
}
return feed;
}
public static FeedElement ToAllEventsBackwardFeed(ClientMessage.ReadAllEventsBackwardCompleted msg, Uri requestedUrl, EmbedLevel embedContent)
{
var self = HostName.Combine(requestedUrl, "/streams/{0}", AllEscaped);
var feed = new FeedElement();
feed.SetTitle(string.Format("All events"));
feed.SetId(self);
feed.SetUpdated(msg.Events.Length > 0 ? msg.Events[0].Event.TimeStamp : DateTime.MinValue.ToUniversalTime());
feed.SetAuthor(AtomSpecs.Author);
feed.AddLink("self", self);
feed.AddLink("first", HostName.Combine(requestedUrl, "/streams/{0}/head/backward/{1}", AllEscaped, msg.MaxCount));
if (!msg.IsEndOfStream)
{
feed.AddLink("last", HostName.Combine(requestedUrl, "/streams/{0}/{1}/forward/{2}", AllEscaped, new TFPos(0, 0).AsString(), msg.MaxCount));
feed.AddLink("next", HostName.Combine(requestedUrl, "/streams/{0}/{1}/backward/{2}", AllEscaped, msg.NextPos.AsString(), msg.MaxCount));
}
feed.AddLink("previous", HostName.Combine(requestedUrl, "/streams/{0}/{1}/forward/{2}", AllEscaped, msg.PrevPos.AsString(), msg.MaxCount));
feed.AddLink("metadata", HostName.Combine(requestedUrl, "/streams/{0}/metadata", AllEscaped));
for (int i = 0; i < msg.Events.Length; ++i)
{
feed.AddEntry(
ToEntry(
new ResolvedEvent(msg.Events[i].Event, msg.Events[i].Link, msg.Events[i].ResolveResult),
requestedUrl, embedContent));
}
return feed;
}
public static EntryElement ToEntry(ResolvedEvent eventLinkPair, Uri requestedUrl, EmbedLevel embedContent, bool singleEntry = false)
{
if (eventLinkPair.Event == null || requestedUrl == null)
return null;
var evnt = eventLinkPair.Event;
EntryElement entry;
if (embedContent > EmbedLevel.Content)
{
var richEntry = new RichEntryElement();
entry = richEntry;
richEntry.EventType = evnt.EventType;
richEntry.EventNumber = evnt.EventNumber;
richEntry.StreamId = evnt.EventStreamId;
richEntry.PositionEventNumber = eventLinkPair.OriginalEvent.EventNumber;
richEntry.PositionStreamId = eventLinkPair.OriginalEvent.EventStreamId;
richEntry.IsJson = (evnt.Flags & PrepareFlags.IsJson) != 0;
if (embedContent >= EmbedLevel.Body)
{
if (richEntry.IsJson)
{
if (embedContent >= EmbedLevel.PrettyBody)
{
try
{
richEntry.Data = Helper.UTF8NoBom.GetString(evnt.Data);
// next step may fail, so we have already assigned body
richEntry.Data = FormatJson(Helper.UTF8NoBom.GetString(evnt.Data));
}
catch
{
// ignore - we tried
}
}
else
richEntry.Data = Helper.UTF8NoBom.GetString(evnt.Data);
}
else if (embedContent >= EmbedLevel.TryHarder)
{
try
{
richEntry.Data = Helper.UTF8NoBom.GetString(evnt.Data);
// next step may fail, so we have already assigned body
richEntry.Data = FormatJson(richEntry.Data);
// it is json if successed
richEntry.IsJson = true;
}
catch
{
// ignore - we tried
}
}
// metadata
if (embedContent >= EmbedLevel.PrettyBody)
{
try
{
richEntry.MetaData = Helper.UTF8NoBom.GetString(evnt.Metadata);
richEntry.IsMetaData = richEntry.MetaData.IsNotEmptyString();
// next step may fail, so we have already assigned body
richEntry.MetaData = FormatJson(richEntry.MetaData);
}
catch
{
// ignore - we tried
}
var lnk = eventLinkPair.Link;
if (lnk != null)
{
try
{
richEntry.LinkMetaData = Helper.UTF8NoBom.GetString(lnk.Metadata);
richEntry.IsLinkMetaData = richEntry.LinkMetaData.IsNotEmptyString();
// next step may fail, so we have already assigned body
richEntry.LinkMetaData = FormatJson(richEntry.LinkMetaData);
}
catch
{
// ignore - we tried
}
}
}
}
}
else
{
entry = new EntryElement();
}
var escapedStreamId = Uri.EscapeDataString(evnt.EventStreamId);
entry.SetTitle(evnt.EventNumber + "@" + evnt.EventStreamId);
entry.SetId(HostName.Combine(requestedUrl, "/streams/{0}/{1}", escapedStreamId, evnt.EventNumber));
entry.SetUpdated(evnt.TimeStamp);
entry.SetAuthor(AtomSpecs.Author);
entry.SetSummary(evnt.EventType);
if ((singleEntry || embedContent == EmbedLevel.Content) && ((evnt.Flags & PrepareFlags.IsJson) != 0))
entry.SetContent(AutoEventConverter.CreateDataDto(eventLinkPair));
entry.AddLink("edit", HostName.Combine(requestedUrl, "/streams/{0}/{1}", escapedStreamId, evnt.EventNumber));
entry.AddLink("alternate", HostName.Combine(requestedUrl, "/streams/{0}/{1}", escapedStreamId, evnt.EventNumber));
return entry;
}
private static string FormatJson(string unformattedjson)
{
if (string.IsNullOrEmpty(unformattedjson))
return unformattedjson;
var jo = JObject.Parse(unformattedjson);
var json = JsonConvert.SerializeObject(jo, Formatting.Indented);
return json;
}
}
}
| |
//#define DEBUG_COMMANDS // uncomment this line for commands
using GTANetworkServer;
using GTANetworkShared;
using System.Collections.Generic;
public class BillboardManager : Script
{
public Dictionary<int, Billboard> Billboards;
public float BillboardRange = 40f;
private int _counter;
public BillboardManager()
{
Billboards = new Dictionary<int, Billboard>();
API.onResourceStart += () =>
{
BillboardRange = API.getSetting<float>("range");
};
}
private Billboard createBasicBillboard(Vector3 pos, Vector3 rot, Vector3 scale)
{
int id = ++_counter;
var bb = new Billboard();
bb.Id = id;
bb.Position = pos;
bb.Rotation = rot;
bb.Scale = scale;
bb.Collision = API.createSphereColShape(pos, BillboardRange);
bb.Collision.onEntityEnterColShape += (shape, entity) =>
{
var player = API.getPlayerFromHandle(entity);
if (player == null) return;
sendBillboard(player, bb);
};
bb.Collision.onEntityExitColShape += (shape, entity) =>
{
var player = API.getPlayerFromHandle(entity);
if (player == null) return;
player.triggerEvent("REMOVE_BILLBOARD", id);
};
Billboards.Add(id, bb);
return bb;
}
private void sendBillboard(Client cl, Billboard bb)
{
object[] args = new object[6 + bb.Arguments.Count * 2];
// id, pos, rot, scale, argc, args*2
// 5 + args*2
args[0] = bb.Id;
args[1] = bb.Position;
args[2] = bb.Rotation;
args[3] = bb.Scale;
args[4] = bb.Type;
args[5] = bb.Arguments.Count;
int counter = 6;
foreach(var pair in bb.Arguments)
{
args[counter] = pair.Key;
args[counter + 1] = pair.Value;
counter += 2;
}
cl.triggerEvent("CREATE_BILLBOARD", args);
}
// EXPORTED METHODS
public void setBillboardRange(float range)
{
BillboardRange = range;
}
// player_name
public int createSimpleBillboard(string text, Vector3 pos, Vector3 rot, Vector3 scale)
{
var bb = createBasicBillboard(pos, rot, scale);
bb.Type = 0;
bb.Arguments.Add("text", text);
return bb.Id;
}
public int createYachtNameBillboard(string text, string subtitle, bool isWhite, Vector3 pos, Vector3 rot, Vector3 scale)
{
var bb = createBasicBillboard(pos, rot, scale);
bb.Type = 1;
bb.Arguments.Add("text", text);
bb.Arguments.Add("subtitle", subtitle);
bb.Arguments.Add("isWhite", isWhite);
return bb.Id;
}
public int createLargeYachtNameBillboard(string text, string subtitle, bool isWhite, Vector3 pos, Vector3 rot, Vector3 scale)
{
var bb = createBasicBillboard(pos, rot, scale);
bb.Type = 2;
bb.Arguments.Add("text", text);
bb.Arguments.Add("subtitle", subtitle);
bb.Arguments.Add("isWhite", isWhite);
return bb.Id;
}
public int createOrganizationName(string text, int style, int color, int font, Vector3 pos, Vector3 rot, Vector3 scale)
{
var bb = createBasicBillboard(pos, rot, scale);
bb.Type = 3;
bb.Arguments.Add("text", text);
bb.Arguments.Add("style", style);
bb.Arguments.Add("color", color);
bb.Arguments.Add("font", font);
return bb.Id;
}
public int createMugshotBoard(string name, string subtitle, string subtitle2, string title, int rank, Vector3 pos, Vector3 rot, Vector3 scale)
{
var bb = createBasicBillboard(pos, rot, scale);
bb.Type = 4;
bb.Arguments.Add("name", name);
bb.Arguments.Add("subtitle", subtitle);
bb.Arguments.Add("subtitle2", subtitle2);
bb.Arguments.Add("title", title);
bb.Arguments.Add("rank", rank);
return bb.Id;
}
public int createScrollingText(string text, int color, Vector3 pos, Vector3 rot, Vector3 scale)
{
var bb = createBasicBillboard(pos, rot, scale);
bb.Type = 5;
bb.Arguments.Add("text", text);
bb.Arguments.Add("color", color);
return bb.Id;
}
public int createMissionBillboard(string text, string subtitle, string percentage, bool isVerified, string players, int rp, int money, string time, Vector3 pos, Vector3 rot, Vector3 scale)
{
var bb = createBasicBillboard(pos, rot, scale);
bb.Type = 6;
bb.Arguments.Add("text", text);
bb.Arguments.Add("subtitle", subtitle);
bb.Arguments.Add("percentage", percentage);
bb.Arguments.Add("isVerified", isVerified);
bb.Arguments.Add("players", players);
bb.Arguments.Add("RP", rp);
bb.Arguments.Add("money", money);
bb.Arguments.Add("time", time);
return bb.Id;
}
public bool doesBillboardExist(int id)
{
return Billboards.ContainsKey(id);
}
public Billboard getBillboard(int id)
{
return Billboards[id];
}
public void setBillboardParams(int id, Vector3 pos, Vector3 rot, Vector3 scale)
{
Billboards[id].Position = pos;
Billboards[id].Rotation = rot;
Billboards[id].Scale = scale;
}
public void setBillboardArg(int id, string argname, object value)
{
if (Billboards[id].Arguments.ContainsKey(argname))
Billboards[id].Arguments[argname] = value;
else Billboards[id].Arguments.Add(argname, value);
}
public void refreshBillboard(int id)
{
foreach (var entity in Billboards[id].Collision.getAllEntities())
{
var player = API.getPlayerFromHandle(entity);
if (player == null) return;
sendBillboard(player, Billboards[id]);
}
}
public void deleteBillboard(int id)
{
foreach (var entity in Billboards[id].Collision.getAllEntities())
{
var player = API.getPlayerFromHandle(entity);
if (player == null) return;
player.triggerEvent("REMOVE_BILLBOARD", id);
}
API.deleteColShape(Billboards[id].Collision);
Billboards.Remove(id);
}
#if DEBUG_COMMANDS
// debug
[Command]
public void createmissionbb(Client sender, string text, string subtitle, string percentage, bool verified, string players, int rp, int money, string time = null)
{
createMissionBillboard(text, subtitle, percentage, verified, players, rp, money, time, sender.position, new Vector3(), new Vector3(6, 6, 1));
}
[Command]
public void createsbb(Client sender, string text)
{
createSimpleBillboard(text, sender.position + new Vector3(0, 0, 1), new Vector3(), new Vector3(3, 3, 3));
}
[Command(GreedyArg = true)]
public void createsbb2(Client sender, string text)
{
createSimpleBillboard(text, sender.position + new Vector3(0, 0, 1), new Vector3(), new Vector3(3, 3, 3));
}
[Command]
public void createybb(Client sender, string text, string subtitle = null)
{
createYachtNameBillboard(text, subtitle, true, sender.position + new Vector3(0, 0, 1), new Vector3(), new Vector3(3, 3, 3));
}
[Command]
public void createOrg(Client sender, string text, int style, int color, int font)
{
createOrganizationName(text, style, color,font, sender.position + new Vector3(0, 0, 1), new Vector3(), new Vector3(6, 6, 3));
}
[Command]
public void CreateBlimp(Client sender, string txt, int col)
{
createScrollingText(txt, col, sender.position + new Vector3(0, 0, 1), new Vector3(), new Vector3(6, 6, 3));
}
[Command]
public void createmugshot(Client sender, string txt, string sub, string sub2, string tit, int rank)
{
createMugshotBoard(txt, sub, sub2, tit, rank, sender.position + new Vector3(0, 0, 1), new Vector3(), new Vector3(6, 6, 3));
}
[Command]
public void newtest(Client sender)
{
createMissionBillboard("Paramedic", "FACTION", "", false, "", 0, 0, "", sender.position, new Vector3(), new Vector3(6, 6, 1));
}
#endif
}
public class Billboard
{
public int Id;
public int Type;
public Vector3 Position, Rotation, Scale;
public Dictionary<string, object> Arguments;
public ColShape Collision;
public Billboard()
{
Arguments = new Dictionary<string, object>();
}
}
| |
// 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.Network
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// LoadBalancerBackendAddressPoolsOperations operations.
/// </summary>
internal partial class LoadBalancerBackendAddressPoolsOperations : IServiceOperations<NetworkManagementClient>, ILoadBalancerBackendAddressPoolsOperations
{
/// <summary>
/// Initializes a new instance of the LoadBalancerBackendAddressPoolsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal LoadBalancerBackendAddressPoolsOperations(NetworkManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the NetworkManagementClient
/// </summary>
public NetworkManagementClient Client { get; private set; }
/// <summary>
/// Gets all the load balancer backed address pools.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the load balancer.
/// </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<BackendAddressPool>>> ListWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (loadBalancerName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "loadBalancerName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-08-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("resourceGroupName", resourceGroupName);
tracingParameters.Add("loadBalancerName", loadBalancerName);
tracingParameters.Add("apiVersion", apiVersion);
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.Network/loadBalancers/{loadBalancerName}/backendAddressPools").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{loadBalancerName}", System.Uri.EscapeDataString(loadBalancerName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
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);
}
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<BackendAddressPool>>();
_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<BackendAddressPool>>(_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>
/// Gets load balancer backend address pool.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the load balancer.
/// </param>
/// <param name='backendAddressPoolName'>
/// The name of the backend address pool.
/// </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<BackendAddressPool>> GetWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, string backendAddressPoolName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (loadBalancerName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "loadBalancerName");
}
if (backendAddressPoolName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "backendAddressPoolName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-08-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("resourceGroupName", resourceGroupName);
tracingParameters.Add("loadBalancerName", loadBalancerName);
tracingParameters.Add("backendAddressPoolName", backendAddressPoolName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/backendAddressPools/{backendAddressPoolName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{loadBalancerName}", System.Uri.EscapeDataString(loadBalancerName));
_url = _url.Replace("{backendAddressPoolName}", System.Uri.EscapeDataString(backendAddressPoolName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
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);
}
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<BackendAddressPool>();
_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<BackendAddressPool>(_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>
/// Gets all the load balancer backed address pools.
/// </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<BackendAddressPool>>> 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);
}
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<BackendAddressPool>>();
_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<BackendAddressPool>>(_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.
using System.Diagnostics;
using System.Dynamic.Utils;
namespace System.Linq.Expressions.Interpreter
{
internal abstract class NotEqualInstruction : Instruction
{
// Perf: EqualityComparer<T> but is 3/2 to 2 times slower.
private static Instruction s_reference, s_Boolean, s_SByte, s_Int16, s_Char, s_Int32, s_Int64, s_Byte, s_UInt16, s_UInt32, s_UInt64, s_Single, s_Double;
private static Instruction s_BooleanLiftedToNull, s_SByteLiftedToNull, s_Int16LiftedToNull, s_CharLiftedToNull, s_Int32LiftedToNull, s_Int64LiftedToNull, s_ByteLiftedToNull, s_UInt16LiftedToNull, s_UInt32LiftedToNull, s_UInt64LiftedToNull, s_SingleLiftedToNull, s_DoubleLiftedToNull;
public override int ConsumedStack => 2;
public override int ProducedStack => 1;
public override string InstructionName => "NotEqual";
private NotEqualInstruction() { }
private sealed class NotEqualBoolean : NotEqualInstruction
{
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null)
{
frame.Push(right != null);
}
else if (right == null)
{
frame.Push(true);
}
else
{
frame.Push((bool)left != (bool)right);
}
return 1;
}
}
private sealed class NotEqualSByte : NotEqualInstruction
{
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null)
{
frame.Push(right != null);
}
else if (right == null)
{
frame.Push(true);
}
else
{
frame.Push((sbyte)left != (sbyte)right);
}
return 1;
}
}
private sealed class NotEqualInt16 : NotEqualInstruction
{
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null)
{
frame.Push(right != null);
}
else if (right == null)
{
frame.Push(true);
}
else
{
frame.Push((short)left != (short)right);
}
return 1;
}
}
private sealed class NotEqualChar : NotEqualInstruction
{
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null)
{
frame.Push(right != null);
}
else if (right == null)
{
frame.Push(true);
}
else
{
frame.Push((char)left != (char)right);
}
return 1;
}
}
private sealed class NotEqualInt32 : NotEqualInstruction
{
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null)
{
frame.Push(right != null);
}
else if (right == null)
{
frame.Push(true);
}
else
{
frame.Push((int)left != (int)right);
}
return 1;
}
}
private sealed class NotEqualInt64 : NotEqualInstruction
{
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null)
{
frame.Push(right != null);
}
else if (right == null)
{
frame.Push(true);
}
else
{
frame.Push((long)left != (long)right);
}
return 1;
}
}
private sealed class NotEqualByte : NotEqualInstruction
{
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null)
{
frame.Push(right != null);
}
else if (right == null)
{
frame.Push(true);
}
else
{
frame.Push((byte)left != (byte)right);
}
return 1;
}
}
private sealed class NotEqualUInt16 : NotEqualInstruction
{
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null)
{
frame.Push(right != null);
}
else if (right == null)
{
frame.Push(true);
}
else
{
frame.Push((ushort)left != (ushort)right);
}
return 1;
}
}
private sealed class NotEqualUInt32 : NotEqualInstruction
{
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null)
{
frame.Push(right != null);
}
else if (right == null)
{
frame.Push(true);
}
else
{
frame.Push((uint)left != (uint)right);
}
return 1;
}
}
private sealed class NotEqualUInt64 : NotEqualInstruction
{
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null)
{
frame.Push(right != null);
}
else if (right == null)
{
frame.Push(true);
}
else
{
frame.Push((ulong)left != (ulong)right);
}
return 1;
}
}
private sealed class NotEqualSingle : NotEqualInstruction
{
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null)
{
frame.Push(right != null);
}
else if (right == null)
{
frame.Push(true);
}
else
{
frame.Push((float)left != (float)right);
}
return 1;
}
}
private sealed class NotEqualDouble : NotEqualInstruction
{
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null)
{
frame.Push(right != null);
}
else if (right == null)
{
frame.Push(true);
}
else
{
frame.Push((double)left != (double)right);
}
return 1;
}
}
private sealed class NotEqualReference : NotEqualInstruction
{
public override int Run(InterpretedFrame frame)
{
frame.Push(frame.Pop() != frame.Pop());
return 1;
}
}
private sealed class NotEqualBooleanLiftedToNull : NotEqualInstruction
{
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null || right == null)
{
frame.Push(null);
}
else
{
frame.Push((bool)left != (bool)right);
}
return 1;
}
}
private sealed class NotEqualSByteLiftedToNull : NotEqualInstruction
{
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null || right == null)
{
frame.Push(null);
}
else
{
frame.Push((sbyte)left != (sbyte)right);
}
return 1;
}
}
private sealed class NotEqualInt16LiftedToNull : NotEqualInstruction
{
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null || right == null)
{
frame.Push(null);
}
else
{
frame.Push((short)left != (short)right);
}
return 1;
}
}
private sealed class NotEqualCharLiftedToNull : NotEqualInstruction
{
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null || right == null)
{
frame.Push(null);
}
else
{
frame.Push((char)left != (char)right);
}
return 1;
}
}
private sealed class NotEqualInt32LiftedToNull : NotEqualInstruction
{
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null || right == null)
{
frame.Push(null);
}
else
{
frame.Push((int)left != (int)right);
}
return 1;
}
}
private sealed class NotEqualInt64LiftedToNull : NotEqualInstruction
{
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null || right == null)
{
frame.Push(null);
}
else
{
frame.Push((long)left != (long)right);
}
return 1;
}
}
private sealed class NotEqualByteLiftedToNull : NotEqualInstruction
{
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null || right == null)
{
frame.Push(null);
}
else
{
frame.Push((byte)left != (byte)right);
}
return 1;
}
}
private sealed class NotEqualUInt16LiftedToNull : NotEqualInstruction
{
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null || right == null)
{
frame.Push(null);
}
else
{
frame.Push((ushort)left != (ushort)right);
}
return 1;
}
}
private sealed class NotEqualUInt32LiftedToNull : NotEqualInstruction
{
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null || right == null)
{
frame.Push(null);
}
else
{
frame.Push((uint)left != (uint)right);
}
return 1;
}
}
private sealed class NotEqualUInt64LiftedToNull : NotEqualInstruction
{
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null || right == null)
{
frame.Push(null);
}
else
{
frame.Push((ulong)left != (ulong)right);
}
return 1;
}
}
private sealed class NotEqualSingleLiftedToNull : NotEqualInstruction
{
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null || right == null)
{
frame.Push(null);
}
else
{
frame.Push((float)left != (float)right);
}
return 1;
}
}
private sealed class NotEqualDoubleLiftedToNull : NotEqualInstruction
{
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null || right == null)
{
frame.Push(null);
}
else
{
frame.Push((double)left != (double)right);
}
return 1;
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
public static Instruction Create(Type type, bool liftedToNull)
{
if (liftedToNull)
{
switch (type.GetNonNullableType().GetTypeCode())
{
case TypeCode.Boolean: return s_BooleanLiftedToNull ?? (s_BooleanLiftedToNull = new NotEqualBooleanLiftedToNull());
case TypeCode.SByte: return s_SByteLiftedToNull ?? (s_SByteLiftedToNull = new NotEqualSByteLiftedToNull());
case TypeCode.Int16: return s_Int16LiftedToNull ?? (s_Int16LiftedToNull = new NotEqualInt16LiftedToNull());
case TypeCode.Char: return s_CharLiftedToNull ?? (s_CharLiftedToNull = new NotEqualCharLiftedToNull());
case TypeCode.Int32: return s_Int32LiftedToNull ?? (s_Int32LiftedToNull = new NotEqualInt32LiftedToNull());
case TypeCode.Int64: return s_Int64LiftedToNull ?? (s_Int64LiftedToNull = new NotEqualInt64LiftedToNull());
case TypeCode.Byte: return s_ByteLiftedToNull ?? (s_ByteLiftedToNull = new NotEqualByteLiftedToNull());
case TypeCode.UInt16: return s_UInt16LiftedToNull ?? (s_UInt16LiftedToNull = new NotEqualUInt16LiftedToNull());
case TypeCode.UInt32: return s_UInt32LiftedToNull ?? (s_UInt32LiftedToNull = new NotEqualUInt32LiftedToNull());
case TypeCode.UInt64: return s_UInt64LiftedToNull ?? (s_UInt64LiftedToNull = new NotEqualUInt64LiftedToNull());
case TypeCode.Single: return s_SingleLiftedToNull ?? (s_SingleLiftedToNull = new NotEqualSingleLiftedToNull());
default:
Debug.Assert(type.GetNonNullableType().GetTypeCode() == TypeCode.Double);
return s_DoubleLiftedToNull ?? (s_DoubleLiftedToNull = new NotEqualDoubleLiftedToNull());
}
}
else
{
switch (type.GetNonNullableType().GetTypeCode())
{
case TypeCode.Boolean: return s_Boolean ?? (s_Boolean = new NotEqualBoolean());
case TypeCode.SByte: return s_SByte ?? (s_SByte = new NotEqualSByte());
case TypeCode.Int16: return s_Int16 ?? (s_Int16 = new NotEqualInt16());
case TypeCode.Char: return s_Char ?? (s_Char = new NotEqualChar());
case TypeCode.Int32: return s_Int32 ?? (s_Int32 = new NotEqualInt32());
case TypeCode.Int64: return s_Int64 ?? (s_Int64 = new NotEqualInt64());
case TypeCode.Byte: return s_Byte ?? (s_Byte = new NotEqualByte());
case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new NotEqualUInt16());
case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new NotEqualUInt32());
case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new NotEqualUInt64());
case TypeCode.Single: return s_Single ?? (s_Single = new NotEqualSingle());
case TypeCode.Double: return s_Double ?? (s_Double = new NotEqualDouble());
default:
// Nullable only valid if one operand is constant null, so this assert is slightly too broad.
Debug.Assert(type.IsNullableOrReferenceType());
return s_reference ?? (s_reference = new NotEqualReference());
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Xunit;
// TODO: Remove these extension methods when the actual methods are available on String in System.Runtime.dll
internal static class TemporaryStringSplitExtensions
{
public static string[] Split(this string value, char separator)
{
return value.Split(new[] { separator });
}
public static string[] Split(this string value, char separator, StringSplitOptions options)
{
return value.Split(new[] { separator }, options);
}
public static string[] Split(this string value, char separator, int count, StringSplitOptions options)
{
return value.Split(new[] { separator }, count, options);
}
public static string[] Split(this string value, string separator)
{
return value.Split(new[] { separator }, StringSplitOptions.None);
}
public static string[] Split(this string value, string separator, StringSplitOptions options)
{
return value.Split(new[] { separator }, options);
}
public static string[] Split(this string value, string separator, int count, StringSplitOptions options)
{
return value.Split(new[] { separator }, count, options);
}
}
public static class StringSplitTests
{
[Fact]
public static void TestSplitInvalidCount()
{
const string value = "a,b";
const int count = -1;
const StringSplitOptions options = StringSplitOptions.None;
Assert.Throws<ArgumentOutOfRangeException>(() => value.Split(',', count, options));
Assert.Throws<ArgumentOutOfRangeException>(() => value.Split(new[] { ',' }, count));
Assert.Throws<ArgumentOutOfRangeException>(() => value.Split(new[] { ',' }, count, options));
Assert.Throws<ArgumentOutOfRangeException>(() => value.Split(",", count, options));
Assert.Throws<ArgumentOutOfRangeException>(() => value.Split(new[] { "," }, count, options));
}
[Fact]
public static void TestSplitInvalidOptions()
{
const string value = "a,b";
const int count = int.MaxValue;
const StringSplitOptions optionsTooLow = StringSplitOptions.None - 1;
const StringSplitOptions optionsTooHigh = StringSplitOptions.RemoveEmptyEntries + 1;
Assert.Throws<ArgumentException>(() => value.Split(',', optionsTooLow));
Assert.Throws<ArgumentException>(() => value.Split(',', optionsTooHigh));
Assert.Throws<ArgumentException>(() => value.Split(',', count, optionsTooLow));
Assert.Throws<ArgumentException>(() => value.Split(',', count, optionsTooHigh));
Assert.Throws<ArgumentException>(() => value.Split(new[] { ',' }, optionsTooLow));
Assert.Throws<ArgumentException>(() => value.Split(new[] { ',' }, optionsTooHigh));
Assert.Throws<ArgumentException>(() => value.Split(new[] { ',' }, count, optionsTooLow));
Assert.Throws<ArgumentException>(() => value.Split(new[] { ',' }, count, optionsTooHigh));
Assert.Throws<ArgumentException>(() => value.Split(",", optionsTooLow));
Assert.Throws<ArgumentException>(() => value.Split(",", optionsTooHigh));
Assert.Throws<ArgumentException>(() => value.Split(",", count, optionsTooLow));
Assert.Throws<ArgumentException>(() => value.Split(",", count, optionsTooHigh));
Assert.Throws<ArgumentException>(() => value.Split(new[] { "," }, optionsTooLow));
Assert.Throws<ArgumentException>(() => value.Split(new[] { "," }, optionsTooHigh));
Assert.Throws<ArgumentException>(() => value.Split(new[] { "," }, count, optionsTooLow));
Assert.Throws<ArgumentException>(() => value.Split(new[] { "," }, count, optionsTooHigh));
}
[Fact]
public static void TestSplitZeroCountEmptyResult()
{
const string value = "a,b";
const int count = 0;
const StringSplitOptions options = StringSplitOptions.None;
string[] expected = new string[0];
Assert.Equal(expected, value.Split(',', count, options));
Assert.Equal(expected, value.Split(new[] { ',' }, count));
Assert.Equal(expected, value.Split(new[] { ',' }, count, options));
Assert.Equal(expected, value.Split(",", count, options));
Assert.Equal(expected, value.Split(new[] { "," }, count, options));
}
[Fact]
public static void TestSplitEmptyValueWithRemoveEmptyEntriesOptionEmptyResult()
{
string value = string.Empty;
const int count = int.MaxValue;
const StringSplitOptions options = StringSplitOptions.RemoveEmptyEntries;
string[] expected = new string[0];
Assert.Equal(expected, value.Split(',', options));
Assert.Equal(expected, value.Split(',', count, options));
Assert.Equal(expected, value.Split(new[] { ',' }, options));
Assert.Equal(expected, value.Split(new[] { ',' }, count, options));
Assert.Equal(expected, value.Split(",", options));
Assert.Equal(expected, value.Split(",", count, options));
Assert.Equal(expected, value.Split(new[] { "," }, options));
Assert.Equal(expected, value.Split(new[] { "," }, count, options));
}
[Fact]
public static void TestSplitOneCountSingleResult()
{
const string value = "a,b";
const int count = 1;
const StringSplitOptions options = StringSplitOptions.None;
string[] expected = new[] { value };
Assert.Equal(expected, value.Split(',', count, options));
Assert.Equal(expected, value.Split(new[] { ',' }, count));
Assert.Equal(expected, value.Split(new[] { ',' }, count, options));
Assert.Equal(expected, value.Split(",", count, options));
Assert.Equal(expected, value.Split(new[] { "," }, count, options));
}
[Fact]
public static void TestSplitNoMatchSingleResult()
{
const string value = "a b";
const int count = int.MaxValue;
const StringSplitOptions options = StringSplitOptions.None;
string[] expected = new[] { value };
Assert.Equal(expected, value.Split(','));
Assert.Equal(expected, value.Split(',', options));
Assert.Equal(expected, value.Split(',', count, options));
Assert.Equal(expected, value.Split(new[] { ',' }));
Assert.Equal(expected, value.Split(new[] { ',' }, options));
Assert.Equal(expected, value.Split(new[] { ',' }, count));
Assert.Equal(expected, value.Split(new[] { ',' }, count, options));
Assert.Equal(expected, value.Split(","));
Assert.Equal(expected, value.Split(",", options));
Assert.Equal(expected, value.Split(",", count, options));
Assert.Equal(expected, value.Split(new[] { "," }, options));
Assert.Equal(expected, value.Split(new[] { "," }, count, options));
}
private const int M = int.MaxValue;
[Theory]
[InlineData("", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("", ',', 1, StringSplitOptions.None, new[] { "" })]
[InlineData("", ',', 2, StringSplitOptions.None, new[] { "" })]
[InlineData("", ',', 3, StringSplitOptions.None, new[] { "" })]
[InlineData("", ',', 4, StringSplitOptions.None, new[] { "" })]
[InlineData("", ',', M, StringSplitOptions.None, new[] { "" })]
[InlineData("", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("", ',', 1, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("", ',', 2, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("", ',', 3, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("", ',', 4, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("", ',', M, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData(",", ',', 1, StringSplitOptions.None, new[] { "," })]
[InlineData(",", ',', 2, StringSplitOptions.None, new[] { "", "" })]
[InlineData(",", ',', 3, StringSplitOptions.None, new[] { "", "" })]
[InlineData(",", ',', 4, StringSplitOptions.None, new[] { "", "" })]
[InlineData(",", ',', M, StringSplitOptions.None, new[] { "", "" })]
[InlineData(",", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "," })]
[InlineData(",", ',', 2, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",", ',', 3, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",", ',', 4, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",", ',', M, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",,", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData(",,", ',', 1, StringSplitOptions.None, new[] { ",," })]
[InlineData(",,", ',', 2, StringSplitOptions.None, new[] { "", ",", })]
[InlineData(",,", ',', 3, StringSplitOptions.None, new[] { "", "", "" })]
[InlineData(",,", ',', 4, StringSplitOptions.None, new[] { "", "", "" })]
[InlineData(",,", ',', M, StringSplitOptions.None, new[] { "", "", "" })]
[InlineData(",,", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",,", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { ",," })]
[InlineData(",,", ',', 2, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",,", ',', 3, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",,", ',', 4, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",,", ',', M, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("ab", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("ab", ',', 1, StringSplitOptions.None, new[] { "ab" })]
[InlineData("ab", ',', 2, StringSplitOptions.None, new[] { "ab" })]
[InlineData("ab", ',', 3, StringSplitOptions.None, new[] { "ab" })]
[InlineData("ab", ',', 4, StringSplitOptions.None, new[] { "ab" })]
[InlineData("ab", ',', M, StringSplitOptions.None, new[] { "ab" })]
[InlineData("ab", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("ab", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "ab" })]
[InlineData("ab", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "ab" })]
[InlineData("ab", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "ab" })]
[InlineData("ab", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "ab" })]
[InlineData("ab", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "ab" })]
[InlineData("a,b", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("a,b", ',', 1, StringSplitOptions.None, new[] { "a,b" })]
[InlineData("a,b", ',', 2, StringSplitOptions.None, new[] { "a", "b" })]
[InlineData("a,b", ',', 3, StringSplitOptions.None, new[] { "a", "b" })]
[InlineData("a,b", ',', 4, StringSplitOptions.None, new[] { "a", "b" })]
[InlineData("a,b", ',', M, StringSplitOptions.None, new[] { "a", "b" })]
[InlineData("a,b", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("a,b", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "a,b" })]
[InlineData("a,b", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b" })]
[InlineData("a,b", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b" })]
[InlineData("a,b", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b" })]
[InlineData("a,b", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b" })]
[InlineData("a,", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("a,", ',', 1, StringSplitOptions.None, new[] { "a," })]
[InlineData("a,", ',', 2, StringSplitOptions.None, new[] { "a", "" })]
[InlineData("a,", ',', 3, StringSplitOptions.None, new[] { "a", "" })]
[InlineData("a,", ',', 4, StringSplitOptions.None, new[] { "a", "" })]
[InlineData("a,", ',', M, StringSplitOptions.None, new[] { "a", "" })]
[InlineData("a,", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("a,", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "a," })]
[InlineData("a,", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "a" })]
[InlineData("a,", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "a" })]
[InlineData("a,", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "a" })]
[InlineData("a,", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "a" })]
[InlineData(",b", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData(",b", ',', 1, StringSplitOptions.None, new[] { ",b" })]
[InlineData(",b", ',', 2, StringSplitOptions.None, new[] { "", "b" })]
[InlineData(",b", ',', 3, StringSplitOptions.None, new[] { "", "b" })]
[InlineData(",b", ',', 4, StringSplitOptions.None, new[] { "", "b" })]
[InlineData(",b", ',', M, StringSplitOptions.None, new[] { "", "b" })]
[InlineData(",b", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",b", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { ",b" })]
[InlineData(",b", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "b" })]
[InlineData(",b", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "b" })]
[InlineData(",b", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "b" })]
[InlineData(",b", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "b" })]
[InlineData(",a,b", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData(",a,b", ',', 1, StringSplitOptions.None, new[] { ",a,b" })]
[InlineData(",a,b", ',', 2, StringSplitOptions.None, new[] { "", "a,b" })]
[InlineData(",a,b", ',', 3, StringSplitOptions.None, new[] { "", "a", "b" })]
[InlineData(",a,b", ',', 4, StringSplitOptions.None, new[] { "", "a", "b" })]
[InlineData(",a,b", ',', M, StringSplitOptions.None, new[] { "", "a", "b" })]
[InlineData(",a,b", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",a,b", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { ",a,b" })]
[InlineData(",a,b", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b" })]
[InlineData(",a,b", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b" })]
[InlineData(",a,b", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b" })]
[InlineData(",a,b", ',', 5, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b" })]
[InlineData("a,b,", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("a,b,", ',', 1, StringSplitOptions.None, new[] { "a,b," })]
[InlineData("a,b,", ',', 2, StringSplitOptions.None, new[] { "a", "b,", })]
[InlineData("a,b,", ',', 3, StringSplitOptions.None, new[] { "a", "b", "" })]
[InlineData("a,b,", ',', 4, StringSplitOptions.None, new[] { "a", "b", "" })]
[InlineData("a,b,", ',', M, StringSplitOptions.None, new[] { "a", "b", "" })]
[InlineData("a,b,", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("a,b,", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "a,b," })]
[InlineData("a,b,", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b," })]
[InlineData("a,b,", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b" })]
[InlineData("a,b,", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b" })]
[InlineData("a,b,", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b" })]
[InlineData("a,b,c", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("a,b,c", ',', 1, StringSplitOptions.None, new[] { "a,b,c" })]
[InlineData("a,b,c", ',', 2, StringSplitOptions.None, new[] { "a", "b,c" })]
[InlineData("a,b,c", ',', 3, StringSplitOptions.None, new[] { "a", "b", "c" })]
[InlineData("a,b,c", ',', 4, StringSplitOptions.None, new[] { "a", "b", "c" })]
[InlineData("a,b,c", ',', M, StringSplitOptions.None, new[] { "a", "b", "c" })]
[InlineData("a,b,c", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("a,b,c", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "a,b,c" })]
[InlineData("a,b,c", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b,c", })]
[InlineData("a,b,c", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c" })]
[InlineData("a,b,c", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c" })]
[InlineData("a,b,c", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c" })]
[InlineData("a,,c", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("a,,c", ',', 1, StringSplitOptions.None, new[] { "a,,c" })]
[InlineData("a,,c", ',', 2, StringSplitOptions.None, new[] { "a", ",c", })]
[InlineData("a,,c", ',', 3, StringSplitOptions.None, new[] { "a", "", "c" })]
[InlineData("a,,c", ',', 4, StringSplitOptions.None, new[] { "a", "", "c" })]
[InlineData("a,,c", ',', M, StringSplitOptions.None, new[] { "a", "", "c" })]
[InlineData("a,,c", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("a,,c", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "a,,c" })]
[InlineData("a,,c", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "c", })]
[InlineData("a,,c", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "c" })]
[InlineData("a,,c", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "c" })]
[InlineData("a,,c", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "c" })]
[InlineData(",a,b,c", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData(",a,b,c", ',', 1, StringSplitOptions.None, new[] { ",a,b,c" })]
[InlineData(",a,b,c", ',', 2, StringSplitOptions.None, new[] { "", "a,b,c" })]
[InlineData(",a,b,c", ',', 3, StringSplitOptions.None, new[] { "", "a", "b,c" })]
[InlineData(",a,b,c", ',', 4, StringSplitOptions.None, new[] { "", "a", "b", "c" })]
[InlineData(",a,b,c", ',', M, StringSplitOptions.None, new[] { "", "a", "b", "c" })]
[InlineData(",a,b,c", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",a,b,c", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { ",a,b,c" })]
[InlineData(",a,b,c", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b,c", })]
[InlineData(",a,b,c", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c" })]
[InlineData(",a,b,c", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c" })]
[InlineData(",a,b,c", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c" })]
[InlineData("a,b,c,", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("a,b,c,", ',', 1, StringSplitOptions.None, new[] { "a,b,c," })]
[InlineData("a,b,c,", ',', 2, StringSplitOptions.None, new[] { "a", "b,c," })]
[InlineData("a,b,c,", ',', 3, StringSplitOptions.None, new[] { "a", "b", "c,", })]
[InlineData("a,b,c,", ',', 4, StringSplitOptions.None, new[] { "a", "b", "c", "" })]
[InlineData("a,b,c,", ',', M, StringSplitOptions.None, new[] { "a", "b", "c", "" })]
[InlineData("a,b,c,", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("a,b,c,", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "a,b,c," })]
[InlineData("a,b,c,", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b,c,", })]
[InlineData("a,b,c,", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c," })]
[InlineData("a,b,c,", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c" })]
[InlineData("a,b,c,", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c" })]
[InlineData(",a,b,c,", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData(",a,b,c,", ',', 1, StringSplitOptions.None, new[] { ",a,b,c," })]
[InlineData(",a,b,c,", ',', 2, StringSplitOptions.None, new[] { "", "a,b,c," })]
[InlineData(",a,b,c,", ',', 3, StringSplitOptions.None, new[] { "", "a", "b,c," })]
[InlineData(",a,b,c,", ',', 4, StringSplitOptions.None, new[] { "", "a", "b", "c," })]
[InlineData(",a,b,c,", ',', M, StringSplitOptions.None, new[] { "", "a", "b", "c", "" })]
[InlineData(",a,b,c,", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",a,b,c,", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { ",a,b,c," })]
[InlineData(",a,b,c,", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b,c," })]
[InlineData(",a,b,c,", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c," })]
[InlineData(",a,b,c,", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c" })]
[InlineData(",a,b,c,", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c" })]
[InlineData("first,second", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("first,second", ',', 1, StringSplitOptions.None, new[] { "first,second" })]
[InlineData("first,second", ',', 2, StringSplitOptions.None, new[] { "first", "second" })]
[InlineData("first,second", ',', 3, StringSplitOptions.None, new[] { "first", "second" })]
[InlineData("first,second", ',', 4, StringSplitOptions.None, new[] { "first", "second" })]
[InlineData("first,second", ',', M, StringSplitOptions.None, new[] { "first", "second" })]
[InlineData("first,second", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("first,second", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "first,second" })]
[InlineData("first,second", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second" })]
[InlineData("first,second", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second" })]
[InlineData("first,second", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second" })]
[InlineData("first,second", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second" })]
[InlineData("first,", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("first,", ',', 1, StringSplitOptions.None, new[] { "first," })]
[InlineData("first,", ',', 2, StringSplitOptions.None, new[] { "first", "" })]
[InlineData("first,", ',', 3, StringSplitOptions.None, new[] { "first", "" })]
[InlineData("first,", ',', 4, StringSplitOptions.None, new[] { "first", "" })]
[InlineData("first,", ',', M, StringSplitOptions.None, new[] { "first", "" })]
[InlineData("first,", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("first,", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "first," })]
[InlineData("first,", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "first" })]
[InlineData("first,", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "first" })]
[InlineData("first,", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "first" })]
[InlineData("first,", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "first" })]
[InlineData(",second", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData(",second", ',', 1, StringSplitOptions.None, new[] { ",second" })]
[InlineData(",second", ',', 2, StringSplitOptions.None, new[] { "", "second" })]
[InlineData(",second", ',', 3, StringSplitOptions.None, new[] { "", "second" })]
[InlineData(",second", ',', 4, StringSplitOptions.None, new[] { "", "second" })]
[InlineData(",second", ',', M, StringSplitOptions.None, new[] { "", "second" })]
[InlineData(",second", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",second", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { ",second" })]
[InlineData(",second", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "second" })]
[InlineData(",second", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "second" })]
[InlineData(",second", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "second" })]
[InlineData(",second", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "second" })]
[InlineData(",first,second", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData(",first,second", ',', 1, StringSplitOptions.None, new[] { ",first,second" })]
[InlineData(",first,second", ',', 2, StringSplitOptions.None, new[] { "", "first,second" })]
[InlineData(",first,second", ',', 3, StringSplitOptions.None, new[] { "", "first", "second" })]
[InlineData(",first,second", ',', 4, StringSplitOptions.None, new[] { "", "first", "second" })]
[InlineData(",first,second", ',', M, StringSplitOptions.None, new[] { "", "first", "second" })]
[InlineData(",first,second", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",first,second", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { ",first,second" })]
[InlineData(",first,second", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second" })]
[InlineData(",first,second", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second" })]
[InlineData(",first,second", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second" })]
[InlineData(",first,second", ',', 5, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second" })]
[InlineData("first,second,", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("first,second,", ',', 1, StringSplitOptions.None, new[] { "first,second," })]
[InlineData("first,second,", ',', 2, StringSplitOptions.None, new[] { "first", "second,", })]
[InlineData("first,second,", ',', 3, StringSplitOptions.None, new[] { "first", "second", "" })]
[InlineData("first,second,", ',', 4, StringSplitOptions.None, new[] { "first", "second", "" })]
[InlineData("first,second,", ',', M, StringSplitOptions.None, new[] { "first", "second", "" })]
[InlineData("first,second,", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("first,second,", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "first,second," })]
[InlineData("first,second,", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second," })]
[InlineData("first,second,", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second" })]
[InlineData("first,second,", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second" })]
[InlineData("first,second,", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second" })]
[InlineData("first,second,third", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("first,second,third", ',', 1, StringSplitOptions.None, new[] { "first,second,third" })]
[InlineData("first,second,third", ',', 2, StringSplitOptions.None, new[] { "first", "second,third" })]
[InlineData("first,second,third", ',', 3, StringSplitOptions.None, new[] { "first", "second", "third" })]
[InlineData("first,second,third", ',', 4, StringSplitOptions.None, new[] { "first", "second", "third" })]
[InlineData("first,second,third", ',', M, StringSplitOptions.None, new[] { "first", "second", "third" })]
[InlineData("first,second,third", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("first,second,third", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "first,second,third" })]
[InlineData("first,second,third", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second,third", })]
[InlineData("first,second,third", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third" })]
[InlineData("first,second,third", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third" })]
[InlineData("first,second,third", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third" })]
[InlineData("first,,third", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("first,,third", ',', 1, StringSplitOptions.None, new[] { "first,,third" })]
[InlineData("first,,third", ',', 2, StringSplitOptions.None, new[] { "first", ",third", })]
[InlineData("first,,third", ',', 3, StringSplitOptions.None, new[] { "first", "", "third" })]
[InlineData("first,,third", ',', 4, StringSplitOptions.None, new[] { "first", "", "third" })]
[InlineData("first,,third", ',', M, StringSplitOptions.None, new[] { "first", "", "third" })]
[InlineData("first,,third", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("first,,third", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "first,,third" })]
[InlineData("first,,third", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "third", })]
[InlineData("first,,third", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "third" })]
[InlineData("first,,third", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "third" })]
[InlineData("first,,third", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "third" })]
[InlineData(",first,second,third", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData(",first,second,third", ',', 1, StringSplitOptions.None, new[] { ",first,second,third" })]
[InlineData(",first,second,third", ',', 2, StringSplitOptions.None, new[] { "", "first,second,third" })]
[InlineData(",first,second,third", ',', 3, StringSplitOptions.None, new[] { "", "first", "second,third" })]
[InlineData(",first,second,third", ',', 4, StringSplitOptions.None, new[] { "", "first", "second", "third" })]
[InlineData(",first,second,third", ',', M, StringSplitOptions.None, new[] { "", "first", "second", "third" })]
[InlineData(",first,second,third", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",first,second,third", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { ",first,second,third" })]
[InlineData(",first,second,third", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second,third", })]
[InlineData(",first,second,third", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third" })]
[InlineData(",first,second,third", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third" })]
[InlineData(",first,second,third", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third" })]
[InlineData("first,second,third,", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("first,second,third,", ',', 1, StringSplitOptions.None, new[] { "first,second,third," })]
[InlineData("first,second,third,", ',', 2, StringSplitOptions.None, new[] { "first", "second,third," })]
[InlineData("first,second,third,", ',', 3, StringSplitOptions.None, new[] { "first", "second", "third,", })]
[InlineData("first,second,third,", ',', 4, StringSplitOptions.None, new[] { "first", "second", "third", "" })]
[InlineData("first,second,third,", ',', M, StringSplitOptions.None, new[] { "first", "second", "third", "" })]
[InlineData("first,second,third,", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("first,second,third,", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "first,second,third," })]
[InlineData("first,second,third,", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second,third,", })]
[InlineData("first,second,third,", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third," })]
[InlineData("first,second,third,", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third" })]
[InlineData("first,second,third,", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third" })]
[InlineData(",first,second,third,", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData(",first,second,third,", ',', 1, StringSplitOptions.None, new[] { ",first,second,third," })]
[InlineData(",first,second,third,", ',', 2, StringSplitOptions.None, new[] { "", "first,second,third," })]
[InlineData(",first,second,third,", ',', 3, StringSplitOptions.None, new[] { "", "first", "second,third," })]
[InlineData(",first,second,third,", ',', 4, StringSplitOptions.None, new[] { "", "first", "second", "third," })]
[InlineData(",first,second,third,", ',', M, StringSplitOptions.None, new[] { "", "first", "second", "third", "" })]
[InlineData(",first,second,third,", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",first,second,third,", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { ",first,second,third," })]
[InlineData(",first,second,third,", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second,third," })]
[InlineData(",first,second,third,", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third," })]
[InlineData(",first,second,third,", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third" })]
[InlineData(",first,second,third,", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third" })]
[InlineData("first,second,third", ' ', M, StringSplitOptions.None, new[] { "first,second,third" })]
[InlineData("first,second,third", ' ', M, StringSplitOptions.RemoveEmptyEntries, new[] { "first,second,third" })]
[InlineData("Foo Bar Baz", ' ', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "Foo", "Bar Baz" })]
[InlineData("Foo Bar Baz", ' ', M, StringSplitOptions.None, new[] { "Foo", "Bar", "Baz" })]
public static void TestSplitCharSeparator(string value, char separator, int count, StringSplitOptions options, string[] expected)
{
Assert.Equal(expected, value.Split(separator, count, options));
Assert.Equal(expected, value.Split(new[] { separator }, count, options));
Assert.Equal(expected, value.Split(separator.ToString(), count, options));
Assert.Equal(expected, value.Split(new[] { separator.ToString() }, count, options));
}
[Theory]
[InlineData("a,b,c", null, M, StringSplitOptions.None, new[] { "a,b,c" })]
[InlineData("a,b,c", "", M, StringSplitOptions.None, new[] { "a,b,c" })]
[InlineData("aaabaaabaaa", "aa", M, StringSplitOptions.None, new[] { "", "ab", "ab", "a" })]
[InlineData("aaabaaabaaa", "aa", M, StringSplitOptions.RemoveEmptyEntries, new[] { "ab", "ab", "a" })]
[InlineData("this, is, a, string, with some spaces", ", ", M, StringSplitOptions.None, new[] { "this", "is", "a", "string", "with some spaces" })]
public static void TestSplitStringSeparator(string value, string separator, int count, StringSplitOptions options, string[] expected)
{
Assert.Equal(expected, value.Split(separator, count, options));
Assert.Equal(expected, value.Split(new[] { separator }, count, options));
}
[Theory]
[InlineData("a b c", null, M, StringSplitOptions.None, new[] { "a", "b", "c" })]
[InlineData("a b c", new char[0], M, StringSplitOptions.None, new[] { "a", "b", "c" })]
[InlineData("a,b,c", null, M, StringSplitOptions.None, new[] { "a,b,c" })]
[InlineData("a,b,c", new char[0], M, StringSplitOptions.None, new[] { "a,b,c" })]
[InlineData("this, is, a, string, with some spaces", new[] { ' ', ',' }, M, StringSplitOptions.None, new[] { "this", "", "is", "", "a", "", "string", "", "with", "some", "spaces" })]
[InlineData("this, is, a, string, with some spaces", new[] { ',', ' ' }, M, StringSplitOptions.None, new[] { "this", "", "is", "", "a", "", "string", "", "with", "some", "spaces" })]
[InlineData("this, is, a, string, with some spaces", new[] { ' ', ',' }, M, StringSplitOptions.RemoveEmptyEntries, new[] { "this", "is", "a", "string", "with", "some", "spaces" })]
[InlineData("this, is, a, string, with some spaces", new[] { ',', ' ' }, M, StringSplitOptions.RemoveEmptyEntries, new[] { "this", "is", "a", "string", "with", "some", "spaces" })]
public static void TestSplitCharArraySeparator(string value, char[] separators, int count, StringSplitOptions options, string[] expected)
{
Assert.Equal(expected, value.Split(separators, count, options));
Assert.Equal(expected, value.Split(ToStringArray(separators), count, options));
}
[Theory]
[InlineData("a b c", null, M, StringSplitOptions.None, new[] { "a", "b", "c" })]
[InlineData("a b c", new string[0], M, StringSplitOptions.None, new[] { "a", "b", "c" })]
[InlineData("a,b,c", null, M, StringSplitOptions.None, new[] { "a,b,c" })]
[InlineData("a,b,c", new string[0], M, StringSplitOptions.None, new[] { "a,b,c" })]
[InlineData("a,b,c", new string[] { null }, M, StringSplitOptions.None, new[] { "a,b,c" })]
[InlineData("a,b,c", new string[] { "" }, M, StringSplitOptions.None, new[] { "a,b,c" })]
[InlineData("this, is, a, string, with some spaces", new[] { " ", ", " }, M, StringSplitOptions.None, new[] { "this", "is", "a", "string", "with", "some", "spaces" })]
[InlineData("this, is, a, string, with some spaces", new[] { ", ", " " }, M, StringSplitOptions.None, new[] { "this", "is", "a", "string", "with", "some", "spaces" })]
[InlineData("this, is, a, string, with some spaces", new[] { " ", ", " }, M, StringSplitOptions.RemoveEmptyEntries, new[] { "this", "is", "a", "string", "with", "some", "spaces" })]
[InlineData("this, is, a, string, with some spaces", new[] { ", ", " " }, M, StringSplitOptions.RemoveEmptyEntries, new[] { "this", "is", "a", "string", "with", "some", "spaces" })]
public static void TestSplitStringArraySeparator(string value, string[] separators, int count, StringSplitOptions options, string[] expected)
{
Assert.Equal(expected, value.Split(separators, count, options));
}
private static string[] ToStringArray(char[] source)
{
if (source == null)
return null;
string[] result = new string[source.Length];
for (int i = 0; i < source.Length; i++)
{
result[i] = source[i].ToString();
}
return result;
}
}
| |
/*!
@file
@author Generate utility by Albert Semenov
@date 01/2009
@module
*/
using System;
using System.Runtime.InteropServices;
namespace MyGUI.Sharp
{
public partial class Widget :
BaseWidget
{
#region Widget
protected override string GetWidgetType() { return "Widget"; }
internal static BaseWidget RequestWrapWidget(BaseWidget _parent, IntPtr _widget)
{
Widget widget = new Widget();
widget.WrapWidget(_parent, _widget);
return widget;
}
internal static BaseWidget RequestCreateWidget(BaseWidget _parent, WidgetStyle _style, string _skin, IntCoord _coord, Align _align, string _layer, string _name)
{
Widget widget = new Widget();
widget.CreateWidgetImpl(_parent, _style, _skin, _coord, _align, _layer, _name);
return widget;
}
#endregion
//InsertPoint
#region Event ChangeCoord
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportWidgetEvent_AdviseChangeCoord(IntPtr _native, bool _advise);
public delegate void HandleChangeCoord(
Widget _sender);
private HandleChangeCoord mEventChangeCoord;
public event HandleChangeCoord EventChangeCoord
{
add
{
if (ExportEventChangeCoord.mDelegate == null)
{
ExportEventChangeCoord.mDelegate = new ExportEventChangeCoord.ExportHandle(OnExportChangeCoord);
ExportEventChangeCoord.ExportWidgetEvent_DelegateChangeCoord(ExportEventChangeCoord.mDelegate);
}
if (mEventChangeCoord == null)
ExportWidgetEvent_AdviseChangeCoord(Native, true);
mEventChangeCoord += value;
}
remove
{
mEventChangeCoord -= value;
if (mEventChangeCoord == null)
ExportWidgetEvent_AdviseChangeCoord(Native, false);
}
}
private struct ExportEventChangeCoord
{
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
public static extern void ExportWidgetEvent_DelegateChangeCoord(ExportHandle _delegate);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate void ExportHandle(
IntPtr _sender);
public static ExportHandle mDelegate;
}
private static void OnExportChangeCoord(
IntPtr _sender)
{
Widget sender = (Widget)BaseWidget.GetByNative(_sender);
if (sender.mEventChangeCoord != null)
sender.mEventChangeCoord(
sender);
}
#endregion
#region Event ChangeProperty
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportWidgetEvent_AdviseChangeProperty(IntPtr _native, bool _advise);
public delegate void HandleChangeProperty(
Widget _sender,
string _key,
string _value);
private HandleChangeProperty mEventChangeProperty;
public event HandleChangeProperty EventChangeProperty
{
add
{
if (ExportEventChangeProperty.mDelegate == null)
{
ExportEventChangeProperty.mDelegate = new ExportEventChangeProperty.ExportHandle(OnExportChangeProperty);
ExportEventChangeProperty.ExportWidgetEvent_DelegateChangeProperty(ExportEventChangeProperty.mDelegate);
}
if (mEventChangeProperty == null)
ExportWidgetEvent_AdviseChangeProperty(Native, true);
mEventChangeProperty += value;
}
remove
{
mEventChangeProperty -= value;
if (mEventChangeProperty == null)
ExportWidgetEvent_AdviseChangeProperty(Native, false);
}
}
private struct ExportEventChangeProperty
{
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
public static extern void ExportWidgetEvent_DelegateChangeProperty(ExportHandle _delegate);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate void ExportHandle(
IntPtr _sender,
[MarshalAs(UnmanagedType.LPStr)] string _key,
[MarshalAs(UnmanagedType.LPStr)] string _value);
public static ExportHandle mDelegate;
}
private static void OnExportChangeProperty(
IntPtr _sender,
string _key,
string _value)
{
Widget sender = (Widget)BaseWidget.GetByNative(_sender);
if (sender.mEventChangeProperty != null)
sender.mEventChangeProperty(
sender ,
_key,
_value);
}
#endregion
#region Method SetWidgetStyle
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportWidget_SetWidgetStyle__style__layer(IntPtr _native,
[MarshalAs(UnmanagedType.I4)] WidgetStyle _style,
[MarshalAs(UnmanagedType.LPStr)] string _layer);
public void SetWidgetStyle(
WidgetStyle _style,
string _layer)
{
ExportWidget_SetWidgetStyle__style__layer(Native,
_style,
_layer);
}
#endregion
#region Method ChangeWidgetSkin
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportWidget_ChangeWidgetSkin__skinName(IntPtr _native,
[MarshalAs(UnmanagedType.LPStr)] string _skinName);
public void ChangeWidgetSkin(
string _skinName)
{
ExportWidget_ChangeWidgetSkin__skinName(Native,
_skinName);
}
#endregion
#region Method AttachToWidget
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportWidget_AttachToWidget__parent__style__layer(IntPtr _native,
IntPtr _parent,
[MarshalAs(UnmanagedType.I4)] WidgetStyle _style,
[MarshalAs(UnmanagedType.LPStr)] string _layer);
public void AttachToWidget(
Widget _parent,
WidgetStyle _style,
string _layer)
{
ExportWidget_AttachToWidget__parent__style__layer(Native,
_parent.Native,
_style,
_layer);
}
#endregion
#region Method DetachFromWidget
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportWidget_DetachFromWidget__layer(IntPtr _native,
[MarshalAs(UnmanagedType.LPStr)] string _layer);
public void DetachFromWidget(
string _layer)
{
ExportWidget_DetachFromWidget__layer(Native,
_layer);
}
#endregion
#region Method SetEnabledSilent
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportWidget_SetEnabledSilent__value(IntPtr _native,
[MarshalAs(UnmanagedType.U1)] bool _value);
public void SetEnabledSilent(
bool _value)
{
ExportWidget_SetEnabledSilent__value(Native,
_value);
}
#endregion
#region Method FindWidget
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr ExportWidget_FindWidget__name(IntPtr _native,
[MarshalAs(UnmanagedType.LPStr)] string _name);
public Widget FindWidget(
string _name)
{
return (Widget)BaseWidget.GetByNative(ExportWidget_FindWidget__name(Native,
_name));
}
#endregion
#region Method GetChildAt
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr ExportWidget_GetChildAt__index(IntPtr _native,
uint _index);
public Widget GetChildAt(
uint _index)
{
return (Widget)BaseWidget.GetByNative(ExportWidget_GetChildAt__index(Native,
_index));
}
#endregion
#region Method SetColour
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportWidget_SetColour__value(IntPtr _native,
[In] ref Colour _value);
public void SetColour(
Colour _value)
{
ExportWidget_SetColour__value(Native,
ref _value);
}
#endregion
#region Method SetRealCoord
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportWidget_SetRealCoord__left__top__width__height(IntPtr _native,
float _left,
float _top,
float _width,
float _height);
public void SetRealCoord(
float _left,
float _top,
float _width,
float _height)
{
ExportWidget_SetRealCoord__left__top__width__height(Native,
_left,
_top,
_width,
_height);
}
#endregion
#region Method SetRealSize
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportWidget_SetRealSize__width__height(IntPtr _native,
float _width,
float _height);
public void SetRealSize(
float _width,
float _height)
{
ExportWidget_SetRealSize__width__height(Native,
_width,
_height);
}
#endregion
#region Method SetRealPosition
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportWidget_SetRealPosition__left__top(IntPtr _native,
float _left,
float _top);
public void SetRealPosition(
float _left,
float _top)
{
ExportWidget_SetRealPosition__left__top(Native,
_left,
_top);
}
#endregion
#region Method SetRealCoord
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportWidget_SetRealCoord__value(IntPtr _native,
[In] ref FloatCoord _value);
public void SetRealCoord(
FloatCoord _value)
{
ExportWidget_SetRealCoord__value(Native,
ref _value);
}
#endregion
#region Method SetRealSize
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportWidget_SetRealSize__value(IntPtr _native,
[In] ref FloatSize _value);
public void SetRealSize(
FloatSize _value)
{
ExportWidget_SetRealSize__value(Native,
ref _value);
}
#endregion
#region Method SetRealPosition
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportWidget_SetRealPosition__value(IntPtr _native,
[In] ref FloatPoint _value);
public void SetRealPosition(
FloatPoint _value)
{
ExportWidget_SetRealPosition__value(Native,
ref _value);
}
#endregion
#region Method SetCoord
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportWidget_SetCoord__left__top__width__height(IntPtr _native,
int _left,
int _top,
int _width,
int _height);
public void SetCoord(
int _left,
int _top,
int _width,
int _height)
{
ExportWidget_SetCoord__left__top__width__height(Native,
_left,
_top,
_width,
_height);
}
#endregion
#region Method SetSize
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportWidget_SetSize__width__height(IntPtr _native,
int _width,
int _height);
public void SetSize(
int _width,
int _height)
{
ExportWidget_SetSize__width__height(Native,
_width,
_height);
}
#endregion
#region Method SetPosition
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportWidget_SetPosition__left__top(IntPtr _native,
int _left,
int _top);
public void SetPosition(
int _left,
int _top)
{
ExportWidget_SetPosition__left__top(Native,
_left,
_top);
}
#endregion
#region Property WidgetStyle
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern WidgetStyle ExportWidget_GetWidgetStyle(IntPtr _native);
public WidgetStyle WidgetStyle
{
get { return ExportWidget_GetWidgetStyle(Native); }
}
#endregion
#region Property ClientWidget
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr ExportWidget_GetClientWidget(IntPtr _native);
public Widget ClientWidget
{
get { return (Widget)BaseWidget.GetByNative(ExportWidget_GetClientWidget(Native)); }
}
#endregion
#region Property ClientCoord
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr ExportWidget_GetClientCoord(IntPtr _native);
public IntCoord ClientCoord
{
get { return (IntCoord)Marshal.PtrToStructure(ExportWidget_GetClientCoord(Native), typeof(IntCoord)); }
}
#endregion
#region Property InheritedEnabled
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ExportWidget_GetInheritedEnabled(IntPtr _native);
public bool InheritedEnabled
{
get { return ExportWidget_GetInheritedEnabled(Native); }
}
#endregion
#region Property Enabled
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ExportWidget_GetEnabled(IntPtr _widget);
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportWidget_SetEnabled(IntPtr _widget, [MarshalAs(UnmanagedType.U1)] bool _value);
public bool Enabled
{
get { return ExportWidget_GetEnabled(Native); }
set { ExportWidget_SetEnabled(Native, value); }
}
#endregion
#region Property ChildCount
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern uint ExportWidget_GetChildCount(IntPtr _native);
public uint ChildCount
{
get { return ExportWidget_GetChildCount(Native); }
}
#endregion
#region Property ParentSize
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr ExportWidget_GetParentSize(IntPtr _native);
public IntSize ParentSize
{
get { return (IntSize)Marshal.PtrToStructure(ExportWidget_GetParentSize(Native), typeof(IntSize)); }
}
#endregion
#region Property Parent
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr ExportWidget_GetParent(IntPtr _native);
public Widget Parent
{
get { return (Widget)BaseWidget.GetByNative(ExportWidget_GetParent(Native)); }
}
#endregion
#region Property IsRootWidget
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ExportWidget_IsRootWidget(IntPtr _native);
public bool IsRootWidget
{
get { return ExportWidget_IsRootWidget(Native); }
}
#endregion
#region Property InheritsAlpha
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ExportWidget_GetInheritsAlpha(IntPtr _widget);
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportWidget_SetInheritsAlpha(IntPtr _widget, [MarshalAs(UnmanagedType.U1)] bool _value);
public bool InheritsAlpha
{
get { return ExportWidget_GetInheritsAlpha(Native); }
set { ExportWidget_SetInheritsAlpha(Native, value); }
}
#endregion
#region Property Alpha
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern float ExportWidget_GetAlpha(IntPtr _widget);
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportWidget_SetAlpha(IntPtr _widget, float _value);
public float Alpha
{
get { return ExportWidget_GetAlpha(Native); }
set { ExportWidget_SetAlpha(Native, value); }
}
#endregion
#region Property Align
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern Align ExportWidget_GetAlign(IntPtr _widget);
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportWidget_SetAlign(IntPtr _widget, [MarshalAs(UnmanagedType.I4)] Align _value);
public Align Align
{
get { return ExportWidget_GetAlign(Native); }
set { ExportWidget_SetAlign(Native, value); }
}
#endregion
#region Property InheritedVisible
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ExportWidget_GetInheritedVisible(IntPtr _native);
public bool InheritedVisible
{
get { return ExportWidget_GetInheritedVisible(Native); }
}
#endregion
#region Property Visible
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ExportWidget_GetVisible(IntPtr _widget);
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportWidget_SetVisible(IntPtr _widget, [MarshalAs(UnmanagedType.U1)] bool _value);
public bool Visible
{
get { return ExportWidget_GetVisible(Native); }
set { ExportWidget_SetVisible(Native, value); }
}
#endregion
#region Property Name
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr ExportWidget_GetName(IntPtr _native);
public string Name
{
get { return Marshal.PtrToStringAnsi(ExportWidget_GetName(Native)); }
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ModelBinding.Binders;
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
using Microsoft.Extensions.Logging.Abstractions;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.IntegrationTests
{
public class ActionParameterIntegrationTest
{
private class Address
{
public string Street { get; set; }
}
private class Person3
{
public Person3()
{
Address = new List<Address>();
}
public List<Address> Address { get; }
}
[Fact]
public async Task ActionParameter_NonSettableCollectionModel_EmptyPrefix_GetsBound()
{
// Arrange
var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
var parameter = new ParameterDescriptor()
{
Name = "prefix",
ParameterType = typeof(Person3)
};
var testContext = ModelBindingTestHelper.GetTestContext(request =>
{
request.QueryString = QueryString.Create("Address[0].Street", "SomeStreet");
});
var modelState = testContext.ModelState;
var model = new Person3();
// Act
var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext);
// Assert
Assert.True(modelBindingResult.IsModelSet);
// Model
Assert.NotNull(modelBindingResult.Model);
var boundModel = Assert.IsType<Person3>(modelBindingResult.Model);
Assert.Single(boundModel.Address);
Assert.Equal("SomeStreet", boundModel.Address[0].Street);
// ModelState
Assert.True(modelState.IsValid);
var key = Assert.Single(modelState.Keys);
Assert.Equal("Address[0].Street", key);
Assert.Equal("SomeStreet", modelState[key].AttemptedValue);
Assert.Equal("SomeStreet", modelState[key].RawValue);
Assert.Empty(modelState[key].Errors);
Assert.Equal(ModelValidationState.Valid, modelState[key].ValidationState);
}
private class Person6
{
public CustomReadOnlyCollection<Address> Address { get; set; }
}
[Fact]
public async Task ActionParameter_ReadOnlyCollectionModel_EmptyPrefix_DoesNotGetBound()
{
// Arrange
var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
var parameter = new ParameterDescriptor()
{
Name = "prefix",
ParameterType = typeof(Person6)
};
var testContext = ModelBindingTestHelper.GetTestContext(request =>
{
request.QueryString = QueryString.Create("Address[0].Street", "SomeStreet");
});
var modelState = testContext.ModelState;
// Act
var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext);
// Assert
Assert.True(modelBindingResult.IsModelSet);
// Model
var boundModel = Assert.IsType<Person6>(modelBindingResult.Model);
Assert.NotNull(boundModel);
Assert.NotNull(boundModel.Address);
// Read-only collection should not be updated.
Assert.Empty(boundModel.Address);
Assert.True(modelState.IsValid);
var entry = Assert.Single(modelState);
Assert.Equal("Address[0].Street", entry.Key);
var state = entry.Value;
Assert.NotNull(state);
Assert.Equal(ModelValidationState.Valid, state.ValidationState);
Assert.Equal("SomeStreet", state.RawValue);
Assert.Equal("SomeStreet", state.AttemptedValue);
}
private class Person4
{
public Address[] Address { get; set; }
}
[Fact]
public async Task ActionParameter_SettableArrayModel_EmptyPrefix_GetsBound()
{
// Arrange
var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
var parameter = new ParameterDescriptor()
{
Name = "prefix",
ParameterType = typeof(Person4)
};
var testContext = ModelBindingTestHelper.GetTestContext(request =>
{
request.QueryString = QueryString.Create("Address[0].Street", "SomeStreet");
});
var modelState = testContext.ModelState;
var model = new Person4();
// Act
var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext);
// Assert
Assert.True(modelBindingResult.IsModelSet);
// Model
Assert.NotNull(modelBindingResult.Model);
var boundModel = Assert.IsType<Person4>(modelBindingResult.Model);
Assert.NotNull(boundModel.Address);
Assert.Single(boundModel.Address);
Assert.Equal("SomeStreet", boundModel.Address[0].Street);
// ModelState
Assert.True(modelState.IsValid);
var key = Assert.Single(modelState.Keys);
Assert.Equal("Address[0].Street", key);
Assert.Equal("SomeStreet", modelState[key].AttemptedValue);
Assert.Equal("SomeStreet", modelState[key].RawValue);
Assert.Empty(modelState[key].Errors);
Assert.Equal(ModelValidationState.Valid, modelState[key].ValidationState);
}
private class Person5
{
public Address[] Address { get; } = new Address[] { };
}
[Fact]
public async Task ActionParameter_NonSettableArrayModel_EmptyPrefix_DoesNotGetBound()
{
// Arrange
var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
var parameter = new ParameterDescriptor()
{
Name = "prefix",
ParameterType = typeof(Person5)
};
var testContext = ModelBindingTestHelper.GetTestContext(request =>
{
request.QueryString = QueryString.Create("Address[0].Street", "SomeStreet");
});
var modelState = testContext.ModelState;
// Act
var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext);
// Assert
Assert.True(modelBindingResult.IsModelSet);
// Model
Assert.NotNull(modelBindingResult.Model);
var boundModel = Assert.IsType<Person5>(modelBindingResult.Model);
Assert.NotNull(boundModel.Address);
// Arrays should not be updated.
Assert.Empty(boundModel.Address);
// ModelState
Assert.True(modelState.IsValid);
Assert.Empty(modelState.Keys);
}
[Fact]
public async Task ActionParameter_NonSettableCollectionModel_WithPrefix_GetsBound()
{
// Arrange
var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
var parameter = new ParameterDescriptor()
{
Name = "Address",
BindingInfo = new BindingInfo()
{
BinderModelName = "prefix"
},
ParameterType = typeof(Person3)
};
var testContext = ModelBindingTestHelper.GetTestContext(request =>
{
request.QueryString = QueryString.Create("prefix.Address[0].Street", "SomeStreet");
});
var modelState = testContext.ModelState;
// Act
var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext);
// Assert
Assert.True(modelBindingResult.IsModelSet);
// Model
Assert.NotNull(modelBindingResult.Model);
var boundModel = Assert.IsType<Person3>(modelBindingResult.Model);
Assert.Single(boundModel.Address);
Assert.Equal("SomeStreet", boundModel.Address[0].Street);
// ModelState
Assert.True(modelState.IsValid);
var key = Assert.Single(modelState.Keys);
Assert.Equal("prefix.Address[0].Street", key);
Assert.Equal("SomeStreet", modelState[key].AttemptedValue);
Assert.Equal("SomeStreet", modelState[key].RawValue);
Assert.Empty(modelState[key].Errors);
Assert.Equal(ModelValidationState.Valid, modelState[key].ValidationState);
}
[Fact]
public async Task ActionParameter_ReadOnlyCollectionModel_WithPrefix_DoesNotGetBound()
{
// Arrange
var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
var parameter = new ParameterDescriptor()
{
Name = "Address",
BindingInfo = new BindingInfo
{
BinderModelName = "prefix"
},
ParameterType = typeof(Person6)
};
var testContext = ModelBindingTestHelper.GetTestContext(request =>
{
request.QueryString = QueryString.Create("prefix.Address[0].Street", "SomeStreet");
});
var modelState = testContext.ModelState;
// Act
var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext);
// Assert
Assert.True(modelBindingResult.IsModelSet);
// Model
var boundModel = Assert.IsType<Person6>(modelBindingResult.Model);
Assert.NotNull(boundModel);
Assert.NotNull(boundModel.Address);
// Read-only collection should not be updated.
Assert.Empty(boundModel.Address);
// ModelState (data cannot be validated).
Assert.True(modelState.IsValid);
var entry = Assert.Single(modelState);
Assert.Equal("prefix.Address[0].Street", entry.Key);
var state = entry.Value;
Assert.NotNull(state);
Assert.Equal(ModelValidationState.Valid, state.ValidationState);
Assert.Equal("SomeStreet", state.AttemptedValue);
Assert.Equal("SomeStreet", state.RawValue);
}
[Fact]
public async Task ActionParameter_SettableArrayModel_WithPrefix_GetsBound()
{
// Arrange
var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
var parameter = new ParameterDescriptor()
{
Name = "Address",
BindingInfo = new BindingInfo()
{
BinderModelName = "prefix"
},
ParameterType = typeof(Person4)
};
var testContext = ModelBindingTestHelper.GetTestContext(request =>
{
request.QueryString = QueryString.Create("prefix.Address[0].Street", "SomeStreet");
});
var modelState = testContext.ModelState;
// Act
var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext);
// Assert
Assert.True(modelBindingResult.IsModelSet);
// Model
Assert.NotNull(modelBindingResult.Model);
var boundModel = Assert.IsType<Person4>(modelBindingResult.Model);
Assert.Single(boundModel.Address);
Assert.Equal("SomeStreet", boundModel.Address[0].Street);
// ModelState
Assert.True(modelState.IsValid);
var key = Assert.Single(modelState.Keys);
Assert.Equal("prefix.Address[0].Street", key);
Assert.Equal("SomeStreet", modelState[key].AttemptedValue);
Assert.Equal("SomeStreet", modelState[key].RawValue);
Assert.Empty(modelState[key].Errors);
Assert.Equal(ModelValidationState.Valid, modelState[key].ValidationState);
}
[Fact]
public async Task ActionParameter_NonSettableArrayModel_WithPrefix_DoesNotGetBound()
{
// Arrange
var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
var parameter = new ParameterDescriptor()
{
Name = "Address",
BindingInfo = new BindingInfo()
{
BinderModelName = "prefix"
},
ParameterType = typeof(Person5)
};
var testContext = ModelBindingTestHelper.GetTestContext(request =>
{
request.QueryString = QueryString.Create("prefix.Address[0].Street", "SomeStreet");
});
var modelState = testContext.ModelState;
// Act
var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext);
// Assert
Assert.True(modelBindingResult.IsModelSet);
// Model
Assert.NotNull(modelBindingResult.Model);
var boundModel = Assert.IsType<Person5>(modelBindingResult.Model);
// Arrays should not be updated.
Assert.Empty(boundModel.Address);
// ModelState
Assert.True(modelState.IsValid);
Assert.Empty(modelState.Keys);
}
[Fact]
public async Task ActionParameter_ModelPropertyTypeWithNoParameterlessConstructor_ThrowsException()
{
// Arrange
var parameterType = typeof(Class1);
var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
var parameter = new ParameterDescriptor()
{
Name = "p",
ParameterType = parameterType
};
var testContext = ModelBindingTestHelper.GetTestContext(request =>
{
request.QueryString = QueryString.Create("Name", "James").Add("Property1.City", "Seattle");
});
var modelState = testContext.ModelState;
// Act & Assert
var exception = await Assert.ThrowsAsync<InvalidOperationException>(() => parameterBinder.BindModelAsync(parameter, testContext));
Assert.Equal(
string.Format(
CultureInfo.CurrentCulture,
"Could not create an instance of type '{0}'. Model bound complex types must not be abstract or " +
"value types and must have a parameterless constructor. Record types must have a single primary constructor. " +
"Alternatively, set the '{1}' property to a non-null value in the '{2}' constructor.",
typeof(ClassWithNoDefaultConstructor).FullName,
nameof(Class1.Property1),
typeof(Class1).FullName),
exception.Message);
}
public record ActionParameter_DefaultValueConstructor(string Name = "test", int Age = 23);
[Fact]
public async Task ActionParameter_UsesDefaultConstructorParameters()
{
// Arrange
var parameterType = typeof(ActionParameter_DefaultValueConstructor);
var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
var parameter = new ParameterDescriptor()
{
Name = "p",
ParameterType = parameterType
};
var testContext = ModelBindingTestHelper.GetTestContext(request =>
{
request.QueryString = QueryString.Create("Name", "James");
});
var modelState = testContext.ModelState;
// Act
var result = await parameterBinder.BindModelAsync(parameter, testContext);
// Assert
Assert.True(modelState.IsValid);
var model = Assert.IsType<ActionParameter_DefaultValueConstructor>(result.Model);
Assert.Equal("James", model.Name);
Assert.Equal(23, model.Age);
}
[Fact]
public async Task ActionParameter_UsingComplexTypeModelBinder_ModelPropertyTypeWithNoParameterlessConstructor_ThrowsException()
{
// Arrange
var parameterType = typeof(Class1);
var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
var parameter = new ParameterDescriptor()
{
Name = "p",
ParameterType = parameterType
};
var testContext = ModelBindingTestHelper.GetTestContext(request =>
{
request.QueryString = QueryString.Create("Name", "James").Add("Property1.City", "Seattle");
}, updateOptions: options =>
{
options.ModelBinderProviders.RemoveType<ComplexObjectModelBinderProvider>();
#pragma warning disable CS0618 // Type or member is obsolete
options.ModelBinderProviders.Add(new ComplexTypeModelBinderProvider());
#pragma warning restore CS0618 // Type or member is obsolete
});
var modelState = testContext.ModelState;
// Act & Assert
var exception = await Assert.ThrowsAsync<InvalidOperationException>(() => parameterBinder.BindModelAsync(parameter, testContext));
Assert.Equal(
string.Format(
CultureInfo.CurrentCulture,
"Could not create an instance of type '{0}'. Model bound complex types must not be abstract or " +
"value types and must have a parameterless constructor. Alternatively, set the '{1}' property to" +
" a non-null value in the '{2}' constructor.",
typeof(ClassWithNoDefaultConstructor).FullName,
nameof(Class1.Property1),
typeof(Class1).FullName),
exception.Message);
}
[Fact]
public async Task ActionParameter_BindingToStructModel_ThrowsException()
{
// Arrange
var parameterType = typeof(PointStruct);
var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
var parameter = new ParameterDescriptor()
{
ParameterType = parameterType,
Name = "p"
};
var testContext = ModelBindingTestHelper.GetTestContext();
// Act & Assert
var exception = await Assert.ThrowsAsync<InvalidOperationException>(() => parameterBinder.BindModelAsync(parameter, testContext));
Assert.Equal(
string.Format(
CultureInfo.CurrentCulture,
"Could not create an instance of type '{0}'. Model bound complex types must not be abstract or " +
"value types and must have a parameterless constructor. Record types must have a single primary constructor.",
typeof(PointStruct).FullName),
exception.Message);
}
[Fact]
public async Task ActionParameter_BindingToAbstractionType_ThrowsException()
{
// Arrange
var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
var parameter = new ParameterDescriptor()
{
ParameterType = typeof(AbstractClassWithNoDefaultConstructor),
Name = "p"
};
var testContext = ModelBindingTestHelper.GetTestContext();
// Act & Assert
var exception = await Assert.ThrowsAsync<InvalidOperationException>(() => parameterBinder.BindModelAsync(parameter, testContext));
Assert.Equal(
string.Format(
CultureInfo.CurrentCulture,
"Could not create an instance of type '{0}'. Model bound complex types must not be abstract or " +
"value types and must have a parameterless constructor. Record types must have a single primary constructor.",
typeof(AbstractClassWithNoDefaultConstructor).FullName),
exception.Message);
}
public class ActionParameter_MultipleConstructorsWithDefaultValues_NoParameterlessConstructorModel
{
public ActionParameter_MultipleConstructorsWithDefaultValues_NoParameterlessConstructorModel(string name = "default-name") => (Name) = (name);
public ActionParameter_MultipleConstructorsWithDefaultValues_NoParameterlessConstructorModel(string name, int age) => (Name, Age) = (name, age);
public string Name { get; init; }
public int Age { get; init; }
}
[Fact]
public async Task ActionParameter_MultipleConstructorsWithDefaultValues_NoParameterlessConstructor_Throws()
{
// Arrange
var parameterType = typeof(ActionParameter_MultipleConstructorsWithDefaultValues_NoParameterlessConstructorModel);
var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
var parameter = new ParameterDescriptor()
{
Name = "p",
ParameterType = parameterType
};
var testContext = ModelBindingTestHelper.GetTestContext(request =>
{
request.QueryString = QueryString.Create("Name", "James");
});
var modelState = testContext.ModelState;
// Act & Assert
var exception = await Assert.ThrowsAsync<InvalidOperationException>(() => parameterBinder.BindModelAsync(parameter, testContext));
Assert.Equal(
string.Format(
CultureInfo.CurrentCulture,
"Could not create an instance of type '{0}'. Model bound complex types must not be abstract or " +
"value types and must have a parameterless constructor. Record types must have a single primary constructor.",
typeof(ActionParameter_MultipleConstructorsWithDefaultValues_NoParameterlessConstructorModel).FullName),
exception.Message);
}
public record ActionParameter_RecordTypeWithMultipleConstructors(string Name, int Age)
{
public ActionParameter_RecordTypeWithMultipleConstructors(string Name) : this(Name, 0) { }
}
[Fact]
public async Task ActionParameter_RecordTypeWithMultipleConstructors_Throws()
{
// Arrange
var parameterType = typeof(ActionParameter_RecordTypeWithMultipleConstructors);
var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
var parameter = new ParameterDescriptor()
{
Name = "p",
ParameterType = parameterType
};
var testContext = ModelBindingTestHelper.GetTestContext(request =>
{
request.QueryString = QueryString.Create("Name", "James").Add("Age", "29");
});
var modelState = testContext.ModelState;
// Act & Assert
var exception = await Assert.ThrowsAsync<InvalidOperationException>(() => parameterBinder.BindModelAsync(parameter, testContext));
Assert.Equal(
string.Format(
CultureInfo.CurrentCulture,
"Could not create an instance of type '{0}'. Model bound complex types must not be abstract or " +
"value types and must have a parameterless constructor. Record types must have a single primary constructor.",
typeof(ActionParameter_RecordTypeWithMultipleConstructors).FullName),
exception.Message);
}
[Fact]
public async Task ActionParameter_CustomModelBinder_CanCreateModels_ForParameterlessConstructorTypes()
{
// Arrange
var testContext = ModelBindingTestHelper.GetTestContext();
var modelState = testContext.ModelState;
var parameterBinder = ModelBindingTestHelper.GetParameterBinder(
testContext.MvcOptions,
new CustomComplexTypeModelBinderProvider());
var parameter = new ParameterDescriptor
{
Name = "prefix",
ParameterType = typeof(ClassWithNoDefaultConstructor)
};
// Act
var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext);
// Assert
Assert.True(modelBindingResult.IsModelSet);
// Model
Assert.NotNull(modelBindingResult.Model);
var boundModel = Assert.IsType<ClassWithNoDefaultConstructor>(modelBindingResult.Model);
Assert.Equal(100, boundModel.Id);
// ModelState
Assert.True(modelState.IsValid);
}
[Fact]
public async Task ActionParameter_WithBindNever_DoesNotGetBound()
{
// Arrange
var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
var parameter = new ParameterDescriptor()
{
Name = BindingAndValidationController.BindNeverParamInfo.Name,
ParameterType = typeof(int)
};
var testContext = ModelBindingTestHelper.GetTestContext(request =>
{
request.QueryString = QueryString.Create(parameter.Name, "123");
});
var modelState = testContext.ModelState;
var modelMetadataProvider = TestModelMetadataProvider.CreateDefaultProvider();
var modelMetadata = modelMetadataProvider
.GetMetadataForParameter(BindingAndValidationController.BindNeverParamInfo);
// Act
var modelBindingResult = await parameterBinder.BindModelAsync(
parameter,
testContext,
modelMetadataProvider,
modelMetadata);
// Assert
Assert.False(modelBindingResult.IsModelSet);
Assert.True(modelState.IsValid);
}
[Fact]
public async Task ActionParameter_WithValidateNever_DoesNotGetValidated()
{
// Arrange
var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
var parameter = new ParameterDescriptor()
{
Name = ParameterWithValidateNever.ValidateNeverParameterInfo.Name,
ParameterType = typeof(ModelWithIValidatableObject)
};
var testContext = ModelBindingTestHelper.GetTestContext(request =>
{
request.QueryString = QueryString.Create(nameof(ModelWithIValidatableObject.FirstName), "TestName");
});
var modelState = testContext.ModelState;
var modelMetadataProvider = TestModelMetadataProvider.CreateDefaultProvider();
var modelMetadata = modelMetadataProvider
.GetMetadataForParameter(ParameterWithValidateNever.ValidateNeverParameterInfo);
// Act
var modelBindingResult = await parameterBinder.BindModelAsync(
parameter,
testContext,
modelMetadataProvider,
modelMetadata);
// Assert
Assert.True(modelBindingResult.IsModelSet);
var model = Assert.IsType<ModelWithIValidatableObject>(modelBindingResult.Model);
Assert.Equal("TestName", model.FirstName);
// No validation errors are expected.
// Assert.True(modelState.IsValid);
// Tracking bug to enable this scenario: https://github.com/dotnet/aspnetcore/issues/24241
Assert.False(modelState.IsValid);
}
[Theory]
[InlineData(123, true)]
[InlineData(null, false)]
public async Task ActionParameter_EnforcesBindRequired(int? input, bool isValid)
{
// Arrange
var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
var parameter = new ParameterDescriptor()
{
Name = BindingAndValidationController.BindRequiredParamInfo.Name,
ParameterType = typeof(int)
};
var testContext = ModelBindingTestHelper.GetTestContext(request =>
{
if (input.HasValue)
{
request.QueryString = QueryString.Create(parameter.Name, input.Value.ToString(CultureInfo.InvariantCulture));
}
});
var modelState = testContext.ModelState;
var modelMetadataProvider = TestModelMetadataProvider.CreateDefaultProvider();
var modelMetadata = modelMetadataProvider
.GetMetadataForParameter(BindingAndValidationController.BindRequiredParamInfo);
// Act
var modelBindingResult = await parameterBinder.BindModelAsync(
parameter,
testContext,
modelMetadataProvider,
modelMetadata);
// Assert
Assert.Equal(input.HasValue, modelBindingResult.IsModelSet);
Assert.Equal(isValid, modelState.IsValid);
if (isValid)
{
Assert.Equal(input.Value, Assert.IsType<int>(modelBindingResult.Model));
}
}
[Theory]
[InlineData("requiredAndStringLengthParam", null, false)]
[InlineData("requiredAndStringLengthParam", "", false)]
[InlineData("requiredAndStringLengthParam", "abc", true)]
[InlineData("requiredAndStringLengthParam", "abcTooLong", false)]
[InlineData("displayNameStringLengthParam", null, true)]
[InlineData("displayNameStringLengthParam", "", true)]
[InlineData("displayNameStringLengthParam", "abc", true)]
[InlineData("displayNameStringLengthParam", "abcTooLong", false, "My Display Name")]
public async Task ActionParameter_EnforcesDataAnnotationsAttributes(
string paramName,
string input,
bool isValid,
string displayName = null)
{
// Arrange
var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
var parameterInfo = BindingAndValidationController.GetParameterInfo(paramName);
var parameter = new ParameterDescriptor()
{
Name = parameterInfo.Name,
ParameterType = parameterInfo.ParameterType
};
var testContext = ModelBindingTestHelper.GetTestContext(request =>
{
if (input != null)
{
request.QueryString = QueryString.Create(parameter.Name, input);
}
});
var modelState = testContext.ModelState;
var modelMetadataProvider = TestModelMetadataProvider.CreateDefaultProvider();
var modelMetadata = modelMetadataProvider
.GetMetadataForParameter(parameterInfo);
// Act
var modelBindingResult = await parameterBinder.BindModelAsync(
parameter,
testContext,
modelMetadataProvider,
modelMetadata);
// Assert
Assert.Equal(input != null, modelBindingResult.IsModelSet);
Assert.Equal(isValid, modelState.IsValid);
if (!isValid)
{
var entry = modelState[paramName];
Assert.NotNull(entry);
var message = entry.Errors.Single().ErrorMessage;
Assert.Contains(displayName ?? parameter.Name, message);
}
}
[Fact]
public async Task ActionParameter_CanRunIValidatableObject_EmptyPrefix()
{
// Arrange
var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
var parameterInfo = BindingAndValidationController.ValidatableObjectParameterInfo;
var parameter = new ParameterDescriptor()
{
Name = parameterInfo.Name,
ParameterType = parameterInfo.ParameterType,
};
var testContext = ModelBindingTestHelper.GetTestContext(request =>
{
request.QueryString = QueryString.Create(nameof(ModelWithIValidatableObject.FirstName), "Billy");
});
var modelState = testContext.ModelState;
var modelMetadataProvider = TestModelMetadataProvider.CreateDefaultProvider();
var modelMetadata = modelMetadataProvider
.GetMetadataForParameter(parameterInfo);
// Act
var modelBindingResult = await parameterBinder.BindModelAsync(
parameter,
testContext,
modelMetadataProvider,
modelMetadata);
// Assert
Assert.True(modelBindingResult.IsModelSet, "model is set");
Assert.False(modelState.IsValid, "model is valid");
var entry = modelState[string.Empty];
Assert.NotNull(entry);
var message = entry.Errors.Single().ErrorMessage;
Assert.Equal("Not valid.", message);
entry = modelState[nameof(ModelWithIValidatableObject.FirstName)];
Assert.NotNull(entry);
message = entry.Errors.Single().ErrorMessage;
Assert.Equal("FirstName Not valid.", message);
}
[Fact]
public async Task ActionParameter_CanRunIValidatableObject_WithPrefix()
{
// Arrange
var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
var parameterInfo = BindingAndValidationController.ValidatableObjectParameterInfo;
var parameter = new ParameterDescriptor()
{
Name = parameterInfo.Name,
ParameterType = parameterInfo.ParameterType,
};
var testContext = ModelBindingTestHelper.GetTestContext(request =>
{
var key = ModelNames.CreatePropertyModelName(parameter.Name, nameof(ModelWithIValidatableObject.FirstName));
request.QueryString = QueryString.Create(key, "Billy");
});
var modelState = testContext.ModelState;
var modelMetadataProvider = TestModelMetadataProvider.CreateDefaultProvider();
var modelMetadata = modelMetadataProvider
.GetMetadataForParameter(parameterInfo);
// Act
var modelBindingResult = await parameterBinder.BindModelAsync(
parameter,
testContext,
modelMetadataProvider,
modelMetadata);
// Assert
Assert.True(modelBindingResult.IsModelSet, "model is set");
Assert.False(modelState.IsValid, "model is valid");
var entry = modelState[parameter.Name];
Assert.NotNull(entry);
var message = entry.Errors.Single().ErrorMessage;
Assert.Equal("Not valid.", message);
entry = modelState[ModelNames.CreatePropertyModelName(parameter.Name, nameof(ModelWithIValidatableObject.FirstName))];
Assert.NotNull(entry);
message = entry.Errors.Single().ErrorMessage;
Assert.Equal("FirstName Not valid.", message);
}
private class ModelWithIValidatableObject : IValidatableObject
{
public string FirstName { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield return new ValidationResult("Not valid.");
yield return new ValidationResult("FirstName Not valid.", new string[] { nameof(FirstName) });
}
}
private struct PointStruct
{
public PointStruct(double x, double y)
{
X = x;
Y = y;
}
public double X { get; }
public double Y { get; }
}
private class Class1
{
public ClassWithNoDefaultConstructor Property1 { get; set; }
public string Name { get; set; }
}
private class ClassWithNoDefaultConstructor
{
public ClassWithNoDefaultConstructor(int id)
{
Id = id;
}
public string City { get; set; }
public int Id { get; }
}
private abstract class AbstractClassWithNoDefaultConstructor
{
private readonly string _name;
public AbstractClassWithNoDefaultConstructor()
: this("James")
{
}
public AbstractClassWithNoDefaultConstructor(string name)
{
_name = name;
}
public string Name { get; set; }
}
private class BindingAndValidationController
{
public void MyAction(
[BindNever] int bindNeverParam,
[BindRequired] int bindRequiredParam,
[Required, StringLength(3)] string requiredAndStringLengthParam,
[Display(Name = "My Display Name"), StringLength(3)] string displayNameStringLengthParam,
ModelWithIValidatableObject validatableObject)
{
}
private static MethodInfo MyActionMethodInfo
=> typeof(BindingAndValidationController).GetMethod(nameof(MyAction));
public static ParameterInfo BindNeverParamInfo
=> MyActionMethodInfo.GetParameters()[0];
public static ParameterInfo BindRequiredParamInfo
=> MyActionMethodInfo.GetParameters()[1];
public static ParameterInfo ValidatableObjectParameterInfo => MyActionMethodInfo.GetParameters()[4];
public static ParameterInfo GetParameterInfo(string parameterName)
{
return MyActionMethodInfo
.GetParameters()
.Single(p => p.Name.Equals(parameterName, StringComparison.Ordinal));
}
}
private class ParameterWithValidateNever
{
public void MyAction([Required] string Name, [ValidateNever] ModelWithIValidatableObject validatableObject)
{
}
private static MethodInfo MyActionMethodInfo
=> typeof(ParameterWithValidateNever).GetMethod(nameof(MyAction));
public static ParameterInfo NameParameterInfo
=> MyActionMethodInfo.GetParameters()[0];
public static ParameterInfo ValidateNeverParameterInfo
=> MyActionMethodInfo.GetParameters()[1];
public static ParameterInfo GetParameterInfo(string parameterName)
{
return MyActionMethodInfo
.GetParameters()
.Single(p => p.Name.Equals(parameterName, StringComparison.Ordinal));
}
}
private class CustomReadOnlyCollection<T> : ICollection<T>
{
private readonly ICollection<T> _original;
public CustomReadOnlyCollection()
: this(new List<T>())
{
}
public CustomReadOnlyCollection(ICollection<T> original)
{
_original = original;
}
public int Count
{
get { return _original.Count; }
}
public bool IsReadOnly
{
get { return true; }
}
public void Add(T item)
{
throw new NotSupportedException();
}
public void Clear()
{
throw new NotSupportedException();
}
public bool Contains(T item)
{
return _original.Contains(item);
}
public void CopyTo(T[] array, int arrayIndex)
{
_original.CopyTo(array, arrayIndex);
}
public bool Remove(T item)
{
throw new NotSupportedException();
}
public IEnumerator<T> GetEnumerator()
{
foreach (var t in _original)
{
yield return t;
}
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
// By default the ComplexTypeModelBinder fails to construct models for types with no parameterless constructor,
// but a developer could change this behavior by overriding CreateModel
#pragma warning disable CS0618 // Type or member is obsolete
private class CustomComplexTypeModelBinder : ComplexTypeModelBinder
#pragma warning restore CS0618 // Type or member is obsolete
{
public CustomComplexTypeModelBinder(IDictionary<ModelMetadata, IModelBinder> propertyBinders)
: base(propertyBinders, NullLoggerFactory.Instance)
{
}
protected override object CreateModel(ModelBindingContext bindingContext)
{
Assert.Equal(typeof(ClassWithNoDefaultConstructor), bindingContext.ModelType);
return new ClassWithNoDefaultConstructor(100);
}
}
private class CustomComplexTypeModelBinderProvider : IModelBinderProvider
{
public IModelBinder GetBinder(ModelBinderProviderContext context)
{
var propertyBinders = new Dictionary<ModelMetadata, IModelBinder>();
foreach (var property in context.Metadata.Properties)
{
propertyBinders.Add(property, context.CreateBinder(property));
}
return new CustomComplexTypeModelBinder(propertyBinders);
}
}
}
}
| |
/*
Copyright (c) 2006-2012 Tomas Matousek, DEVSENSE
The use and distribution terms for this software are contained in the file named License.txt,
which can be found in the root of the Phalanger distribution. By using this software
in any fashion, you are agreeing to be bound by the terms of this license.
You must not remove this notice from this software.
*/
using System;
using System.Reflection;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Xml;
using System.Threading;
using System.Reflection.Emit;
using System.IO;
using System.Diagnostics;
using System.Runtime.Serialization;
#if SILVERLIGHT
using PHP.CoreCLR;
#endif
namespace PHP.Core.Reflection
{
#region PureAssembly
public sealed class PureAssembly : PhpAssembly
{
internal const string ModuleName = "PurePhpModule";
public static readonly Name EntryPointName = new Name("Main");
internal override DModule/*!*/ ExportModule { get { return module; } }
public PureModule/*!*/ Module { get { return module; } internal /* friend PAB */ set { module = value; } }
private PureModule/*!*/ module;
#region Construction
/// <summary>
/// Used by the loader.
/// </summary>
internal PureAssembly(ApplicationContext/*!*/ applicationContext, Assembly/*!*/ realAssembly,
PurePhpAssemblyAttribute/*!*/ attribute, LibraryConfigStore configStore)
: base(applicationContext, realAssembly)
{
module = new PureModule(this);
}
/// <summary>
/// Used by the builder.
/// </summary>
internal PureAssembly(ApplicationContext/*!*/ applicationContext)
: base(applicationContext)
{
// to be written-up
}
#endregion
public override PhpModule GetModule(PhpSourceFile name)
{
return module;
}
internal override void LoadCompileTimeReferencedAssemblies(AssemblyLoader/*!*/ loader)
{
base.LoadCompileTimeReferencedAssemblies(loader);
foreach (string full_name in GetAttribute().ReferencedAssemblies)
loader.Load(full_name, null, null);
}
private PurePhpAssemblyAttribute GetAttribute()
{
return PurePhpAssemblyAttribute.Reflect(RealAssembly);
}
}
#endregion
#region ScriptAssembly
[Serializable]
public sealed class InvalidScriptAssemblyException : Exception
{
internal InvalidScriptAssemblyException(Assembly/*!*/ assembly)
: base(CoreResources.GetString("invalid_script_assembly", assembly.Location))
{
}
#region Serializable
public InvalidScriptAssemblyException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
[System.Security.SecurityCritical]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
}
#endregion
}
/// <summary>
/// An abstract base class representing general script assembly.
/// </summary>
public abstract class ScriptAssembly : PhpAssembly
{
internal const string RealModuleName = "PhpScriptModule";
internal const string EntryPointHelperName = "Run";
public abstract bool IsMultiScript { get; }
#region Construction
/// <summary>
/// Used by assembly loader.
/// </summary>
public ScriptAssembly(ApplicationContext/*!*/ applicationContext, Module/*!*/ realModule)
: base(applicationContext, realModule)
{
}
/// <summary>
/// Used by assembly loader.
/// </summary>
public ScriptAssembly(ApplicationContext/*!*/ applicationContext, Assembly/*!*/ realAssembly)
: this(applicationContext, realAssembly.ManifestModule)
{
}
/// <summary>
/// Used by builders (written-up).
/// </summary>
protected ScriptAssembly(ApplicationContext/*!*/ applicationContext)
: base(applicationContext)
{
}
internal static ScriptAssembly/*!*/ Create(ApplicationContext/*!*/ applicationContext, Assembly/*!*/ realAssembly,
ScriptAssemblyAttribute/*!*/ scriptAttribute)
{
return Create(applicationContext, realAssembly, scriptAttribute, null);
}
internal static ScriptAssembly/*!*/ Create(ApplicationContext/*!*/ applicationContext, Assembly/*!*/ realAssembly,
ScriptAssemblyAttribute/*!*/ scriptAttribute, string libraryRoot)
{
if (scriptAttribute.IsMultiScript)
return new MultiScriptAssembly(applicationContext, realAssembly, libraryRoot);
else
return new SingleScriptAssembly(applicationContext, realAssembly, libraryRoot);
}
/// <summary>
/// Loads a script assembly using a specified CLR assembly.
/// </summary>
public static ScriptAssembly/*!*/ LoadFromAssembly(ApplicationContext/*!*/ applicationContext, Assembly/*!*/ realAssembly)
{
return LoadFromAssembly(applicationContext, realAssembly, null);
}
/// <summary>
/// Loads a script assembly using a specified CLR assembly with specified offset path.
/// </summary>
public static ScriptAssembly/*!*/ LoadFromAssembly(ApplicationContext/*!*/ applicationContext, Assembly/*!*/ realAssembly, string libraryRoot)
{
return Create(applicationContext, realAssembly, GetAttribute(realAssembly), libraryRoot);
}
#endregion
public abstract IEnumerable<ScriptModule> GetModules();
/// <summary>
/// Gets a type name of the script type given a subnamespace.
/// </summary>
/// <param name="subnamespace">The subnamespace or a <B>null</B> reference.</param>
/// <returns>Full name of the type.</returns>
public string GetQualifiedScriptTypeName(string subnamespace)
{
Debug.Assert(String.IsNullOrEmpty(subnamespace) || subnamespace[subnamespace.Length - 1] == Type.Delimiter);
return String.Concat(subnamespace, ScriptModule.ScriptTypeName);
}
/// <summary>
/// Extracts metadata information associtated with the CLR assembly.
/// </summary>
/// <exception cref="InvalidScriptAssemblyException">The assembly is invalid.</exception>
private static ScriptAssemblyAttribute/*!*/ GetAttribute(Assembly/*!*/ realAssembly)
{
ScriptAssemblyAttribute result = ScriptAssemblyAttribute.Reflect(realAssembly);
if (result == null)
throw new InvalidScriptAssemblyException(realAssembly);
return result;
}
}
#endregion
#region SingleScriptAssembly
/// <summary>
/// Represents a script assembly comprising of a single script module.
/// </summary>
public sealed class SingleScriptAssembly : ScriptAssembly
{
public ScriptModule Module { get { return module; } internal /* friend SSAB */ set { module = value; } }
private ScriptModule module;
private Type scriptType;
public override bool IsMultiScript { get { return false; } }
#region Construction
/// <summary>
/// Used by the loader.
/// </summary>
/// <param name="applicationContext">Current application context.</param>
/// <param name="realAssembly">Underlying real assembly.</param>
/// <param name="libraryRoot">Offset path for scripts.</param>
internal SingleScriptAssembly(ApplicationContext/*!*/ applicationContext, Assembly/*!*/ realAssembly, string libraryRoot)
: base(applicationContext, realAssembly)
{
var scriptType = this.GetScriptType();
var subnamespace = string.IsNullOrEmpty(scriptType.Namespace) ? string.Empty : (scriptType.Namespace + ".");
this.module = new ScriptModule(libraryRoot, scriptType, this, subnamespace);
}
/// <summary>
/// Used by the builder, written-up.
/// </summary>
internal SingleScriptAssembly(ApplicationContext/*!*/ applicationContext)
: base(applicationContext)
{
this.module = null; // to be set by the builder
}
#endregion
/// <summary>
/// Gets the script module contained in the assembly.
/// </summary>
public override PhpModule GetModule(PhpSourceFile name)
{
return this.module;
}
/// <summary>
/// Gets a script type stored in a specified single-script assembly.
/// </summary>
internal Type/*!*/GetScriptType()
{
if (this.scriptType == null)
{
var attr = ScriptAssemblyAttribute.Reflect(RealModule.Assembly);
Debug.Assert(attr != null);
Debug.Assert(!attr.IsMultiScript);
Debug.Assert(attr.SSAScriptType != null);
this.scriptType = attr.SSAScriptType;
Debug.Assert(this.scriptType != null);
}
return this.scriptType;
}
/// <summary>
/// Gets an enumerator of script module stored in this single-script assembly.
/// </summary>
public override IEnumerable<ScriptModule> GetModules()
{
yield return this.module;
}
}
#endregion
#region MultiScriptAssembly
/// <summary>
/// Represents a script assembly comprising of multiple script modules.
/// </summary>
public sealed class MultiScriptAssembly : ScriptAssembly
{
/// <summary>
/// Source files to modules mapping.
/// </summary>
internal Dictionary<PhpSourceFile, ScriptModule> Modules { get { return modules; } }
private Dictionary<PhpSourceFile, ScriptModule> modules;
/// <summary>
/// Root path to script in this library.
/// </summary>
private string libraryRoot;
public override bool IsMultiScript { get { return true; } }
/// <summary>
/// Used by assembly loader.
/// </summary>
/// <param name="applicationContext">Current application context.</param>
/// <param name="realAssembly">Underlying real assembly.</param>
/// <param name="libraryRoot">Relative path of root of the library scripts.</param>
internal MultiScriptAssembly(ApplicationContext/*!*/ applicationContext, Assembly/*!*/ realAssembly, string libraryRoot)
: base(applicationContext, realAssembly)
{
this.libraryRoot = libraryRoot;
}
/// <summary>
/// Used by the builder (real assembly is written up).
/// </summary>
internal MultiScriptAssembly(ApplicationContext/*!*/ applicationContext)
: base(applicationContext)
{
this.modules = new Dictionary<PhpSourceFile, ScriptModule>();
}
private void EnsureLibraryReflected()
{
if (modules == null)
lock(this)
if (modules == null)
ReflectAssemblyNoLock();
}
/// <summary>
/// Reflects the assembly and creates ScriptModules.
/// </summary>
private void ReflectAssemblyNoLock()
{
// TODO: this should be changed into ScriptAttribute resolution when all assemblies have this attribute correctly generated
// (same as WebCompilerManager does that)
this.modules = new Dictionary<PhpSourceFile, ScriptModule>();
// go through all types in the assembly
foreach (Type type in RealAssembly.GetTypes()/*GetExportedTypes()*/)
{
//bool isScript = false;
////check whether type implements IPhpScript interface
//foreach (Type iface in type.GetInterfaces())
//{
// if (iface == typeof(IPhpScript))
// {
// isScript = true;
// break;
// }
//}
//if (!isScript) continue;
if (type.IsVisible && type.Name == ScriptModule.ScriptTypeName)
{
//customary . is required
string subnamespace = type.Namespace + ".";
//get script's arbitrary path
string scriptPath = ScriptModule.GetPathFromSubnamespace(subnamespace).ToString();
if (libraryRoot != null)
scriptPath = System.IO.Path.Combine(libraryRoot, scriptPath);
modules.Add(new PhpSourceFile(Configuration.Application.Compiler.SourceRoot, new RelativePath(scriptPath)), new ScriptModule(scriptPath, type, this, subnamespace));
}
}
}
/// <summary>
/// Gets a script module associated with a specified source file.
/// </summary>
public override PhpModule GetModule(PhpSourceFile/*!*/ sourceFile)
{
Debug.Assert(sourceFile != null);
EnsureLibraryReflected();
ScriptModule result;
modules.TryGetValue(sourceFile, out result);
return result;
}
/// <summary>
/// Adds a new script module. Used by builder.
/// </summary>
internal void AddScriptModule(PhpSourceFile/*!*/ sourceFile, ScriptModule/*!*/ module)
{
modules.Add(sourceFile, module);
}
/// <summary>
/// Gets a full qualified name of a script type given a sub-namespace.
/// </summary>
/// <param name="sourceFile">Source file.</param>
/// <returns>The qualified name.</returns>
public string GetQualifiedScriptTypeName(PhpSourceFile/*!*/ sourceFile)
{
Debug.Assert(sourceFile != null);
return GetQualifiedScriptTypeName(ScriptModule.GetSubnamespace(sourceFile.RelativePath, true));
}
/// <summary>
/// Determine if script specified by <paramref name="fullPath"/> is loaded in script library.
/// </summary>
/// <param name="fullPath">The script path.</param>
/// <returns>True if given script is loaded.</returns>
internal bool ScriptExists(FullPath fullPath)
{
EnsureLibraryReflected();
PhpSourceFile source_file = new PhpSourceFile(Configuration.Application.Compiler.SourceRoot, fullPath);
return modules.ContainsKey(source_file);
}
/// <summary>
/// Gets an enumerator of script modules stored in this multi-script assembly.
/// </summary>
public override IEnumerable<ScriptModule> GetModules()
{
EnsureLibraryReflected();
return modules.Values;
}
}
#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.IO;
using System.Reflection;
using Xunit;
namespace System.Diagnostics.TraceSourceTests
{
using Method = TestTraceListener.Method;
public class TraceClassTests : IDisposable
{
private readonly string TestRunnerAssemblyName = Assembly.GetEntryAssembly().GetName().Name;
void IDisposable.Dispose()
{
TraceTestHelper.ResetState();
}
[Fact]
public void AutoFlushTest()
{
Trace.AutoFlush = false;
Assert.False(Trace.AutoFlush);
Trace.AutoFlush = true;
Assert.True(Trace.AutoFlush);
}
[Fact]
public void UseGlobalLockTest()
{
Trace.UseGlobalLock = true;
Assert.True(Trace.UseGlobalLock);
Trace.UseGlobalLock = false;
Assert.False(Trace.UseGlobalLock);
}
[Fact]
public void RefreshTest()
{
Trace.UseGlobalLock = true;
Assert.True(Trace.UseGlobalLock);
// NOTE: Refresh does not reset to default config values
Trace.Refresh();
Assert.True(Trace.UseGlobalLock);
}
[Theory]
[InlineData(1, 1)]
[InlineData(2, 2)]
[InlineData(-2, 0)]
public void IndentLevelTest(int indent, int expected)
{
Trace.Listeners.Clear();
Trace.Listeners.Add(new DefaultTraceListener());
Trace.IndentLevel = indent;
Assert.Equal(expected, Trace.IndentLevel);
foreach (TraceListener listener in Trace.Listeners)
{
Assert.Equal(expected, listener.IndentLevel);
}
}
[Theory]
[InlineData(1, 1)]
[InlineData(2, 2)]
[InlineData(-2, 0)]
public void IndentSizeTest(int indent, int expected)
{
Trace.Listeners.Clear();
Trace.Listeners.Add(new DefaultTraceListener());
Trace.IndentSize = indent;
Assert.Equal(expected, Trace.IndentSize);
foreach (TraceListener listener in Trace.Listeners)
{
Assert.Equal(expected, listener.IndentSize);
}
}
[Fact]
public void FlushTest()
{
var listener = new TestTextTraceListener();
Trace.Listeners.Clear();
Trace.AutoFlush = false;
Trace.Listeners.Add(listener);
Trace.Write("Test");
Assert.DoesNotContain("Test", listener.Output);
Trace.Flush();
Assert.Contains("Test", listener.Output);
}
[Fact]
public void CloseTest()
{
var listener = new TestTraceListener();
Trace.Listeners.Add(listener);
Trace.Close();
Assert.Equal(1, listener.GetCallCount(Method.Close));
}
[Fact]
public void Assert1Test()
{
var listener = new TestTraceListener();
// We have to clear the listeners list on Trace since there is a trace listener by default with AssertUiEnabled = true in Desktop and that will pop up an assert window with Trace.Fail
Trace.Listeners.Clear();
Trace.Listeners.Add(listener);
Trace.Assert(true);
Assert.Equal(0, listener.GetCallCount(Method.WriteLine));
Assert.Equal(0, listener.GetCallCount(Method.Fail));
Trace.Assert(false);
Assert.Equal(0, listener.GetCallCount(Method.WriteLine));
Assert.Equal(1, listener.GetCallCount(Method.Fail));
}
[Fact]
public void Assert2Test()
{
var listener = new TestTraceListener();
var text = new TestTextTraceListener();
// We have to clear the listeners list on Trace since there is a trace listener by default with AssertUiEnabled = true in Desktop and that will pop up an assert window with Trace.Fail
Trace.Listeners.Clear();
Trace.Listeners.Add(listener);
Trace.Listeners.Add(text);
Trace.Assert(true, "Message");
Assert.Equal(0, listener.GetCallCount(Method.WriteLine));
Assert.Equal(0, listener.GetCallCount(Method.Fail));
text.Flush();
Assert.DoesNotContain("Message", text.Output);
Trace.Assert(false, "Message");
Assert.Equal(0, listener.GetCallCount(Method.WriteLine));
Assert.Equal(1, listener.GetCallCount(Method.Fail));
text.Flush();
Assert.Contains("Message", text.Output);
}
[Fact]
public void Assert3Test()
{
var listener = new TestTraceListener();
var text = new TestTextTraceListener();
// We have to clear the listeners list on Trace since there is a trace listener by default with AssertUiEnabled = true in Desktop and that will pop up an assert window with Trace.Fail
Trace.Listeners.Clear();
Trace.Listeners.Add(listener);
Trace.Listeners.Add(text);
Trace.Assert(true, "Message", "Detail");
Assert.Equal(0, listener.GetCallCount(Method.WriteLine));
Assert.Equal(0, listener.GetCallCount(Method.Fail));
text.Flush();
Assert.DoesNotContain("Message", text.Output);
Trace.Assert(false, "Message", "Detail");
Assert.Equal(0, listener.GetCallCount(Method.WriteLine));
Assert.Equal(1, listener.GetCallCount(Method.Fail));
text.Flush();
Assert.Contains("Message", text.Output);
Assert.Contains("Detail", text.Output);
}
[Fact]
public void WriteTest()
{
var listener = new TestTextTraceListener();
Trace.Listeners.Add(listener);
Trace.Write("Message", "Category");
Trace.Flush();
Assert.Equal("Category: Message", listener.Output);
}
[Fact]
public void WriteObject1Test()
{
var listener = new TestTextTraceListener();
Trace.Listeners.Add(listener);
Trace.Write((object)"Text");
listener.Flush();
Assert.Equal("Text", listener.Output);
}
[Fact]
public void WriteObject2Test()
{
var listener = new TestTextTraceListener();
Trace.Listeners.Add(listener);
Trace.Write((object)"Message", "Category");
Trace.Flush();
Assert.Equal("Category: Message", listener.Output);
}
[Fact]
public void WriteLineObjectTest()
{
var listener = new TestTextTraceListener();
Trace.Listeners.Add(listener);
Trace.WriteLine((object)"Text");
listener.Flush();
Assert.Equal("Text" + Environment.NewLine, listener.Output);
}
[Fact]
public void WriteLine1Test()
{
var listener = new TestTextTraceListener();
Trace.Listeners.Add(listener);
Trace.WriteLine("Message", "Category");
listener.Flush();
Assert.Equal("Category: Message" + Environment.NewLine, listener.Output);
}
[Fact]
public void WriteLine2Test()
{
var listener = new TestTextTraceListener();
Trace.Listeners.Add(listener);
Trace.WriteLine((object)"Message", "Category");
listener.Flush();
Assert.Equal("Category: Message" + Environment.NewLine, listener.Output);
}
[Fact]
public void WriteIf1Test()
{
var listener = new TestTraceListener();
Trace.Listeners.Add(listener);
Trace.WriteIf(false, (object)"Message");
Assert.Equal(0, listener.GetCallCount(Method.Write));
Trace.WriteIf(true, (object)"Message");
Assert.Equal(1, listener.GetCallCount(Method.Write));
}
[Fact]
public void WriteIf2Test()
{
var listener = new TestTraceListener();
Trace.Listeners.Add(listener);
Trace.WriteIf(false, "Message");
Assert.Equal(0, listener.GetCallCount(Method.Write));
Trace.WriteIf(true, "Message");
Assert.Equal(1, listener.GetCallCount(Method.Write));
}
[Fact]
public void WriteIf3Test()
{
var listener = new TestTraceListener();
Trace.Listeners.Add(listener);
Trace.WriteIf(false, (object)"Message", "Category");
Assert.Equal(0, listener.GetCallCount(Method.Write));
Trace.WriteIf(true, (object)"Message", "Category");
Assert.Equal(1, listener.GetCallCount(Method.Write));
}
[Fact]
public void WriteIf4Test()
{
var listener = new TestTraceListener();
Trace.Listeners.Add(listener);
Trace.WriteIf(false, "Message", "Category");
Assert.Equal(0, listener.GetCallCount(Method.Write));
Trace.WriteIf(true, "Message", "Category");
Assert.Equal(1, listener.GetCallCount(Method.Write));
}
[Fact]
public void WriteLineIf1Test()
{
var listener = new TestTraceListener();
Trace.Listeners.Add(listener);
Trace.WriteLineIf(false, (object)"Message");
Assert.Equal(0, listener.GetCallCount(Method.WriteLine));
Trace.WriteLineIf(true, (object)"Message");
Assert.Equal(1, listener.GetCallCount(Method.WriteLine));
}
[Fact]
public void WriteLineIf2Test()
{
var listener = new TestTraceListener();
Trace.Listeners.Add(listener);
Trace.WriteLineIf(false, "Message");
Assert.Equal(0, listener.GetCallCount(Method.WriteLine));
Trace.WriteLineIf(true, "Message");
Assert.Equal(1, listener.GetCallCount(Method.WriteLine));
}
[Fact]
public void WriteLineIf3Test()
{
var listener = new TestTraceListener();
Trace.Listeners.Add(listener);
Trace.WriteLineIf(false, (object)"Message", "Category");
Assert.Equal(0, listener.GetCallCount(Method.WriteLine));
Trace.WriteLineIf(true, (object)"Message", "Category");
Assert.Equal(1, listener.GetCallCount(Method.WriteLine));
}
[Fact]
public void WriteLineIf4Test()
{
var listener = new TestTraceListener();
Trace.Listeners.Add(listener);
Trace.WriteLineIf(false, "Message", "Category");
Assert.Equal(0, listener.GetCallCount(Method.WriteLine));
Trace.WriteLineIf(true, "Message", "Category");
Assert.Equal(1, listener.GetCallCount(Method.WriteLine));
}
[Fact]
public void FailTest()
{
var listener = new TestTraceListener();
// We have to clear the listeners list on Trace since there is a trace listener by default with AssertUiEnabled = true in Desktop and that will pop up an assert window with Trace.Fail
Trace.Listeners.Clear();
Trace.Listeners.Add(listener);
Trace.Fail("Text");
Assert.Equal(1, listener.GetCallCount(Method.Fail));
Trace.Fail("Text", "Detail");
Assert.Equal(2, listener.GetCallCount(Method.Fail));
}
[Fact]
public void TraceTest01()
{
var textTL = new TestTextTraceListener();
Trace.Listeners.Add(textTL);
Trace.IndentLevel = 0;
Trace.WriteLine("Message start.");
Trace.IndentSize = 2;
Trace.IndentLevel = 2;
Trace.Write("This message should be indented.");
Trace.TraceError("This error not be indented.");
Trace.TraceError("{0}", "This error is indented");
Trace.TraceWarning("This warning is indented");
Trace.TraceWarning("{0}", "This warning is also indented");
Trace.TraceInformation("This information in indented");
Trace.TraceInformation("{0}", "This information is also indented");
Trace.IndentSize = 0;
Trace.IndentLevel = 0;
Trace.WriteLine("Message end.");
textTL.Flush();
string newLine = Environment.NewLine;
var expected =
string.Format(
"Message start." + newLine + " This message should be indented.{0} Error: 0 : This error not be indented." + newLine + " {0} Error: 0 : This error is indented" + newLine + " {0} Warning: 0 : This warning is indented" + newLine + " {0} Warning: 0 : This warning is also indented" + newLine + " {0} Information: 0 : This information in indented" + newLine + " {0} Information: 0 : This information is also indented" + newLine + "Message end." + newLine + "",
TestRunnerAssemblyName
);
Assert.Equal(expected, textTL.Output);
}
[Fact]
public void TraceTest02()
{
string newLine = Environment.NewLine;
var textTL = new TestTextTraceListener();
Trace.Listeners.Clear();
Trace.Listeners.Add(textTL);
Trace.IndentLevel = 0;
Trace.Fail("");
textTL.Flush();
var fail = textTL.Output.TrimEnd(newLine.ToCharArray());
textTL = new TestTextTraceListener();
// We have to clear the listeners list on Trace since there is a trace listener by default with AssertUiEnabled = true in Desktop and that will pop up an assert window with Trace.Fail
Trace.Listeners.Clear();
Trace.Listeners.Add(textTL);
Trace.IndentLevel = 0;
Trace.IndentSize = 2;
Trace.WriteLineIf(true, "Message start.");
Trace.Indent();
Trace.Indent();
Trace.WriteIf(true, "This message should be indented.");
Trace.WriteIf(false, "This message should be ignored.");
Trace.Indent();
Trace.WriteLine("This should not be indented.");
Trace.WriteLineIf(false, "This message will be ignored");
Trace.Fail("This failure is reported", "with a detailed message");
Trace.Assert(false);
Trace.Assert(false, "This assert is reported");
Trace.Assert(true, "This assert is not reported");
Trace.Unindent();
Trace.Unindent();
Trace.Unindent();
Trace.WriteLine("Message end.");
textTL.Flush();
newLine = Environment.NewLine;
var expected = "Message start." + newLine + " This message should be indented.This should not be indented." + newLine + " " + fail + "This failure is reported with a detailed message" + newLine + " " + fail + newLine + " " + fail + "This assert is reported" + newLine + "Message end." + newLine;
Assert.Equal(expected, textTL.Output);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.