context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Orleans.Internal;
using static Orleans.Runtime.MembershipService.SiloHealthMonitor;
namespace Orleans.Runtime.MembershipService
{
/// <summary>
/// Responsible for monitoring an individual remote silo.
/// </summary>
internal class SiloHealthMonitor : ITestAccessor
{
private readonly ILogger log;
private readonly IRemoteSiloProber prober;
private readonly CancellationTokenSource stoppingCancellation = new CancellationTokenSource();
private readonly Task stopping;
private readonly object lockObj = new object();
/// <summary>
/// The id of the next probe.
/// </summary>
private long nextProbeId;
/// <summary>
/// The highest internal probe number which has completed.
/// </summary>
private long highestCompletedProbeId = -1;
/// <summary>
/// The number of failed probes since the last successful probe.
/// </summary>
private int missedProbes;
public SiloHealthMonitor(
SiloAddress siloAddress,
ILoggerFactory loggerFactory,
IRemoteSiloProber remoteSiloProber)
{
this.stopping = this.stoppingCancellation.Token.WhenCancelled();
this.SiloAddress = siloAddress;
this.prober = remoteSiloProber;
this.log = loggerFactory.CreateLogger<SiloHealthMonitor>();
}
internal interface ITestAccessor
{
int MissedProbes { get; }
}
/// <summary>
/// The silo which this instance is responsible for.
/// </summary>
public SiloAddress SiloAddress { get; }
/// <summary>
/// Whether or not this monitor is canceled.
/// </summary>
public bool IsCanceled => this.stoppingCancellation.IsCancellationRequested;
int ITestAccessor.MissedProbes => this.missedProbes;
public void Cancel() => this.stoppingCancellation.Cancel();
/// <summary>
/// Probes the remote silo.
/// </summary>
/// <param name="diagnosticProbeNumber">The probe number, for diagnostic purposes.</param>
/// <param name="cancellation">A token to cancel and fail the probe attempt.</param>
/// <returns>The number of failed probes since the last successful probe.</returns>
public async Task<int> Probe(int diagnosticProbeNumber, CancellationToken cancellation)
{
var id = Interlocked.Increment(ref this.nextProbeId);
if (this.log.IsEnabled(LogLevel.Trace))
{
this.log.LogTrace("Going to send Ping #{ProbeNumber}/{Id} to probe silo {Silo}", diagnosticProbeNumber, id, this.SiloAddress);
}
bool probeResult;
try
{
var probeCancellation = cancellation.WhenCancelled();
var probeTask = prober.Probe(SiloAddress, diagnosticProbeNumber);
var task = await Task.WhenAny(stopping, probeCancellation, probeTask);
if (ReferenceEquals(task, stopping))
{
probeTask.Ignore();
probeResult = false;
}
else if (ReferenceEquals(task, probeCancellation))
{
probeTask.Ignore();
probeResult = this.RecordFailure(id, diagnosticProbeNumber, new OperationCanceledException($"The ping attempt was cancelled. Ping #{diagnosticProbeNumber}/{id}"));
}
else
{
await probeTask;
probeResult = this.RecordSuccess(id, diagnosticProbeNumber);
}
}
catch (Exception exception)
{
probeResult = this.RecordFailure(id, diagnosticProbeNumber, exception);
}
// If the probe finished and the result was valid then return the number of missed probes.
if (probeResult) return this.missedProbes;
// The probe was superseded or the monitor is being shutdown.
return -1;
}
private bool RecordSuccess(long id, int diagnosticProbeNumber)
{
if (this.log.IsEnabled(LogLevel.Trace))
{
this.log.LogTrace("Got successful ping response for ping #{ProbeNumber}/{Id} from {Silo}", diagnosticProbeNumber, id, this.SiloAddress);
}
MessagingStatisticsGroup.OnPingReplyReceived(this.SiloAddress);
lock (this.lockObj)
{
if (id <= this.highestCompletedProbeId)
{
this.log.Info(
"Ignoring success result for ping #{ProbeNumber}/{Id} from {Silo} since a later probe has already completed. Highest ({HighestCompletedProbeId}) > Current ({CurrentProbeId})",
diagnosticProbeNumber,
id,
this.SiloAddress,
this.highestCompletedProbeId,
id);
return false;
}
else if (this.stoppingCancellation.IsCancellationRequested)
{
this.log.Info(
"Ignoring success result for ping #{ProbeNumber}/{Id} from {Silo} since this monitor has been stopped",
diagnosticProbeNumber,
id,
this.SiloAddress);
return false;
}
else
{
this.highestCompletedProbeId = id;
Interlocked.Exchange(ref this.missedProbes, 0);
return true;
}
}
}
private bool RecordFailure(long id, int diagnosticProbeNumber, Exception failureReason)
{
if (this.log.IsEnabled(LogLevel.Trace))
{
this.log.LogTrace("Got failed ping response for ping #{ProbeNumber}/{Id} from {Silo}: {Exception}", diagnosticProbeNumber, id, this.SiloAddress, failureReason);
}
MessagingStatisticsGroup.OnPingReplyMissed(this.SiloAddress);
lock (this.lockObj)
{
if (id <= this.highestCompletedProbeId)
{
this.log.Info(
"Ignoring failure result for ping #{ProbeNumber}/{Id} from {Silo} since a later probe has already completed. Highest completed id ({HighestCompletedProbeId})",
diagnosticProbeNumber,
id,
this.SiloAddress,
this.highestCompletedProbeId,
id);
return false;
}
else if (this.stoppingCancellation.IsCancellationRequested)
{
this.log.Info(
"Ignoring failure result for ping #{ProbeNumber}/{Id} from {Silo} since this monitor has been stopped",
diagnosticProbeNumber,
id,
this.SiloAddress);
return false;
}
else
{
this.highestCompletedProbeId = id;
var missed = Interlocked.Increment(ref this.missedProbes);
this.log.LogWarning(
(int)ErrorCode.MembershipMissedPing,
"Did not get ping response for ping #{ProbeNumber}/{Id} from {Silo}: {Exception}",
diagnosticProbeNumber,
id,
this.SiloAddress,
failureReason);
if (this.log.IsEnabled(LogLevel.Trace))
{
this.log.LogTrace("Current number of failed probes for {Silo}: {MissedProbes}", this.SiloAddress, missed);
}
return true;
}
}
}
}
}
| |
#pragma warning disable 612,618
using DevExpress.Mvvm.Native;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
#if !MONO
#if !NETFX_CORE
using System.Windows.Threading;
#else
using Windows.UI.Xaml;
using Windows.UI.Core;
#endif
#endif
namespace DevExpress.Mvvm {
public abstract class CommandBase {
#if !SILVERLIGHT && !NETFX_CORE && !MONO
static bool defaultUseCommandManager = true;
public static bool DefaultUseCommandManager { get { return defaultUseCommandManager; } set { defaultUseCommandManager = value; } }
#endif
}
public abstract class CommandBase<T> : CommandBase, ICommand, IDelegateCommand {
protected Func<T, bool> canExecuteMethod = null;
protected bool useCommandManager;
event EventHandler canExecuteChanged;
public event EventHandler CanExecuteChanged {
add {
if(useCommandManager) {
#if !SILVERLIGHT && !NETFX_CORE && !MONO
CommandManager.RequerySuggested += value;
#endif
}
else {
canExecuteChanged += value;
}
}
remove {
if(useCommandManager) {
#if !SILVERLIGHT && !NETFX_CORE && !MONO
CommandManager.RequerySuggested -= value;
#endif
}
else {
canExecuteChanged -= value;
}
}
}
#if !SILVERLIGHT && !NETFX_CORE && !MONO
public CommandBase(bool? useCommandManager = null) {
this.useCommandManager = useCommandManager ?? DefaultUseCommandManager;
}
#else
public CommandBase() {
this.useCommandManager = false;
}
#endif
public virtual bool CanExecute(T parameter) {
if(canExecuteMethod == null) return true;
return canExecuteMethod(parameter);
}
public abstract void Execute(T parameter);
public void RaiseCanExecuteChanged() {
if(useCommandManager) {
#if !SILVERLIGHT && !NETFX_CORE && !MONO
CommandManager.InvalidateRequerySuggested();
#endif
}
else {
OnCanExecuteChanged();
}
}
protected virtual void OnCanExecuteChanged() {
if(canExecuteChanged != null)
canExecuteChanged(this, EventArgs.Empty);
}
bool ICommand.CanExecute(object parameter) {
return CanExecute(GetGenericParameter(parameter, true));
}
void ICommand.Execute(object parameter) {
Execute(GetGenericParameter(parameter));
}
static T GetGenericParameter(object parameter, bool suppressCastException = false) {
parameter = TypeCastHelper.TryCast(parameter, typeof(T));
if(parameter == null || parameter is T) return (T)parameter;
if(suppressCastException) return default(T);
throw new InvalidCastException(string.Format("CommandParameter: Unable to cast object of type '{0}' to type '{1}'", parameter.GetType().FullName, typeof(T).FullName));
}
}
public abstract class DelegateCommandBase<T> : CommandBase<T> {
protected Action<T> executeMethod = null;
void Init(Action<T> executeMethod, Func<T, bool> canExecuteMethod) {
if(executeMethod == null && canExecuteMethod == null)
throw new ArgumentNullException("executeMethod");
this.executeMethod = executeMethod;
this.canExecuteMethod = canExecuteMethod;
}
#if !SILVERLIGHT && !NETFX_CORE && !MONO
public DelegateCommandBase(Action<T> executeMethod)
: this(executeMethod, null, null) {
}
public DelegateCommandBase(Action<T> executeMethod, bool useCommandManager)
: this(executeMethod, null, useCommandManager) {
}
public DelegateCommandBase(Action<T> executeMethod, Func<T, bool> canExecuteMethod, bool? useCommandManager = null)
: base(useCommandManager) {
Init(executeMethod, canExecuteMethod);
}
#else
public DelegateCommandBase(Action<T> executeMethod)
: this(executeMethod, null) {
}
public DelegateCommandBase(Action<T> executeMethod, Func<T, bool> canExecuteMethod)
: base() {
Init(executeMethod, canExecuteMethod);
}
#endif
}
public abstract class AsyncCommandBase<T> : CommandBase<T>, INotifyPropertyChanged {
protected Func<T, Task> executeMethod = null;
void Init(Func<T, Task> executeMethod, Func<T, bool> canExecuteMethod) {
if(executeMethod == null && canExecuteMethod == null)
throw new ArgumentNullException("executeMethod");
this.executeMethod = executeMethod;
this.canExecuteMethod = canExecuteMethod;
}
#if !SILVERLIGHT && !NETFX_CORE && !MONO
public AsyncCommandBase(Func<T, Task> executeMethod)
: this(executeMethod, null, null) {
}
public AsyncCommandBase(Func<T, Task> executeMethod, bool useCommandManager)
: this(executeMethod, null, useCommandManager) {
}
public AsyncCommandBase(Func<T, Task> executeMethod, Func<T, bool> canExecuteMethod, bool? useCommandManager = null)
: base(useCommandManager) {
Init(executeMethod, canExecuteMethod);
}
#else
public AsyncCommandBase(Func<T, Task> executeMethod)
: this(executeMethod, null) {
}
public AsyncCommandBase(Func<T, Task> executeMethod, Func<T, bool> canExecuteMethod)
: base() {
Init(executeMethod, canExecuteMethod);
}
#endif
event PropertyChangedEventHandler propertyChanged;
event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged {
add { propertyChanged += value; }
remove { propertyChanged -= value; }
}
protected void RaisePropertyChanged(string propName) {
if(propertyChanged != null)
propertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
public class DelegateCommand<T> : DelegateCommandBase<T> {
#if !SILVERLIGHT && !NETFX_CORE && !MONO
public DelegateCommand(Action<T> executeMethod)
: this(executeMethod, null, null) {
}
public DelegateCommand(Action<T> executeMethod, bool useCommandManager)
: this(executeMethod, null, useCommandManager) {
}
public DelegateCommand(Action<T> executeMethod, Func<T, bool> canExecuteMethod, bool? useCommandManager = null)
: base(executeMethod, canExecuteMethod, useCommandManager) {
}
#else
public DelegateCommand(Action<T> executeMethod)
: this(executeMethod, null) {
}
public DelegateCommand(Action<T> executeMethod, Func<T, bool> canExecuteMethod)
: base(executeMethod, canExecuteMethod) {
}
#endif
public override void Execute(T parameter) {
if(!CanExecute(parameter))
return;
if(executeMethod == null) return;
executeMethod(parameter);
}
}
public class DelegateCommand : DelegateCommand<object> {
#if !SILVERLIGHT && !NETFX_CORE && !MONO
public DelegateCommand(Action executeMethod)
: this(executeMethod, null, null) {
}
public DelegateCommand(Action executeMethod, bool useCommandManager)
: this(executeMethod, null, useCommandManager) {
}
public DelegateCommand(Action executeMethod, Func<bool> canExecuteMethod, bool? useCommandManager = null)
: base(
executeMethod != null ? (Action<object>)(o => executeMethod()) : null,
canExecuteMethod != null ? (Func<object, bool>)(o => canExecuteMethod()) : null,
useCommandManager) {
}
#else
public DelegateCommand(Action executeMethod)
: this(executeMethod, null) {
}
public DelegateCommand(Action executeMethod, Func<bool> canExecuteMethod)
: base(
executeMethod != null ? (Action<object>)(o => executeMethod()) : null,
canExecuteMethod != null ? (Func<object, bool>)(o => canExecuteMethod()) : null) {
}
#endif
}
public class AsyncCommand<T> : AsyncCommandBase<T>, IAsyncCommand {
bool allowMultipleExecution = false;
bool isExecuting = false;
CancellationTokenSource cancellationTokenSource;
bool shouldCancel = false;
internal Task executeTask;
public bool AllowMultipleExecution {
get { return allowMultipleExecution; }
set { allowMultipleExecution = value; }
}
public bool IsExecuting {
get { return isExecuting; }
private set {
if(isExecuting == value) return;
isExecuting = value;
RaisePropertyChanged(BindableBase.GetPropertyName(() => IsExecuting));
OnIsExecutingChanged();
}
}
public CancellationTokenSource CancellationTokenSource {
get { return cancellationTokenSource; }
private set {
if(cancellationTokenSource == value) return;
cancellationTokenSource = value;
RaisePropertyChanged(BindableBase.GetPropertyName(() => CancellationTokenSource));
}
}
[Obsolete("This property is obsolete. Use the IsCancellationRequested property instead.")]
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public bool ShouldCancel {
get { return shouldCancel; }
private set {
if(shouldCancel == value) return;
shouldCancel = value;
RaisePropertyChanged(BindableBase.GetPropertyName(() => ShouldCancel));
}
}
public bool IsCancellationRequested {
get {
if(CancellationTokenSource == null) return false;
return CancellationTokenSource.IsCancellationRequested;
}
}
public DelegateCommand CancelCommand { get; private set; }
ICommand IAsyncCommand.CancelCommand { get { return CancelCommand; } }
#if !SILVERLIGHT && !NETFX_CORE && !MONO
public AsyncCommand(Func<T, Task> executeMethod)
: this(executeMethod, null, false, null) {
}
public AsyncCommand(Func<T, Task> executeMethod, bool useCommandManager)
: this(executeMethod, null, false, useCommandManager) {
}
public AsyncCommand(Func<T, Task> executeMethod, Func<T, bool> canExecuteMethod, bool? useCommandManager = null)
: this(executeMethod, canExecuteMethod, false, useCommandManager) {
}
public AsyncCommand(Func<T, Task> executeMethod, Func<T, bool> canExecuteMethod, bool allowMultipleExecution, bool? useCommandManager = null)
: base(executeMethod, canExecuteMethod, useCommandManager) {
CancelCommand = new DelegateCommand(Cancel, CanCancel, false);
AllowMultipleExecution = allowMultipleExecution;
}
#else
public AsyncCommand(Func<T, Task> executeMethod)
: this(executeMethod, null, false) {
}
public AsyncCommand(Func<T, Task> executeMethod, Func<T, bool> canExecuteMethod)
: this(executeMethod, canExecuteMethod, false) {
}
public AsyncCommand(Func<T, Task> executeMethod, Func<T, bool> canExecuteMethod, bool allowMultipleExecution)
: base(executeMethod, canExecuteMethod) {
CancelCommand = new DelegateCommand(Cancel);
AllowMultipleExecution = allowMultipleExecution;
}
#endif
public override bool CanExecute(T parameter) {
if(!AllowMultipleExecution && IsExecuting) return false;
return base.CanExecute(parameter);
}
public override void Execute(T parameter) {
if(!CanExecute(parameter))
return;
if(executeMethod == null) return;
IsExecuting = true;
#if SILVERLIGHT
Dispatcher dispatcher = Deployment.Current.Dispatcher;
#elif NETFX_CORE
var dispatcher = Window.Current.Dispatcher;
#elif MONO
var scheduler = TaskScheduler.FromCurrentSynchronizationContext();
#else
Dispatcher dispatcher = Dispatcher.CurrentDispatcher;
#endif
CancellationTokenSource = new CancellationTokenSource();
executeTask = executeMethod(parameter).ContinueWith(x =>
{
#if !MONO
#if !NETFX_CORE
dispatcher.BeginInvoke(new Action(() => {
IsExecuting = false;
ShouldCancel = false;
}));
#else
#pragma warning disable 4014
dispatcher.RunAsync(CoreDispatcherPriority.Normal, new DispatchedHandler(() => {
IsExecuting = false;
ShouldCancel = false;
}));
#pragma warning restore 4014
#endif
});
#else
IsExecuting = false;
ShouldCancel = false;
}, scheduler);
#endif
}
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public void Cancel() {
if(!CanCancel()) return;
ShouldCancel = true;
CancellationTokenSource.Cancel();
}
bool CanCancel() {
return IsExecuting;
}
void OnIsExecutingChanged() {
CancelCommand.RaiseCanExecuteChanged();
RaiseCanExecuteChanged();
}
}
public class AsyncCommand : AsyncCommand<object> {
#if !SILVERLIGHT && !NETFX_CORE && !MONO
public AsyncCommand(Func<Task> executeMethod)
: this(executeMethod, null, false, null) {
}
public AsyncCommand(Func<Task> executeMethod, bool useCommandManager)
: this(executeMethod, null, false, useCommandManager) {
}
public AsyncCommand(Func<Task> executeMethod, Func<bool> canExecuteMethod, bool? useCommandManager = null)
: this(executeMethod, canExecuteMethod, false, useCommandManager) {
}
public AsyncCommand(Func<Task> executeMethod, Func<bool> canExecuteMethod, bool allowMultipleExecution, bool? useCommandManager = null)
: base(
executeMethod != null ? (Func<object, Task>)(o => executeMethod()) : null,
canExecuteMethod != null ? (Func<object, bool>)(o => canExecuteMethod()) : null,
allowMultipleExecution,
useCommandManager) {
}
#else
public AsyncCommand(Func<Task> executeMethod)
: this(executeMethod, null, false) {
}
public AsyncCommand(Func<Task> executeMethod, Func<bool> canExecuteMethod)
: this(executeMethod, canExecuteMethod, false) {
}
public AsyncCommand(Func<Task> executeMethod, Func<bool> canExecuteMethod, bool allowMultipleExecution)
: base(
executeMethod != null ? (Func<object, Task>)(o => executeMethod()) : null,
canExecuteMethod != null ? (Func<object, bool>)(o => canExecuteMethod()) : null,
allowMultipleExecution) {
}
#endif
}
}
#pragma warning restore 612, 618
| |
/*
* CP20866.cs - Cyrillic (KOI8-R) code page.
*
* 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
*/
// Generated from "ibm-878.ucm".
namespace I18N.Other
{
using System;
using I18N.Common;
public class CP20866 : ByteEncoding
{
public CP20866()
: base(20866, ToChars, "Cyrillic (KOI8-R)",
"koi8-r", "koi8-r", "koi8-r",
true, true, true, true, 1251)
{}
private static readonly char[] ToChars = {
'\u0000', '\u0001', '\u0002', '\u0003', '\u0004', '\u0005',
'\u0006', '\u0007', '\u0008', '\u0009', '\u000A', '\u000B',
'\u000C', '\u000D', '\u000E', '\u000F', '\u0010', '\u0011',
'\u0012', '\u0013', '\u0014', '\u0015', '\u0016', '\u0017',
'\u0018', '\u0019', '\u001A', '\u001B', '\u001C', '\u001D',
'\u001E', '\u001F', '\u0020', '\u0021', '\u0022', '\u0023',
'\u0024', '\u0025', '\u0026', '\u0027', '\u0028', '\u0029',
'\u002A', '\u002B', '\u002C', '\u002D', '\u002E', '\u002F',
'\u0030', '\u0031', '\u0032', '\u0033', '\u0034', '\u0035',
'\u0036', '\u0037', '\u0038', '\u0039', '\u003A', '\u003B',
'\u003C', '\u003D', '\u003E', '\u003F', '\u0040', '\u0041',
'\u0042', '\u0043', '\u0044', '\u0045', '\u0046', '\u0047',
'\u0048', '\u0049', '\u004A', '\u004B', '\u004C', '\u004D',
'\u004E', '\u004F', '\u0050', '\u0051', '\u0052', '\u0053',
'\u0054', '\u0055', '\u0056', '\u0057', '\u0058', '\u0059',
'\u005A', '\u005B', '\u005C', '\u005D', '\u005E', '\u005F',
'\u0060', '\u0061', '\u0062', '\u0063', '\u0064', '\u0065',
'\u0066', '\u0067', '\u0068', '\u0069', '\u006A', '\u006B',
'\u006C', '\u006D', '\u006E', '\u006F', '\u0070', '\u0071',
'\u0072', '\u0073', '\u0074', '\u0075', '\u0076', '\u0077',
'\u0078', '\u0079', '\u007A', '\u007B', '\u007C', '\u007D',
'\u007E', '\u007F', '\u2500', '\u2502', '\u250C', '\u2510',
'\u2514', '\u2518', '\u251C', '\u2524', '\u252C', '\u2534',
'\u253C', '\u2580', '\u2584', '\u2588', '\u258C', '\u2590',
'\u2591', '\u2592', '\u2593', '\u2320', '\u25A0', '\u2219',
'\u221A', '\u2248', '\u2264', '\u2265', '\u00A0', '\u2321',
'\u00B0', '\u00B2', '\u00B7', '\u00F7', '\u2550', '\u2551',
'\u2552', '\u0451', '\u2553', '\u2554', '\u2555', '\u2556',
'\u2557', '\u2558', '\u2559', '\u255A', '\u255B', '\u255C',
'\u255D', '\u255E', '\u255F', '\u2560', '\u2561', '\u0401',
'\u2562', '\u2563', '\u2564', '\u2565', '\u2566', '\u2567',
'\u2568', '\u2569', '\u256A', '\u256B', '\u256C', '\u00A9',
'\u044E', '\u0430', '\u0431', '\u0446', '\u0434', '\u0435',
'\u0444', '\u0433', '\u0445', '\u0438', '\u0439', '\u043A',
'\u043B', '\u043C', '\u043D', '\u043E', '\u043F', '\u044F',
'\u0440', '\u0441', '\u0442', '\u0443', '\u0436', '\u0432',
'\u044C', '\u044B', '\u0437', '\u0448', '\u044D', '\u0449',
'\u0447', '\u044A', '\u042E', '\u0410', '\u0411', '\u0426',
'\u0414', '\u0415', '\u0424', '\u0413', '\u0425', '\u0418',
'\u0419', '\u041A', '\u041B', '\u041C', '\u041D', '\u041E',
'\u041F', '\u042F', '\u0420', '\u0421', '\u0422', '\u0423',
'\u0416', '\u0412', '\u042C', '\u042B', '\u0417', '\u0428',
'\u042D', '\u0429', '\u0427', '\u042A',
};
protected override void ToBytes(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
int ch;
while(charCount > 0)
{
ch = (int)(chars[charIndex++]);
if(ch >= 128) switch(ch)
{
case 0x00A0: ch = 0x9A; break;
case 0x00A9: ch = 0xBF; break;
case 0x00B0: ch = 0x9C; break;
case 0x00B2: ch = 0x9D; break;
case 0x00B7: ch = 0x9E; break;
case 0x00F7: ch = 0x9F; break;
case 0x0401: ch = 0xB3; break;
case 0x0410: ch = 0xE1; break;
case 0x0411: ch = 0xE2; break;
case 0x0412: ch = 0xF7; break;
case 0x0413: ch = 0xE7; break;
case 0x0414: ch = 0xE4; break;
case 0x0415: ch = 0xE5; break;
case 0x0416: ch = 0xF6; break;
case 0x0417: ch = 0xFA; break;
case 0x0418:
case 0x0419:
case 0x041A:
case 0x041B:
case 0x041C:
case 0x041D:
case 0x041E:
case 0x041F:
ch -= 0x032F;
break;
case 0x0420:
case 0x0421:
case 0x0422:
case 0x0423:
ch -= 0x032E;
break;
case 0x0424: ch = 0xE6; break;
case 0x0425: ch = 0xE8; break;
case 0x0426: ch = 0xE3; break;
case 0x0427: ch = 0xFE; break;
case 0x0428: ch = 0xFB; break;
case 0x0429: ch = 0xFD; break;
case 0x042A: ch = 0xFF; break;
case 0x042B: ch = 0xF9; break;
case 0x042C: ch = 0xF8; break;
case 0x042D: ch = 0xFC; break;
case 0x042E: ch = 0xE0; break;
case 0x042F: ch = 0xF1; break;
case 0x0430: ch = 0xC1; break;
case 0x0431: ch = 0xC2; break;
case 0x0432: ch = 0xD7; break;
case 0x0433: ch = 0xC7; break;
case 0x0434: ch = 0xC4; break;
case 0x0435: ch = 0xC5; break;
case 0x0436: ch = 0xD6; break;
case 0x0437: ch = 0xDA; break;
case 0x0438:
case 0x0439:
case 0x043A:
case 0x043B:
case 0x043C:
case 0x043D:
case 0x043E:
case 0x043F:
ch -= 0x036F;
break;
case 0x0440:
case 0x0441:
case 0x0442:
case 0x0443:
ch -= 0x036E;
break;
case 0x0444: ch = 0xC6; break;
case 0x0445: ch = 0xC8; break;
case 0x0446: ch = 0xC3; break;
case 0x0447: ch = 0xDE; break;
case 0x0448: ch = 0xDB; break;
case 0x0449: ch = 0xDD; break;
case 0x044A: ch = 0xDF; break;
case 0x044B: ch = 0xD9; break;
case 0x044C: ch = 0xD8; break;
case 0x044D: ch = 0xDC; break;
case 0x044E: ch = 0xC0; break;
case 0x044F: ch = 0xD1; break;
case 0x0451: ch = 0xA3; break;
case 0x2219: ch = 0x95; break;
case 0x221A: ch = 0x96; break;
case 0x2248: ch = 0x97; break;
case 0x2264: ch = 0x98; break;
case 0x2265: ch = 0x99; break;
case 0x2320: ch = 0x93; break;
case 0x2321: ch = 0x9B; break;
case 0x2500: ch = 0x80; break;
case 0x2502: ch = 0x81; break;
case 0x250C: ch = 0x82; break;
case 0x2510: ch = 0x83; break;
case 0x2514: ch = 0x84; break;
case 0x2518: ch = 0x85; break;
case 0x251C: ch = 0x86; break;
case 0x2524: ch = 0x87; break;
case 0x252C: ch = 0x88; break;
case 0x2534: ch = 0x89; break;
case 0x253C: ch = 0x8A; break;
case 0x2550: ch = 0xA0; break;
case 0x2551: ch = 0xA1; break;
case 0x2552: ch = 0xA2; break;
case 0x2553:
case 0x2554:
case 0x2555:
case 0x2556:
case 0x2557:
case 0x2558:
case 0x2559:
case 0x255A:
case 0x255B:
case 0x255C:
case 0x255D:
case 0x255E:
case 0x255F:
case 0x2560:
case 0x2561:
ch -= 0x24AF;
break;
case 0x2562:
case 0x2563:
case 0x2564:
case 0x2565:
case 0x2566:
case 0x2567:
case 0x2568:
case 0x2569:
case 0x256A:
case 0x256B:
case 0x256C:
ch -= 0x24AE;
break;
case 0x2580: ch = 0x8B; break;
case 0x2584: ch = 0x8C; break;
case 0x2588: ch = 0x8D; break;
case 0x258C: ch = 0x8E; break;
case 0x2590:
case 0x2591:
case 0x2592:
case 0x2593:
ch -= 0x2501;
break;
case 0x25A0: ch = 0x94; break;
case 0xFFE8: ch = 0x81; break;
case 0xFFED: ch = 0x94; break;
default:
{
if(ch >= 0xFF01 && ch <= 0xFF5E)
ch -= 0xFEE0;
else
ch = 0x3F;
}
break;
}
bytes[byteIndex++] = (byte)ch;
--charCount;
}
}
protected override void ToBytes(String s, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
int ch;
while(charCount > 0)
{
ch = (int)(s[charIndex++]);
if(ch >= 128) switch(ch)
{
case 0x00A0: ch = 0x9A; break;
case 0x00A9: ch = 0xBF; break;
case 0x00B0: ch = 0x9C; break;
case 0x00B2: ch = 0x9D; break;
case 0x00B7: ch = 0x9E; break;
case 0x00F7: ch = 0x9F; break;
case 0x0401: ch = 0xB3; break;
case 0x0410: ch = 0xE1; break;
case 0x0411: ch = 0xE2; break;
case 0x0412: ch = 0xF7; break;
case 0x0413: ch = 0xE7; break;
case 0x0414: ch = 0xE4; break;
case 0x0415: ch = 0xE5; break;
case 0x0416: ch = 0xF6; break;
case 0x0417: ch = 0xFA; break;
case 0x0418:
case 0x0419:
case 0x041A:
case 0x041B:
case 0x041C:
case 0x041D:
case 0x041E:
case 0x041F:
ch -= 0x032F;
break;
case 0x0420:
case 0x0421:
case 0x0422:
case 0x0423:
ch -= 0x032E;
break;
case 0x0424: ch = 0xE6; break;
case 0x0425: ch = 0xE8; break;
case 0x0426: ch = 0xE3; break;
case 0x0427: ch = 0xFE; break;
case 0x0428: ch = 0xFB; break;
case 0x0429: ch = 0xFD; break;
case 0x042A: ch = 0xFF; break;
case 0x042B: ch = 0xF9; break;
case 0x042C: ch = 0xF8; break;
case 0x042D: ch = 0xFC; break;
case 0x042E: ch = 0xE0; break;
case 0x042F: ch = 0xF1; break;
case 0x0430: ch = 0xC1; break;
case 0x0431: ch = 0xC2; break;
case 0x0432: ch = 0xD7; break;
case 0x0433: ch = 0xC7; break;
case 0x0434: ch = 0xC4; break;
case 0x0435: ch = 0xC5; break;
case 0x0436: ch = 0xD6; break;
case 0x0437: ch = 0xDA; break;
case 0x0438:
case 0x0439:
case 0x043A:
case 0x043B:
case 0x043C:
case 0x043D:
case 0x043E:
case 0x043F:
ch -= 0x036F;
break;
case 0x0440:
case 0x0441:
case 0x0442:
case 0x0443:
ch -= 0x036E;
break;
case 0x0444: ch = 0xC6; break;
case 0x0445: ch = 0xC8; break;
case 0x0446: ch = 0xC3; break;
case 0x0447: ch = 0xDE; break;
case 0x0448: ch = 0xDB; break;
case 0x0449: ch = 0xDD; break;
case 0x044A: ch = 0xDF; break;
case 0x044B: ch = 0xD9; break;
case 0x044C: ch = 0xD8; break;
case 0x044D: ch = 0xDC; break;
case 0x044E: ch = 0xC0; break;
case 0x044F: ch = 0xD1; break;
case 0x0451: ch = 0xA3; break;
case 0x2219: ch = 0x95; break;
case 0x221A: ch = 0x96; break;
case 0x2248: ch = 0x97; break;
case 0x2264: ch = 0x98; break;
case 0x2265: ch = 0x99; break;
case 0x2320: ch = 0x93; break;
case 0x2321: ch = 0x9B; break;
case 0x2500: ch = 0x80; break;
case 0x2502: ch = 0x81; break;
case 0x250C: ch = 0x82; break;
case 0x2510: ch = 0x83; break;
case 0x2514: ch = 0x84; break;
case 0x2518: ch = 0x85; break;
case 0x251C: ch = 0x86; break;
case 0x2524: ch = 0x87; break;
case 0x252C: ch = 0x88; break;
case 0x2534: ch = 0x89; break;
case 0x253C: ch = 0x8A; break;
case 0x2550: ch = 0xA0; break;
case 0x2551: ch = 0xA1; break;
case 0x2552: ch = 0xA2; break;
case 0x2553:
case 0x2554:
case 0x2555:
case 0x2556:
case 0x2557:
case 0x2558:
case 0x2559:
case 0x255A:
case 0x255B:
case 0x255C:
case 0x255D:
case 0x255E:
case 0x255F:
case 0x2560:
case 0x2561:
ch -= 0x24AF;
break;
case 0x2562:
case 0x2563:
case 0x2564:
case 0x2565:
case 0x2566:
case 0x2567:
case 0x2568:
case 0x2569:
case 0x256A:
case 0x256B:
case 0x256C:
ch -= 0x24AE;
break;
case 0x2580: ch = 0x8B; break;
case 0x2584: ch = 0x8C; break;
case 0x2588: ch = 0x8D; break;
case 0x258C: ch = 0x8E; break;
case 0x2590:
case 0x2591:
case 0x2592:
case 0x2593:
ch -= 0x2501;
break;
case 0x25A0: ch = 0x94; break;
case 0xFFE8: ch = 0x81; break;
case 0xFFED: ch = 0x94; break;
default:
{
if(ch >= 0xFF01 && ch <= 0xFF5E)
ch -= 0xFEE0;
else
ch = 0x3F;
}
break;
}
bytes[byteIndex++] = (byte)ch;
--charCount;
}
}
}; // class CP20866
public class ENCkoi8_r : CP20866
{
public ENCkoi8_r() : base() {}
}; // class ENCkoi8_r
}; // namespace I18N.Other
| |
//-----------------------------------------------------------------------
// <copyright file="InnerListGridView.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <summary>
// Implements the InnerListGridView control.
//</summary>
//-----------------------------------------------------------------------
namespace Microsoft.Management.UI.Internal
{
using System;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Markup;
using System.Collections.ObjectModel;
/// <summary>
/// Extends the basic GrdView class to introduce the Visible concept to the
/// Columns collection.
/// </summary>
/// <!--We create our own version of Columns, that:
/// 1) Only takes InnerListColumn's
/// 2) Passes through the underlying ListView Columns, only the InnerListColumns
/// that have Visible=true.-->
[ContentProperty("AvailableColumns")]
public class InnerListGridView : GridView
{
/// <summary>
/// Set to true when we want to change the Columns collection.
/// </summary>
private bool canChangeColumns = false;
/// <summary>
/// Instantiates a new object of this class.
/// </summary>
public InnerListGridView()
: this(new ObservableCollection<InnerListColumn>())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="InnerListGridView"/> class with the specified columns.
/// </summary>
/// <param name="availableColumns">The columns this grid should display.</param>
/// <exception cref="ArgumentNullException">The specified value is a null reference.</exception>
internal InnerListGridView(ObservableCollection<InnerListColumn> availableColumns)
{
if (availableColumns == null)
{
throw new ArgumentNullException("availableColumns");
}
// Setting the AvailableColumns property won't trigger CollectionChanged, so we have to do it manually \\
this.AvailableColumns = availableColumns;
this.AvailableColumns_CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, availableColumns));
availableColumns.CollectionChanged += new NotifyCollectionChangedEventHandler(this.AvailableColumns_CollectionChanged);
this.Columns.CollectionChanged += new NotifyCollectionChangedEventHandler(this.Columns_CollectionChanged);
}
/// <summary>
/// Gets a collection of all columns which can be
/// added to the ManagementList, for example through ColumnPicker.
/// Columns is the collection of the columns which are currently
/// displayed (in the order in which they are displayed).
/// </summary>
internal ObservableCollection<InnerListColumn> AvailableColumns
{
get;
private set;
}
/// <summary>
/// Releases this instance's references to its controls.
/// This API supports the framework infrastructure and is not intended to be used directly from your code.
/// </summary>
public void ReleaseReferences()
{
this.AvailableColumns.CollectionChanged -= this.AvailableColumns_CollectionChanged;
this.Columns.CollectionChanged -= this.Columns_CollectionChanged;
foreach (InnerListColumn column in this.AvailableColumns)
{
// Unsubscribe from the column's change events \\
((INotifyPropertyChanged)column).PropertyChanged -= this.Column_PropertyChanged;
// If the column is shown, store its last width before releasing \\
if (column.Visible)
{
column.Width = column.ActualWidth;
}
}
// Remove the columns so they can be added to the next GridView \\
this.Columns.Clear();
}
/// <summary>
/// Called when the ItemsSource changes to auto populate the GridView columns
/// with reflection information on the first element of the ItemsSource.
/// </summary>
/// <param name="newValue">
/// The new ItemsSource.
/// This is used just to fetch .the first collection element.
/// </param>
internal void PopulateColumns(System.Collections.IEnumerable newValue)
{
if (newValue == null)
{
return; // No elements, so we can't populate
}
IEnumerator newValueEnumerator = newValue.GetEnumerator();
if (!newValueEnumerator.MoveNext())
{
return; // No first element, so we can't populate
}
object first = newValueEnumerator.Current;
if (first == null)
{
return;
}
Debug.Assert(this.AvailableColumns.Count == 0, "AvailableColumns should be empty at this point");
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(first);
foreach (PropertyDescriptor property in properties)
{
UIPropertyGroupDescription dataDescription = new UIPropertyGroupDescription(property.Name, property.Name, property.PropertyType);
InnerListColumn column = new InnerListColumn(dataDescription);
this.AvailableColumns.Add(column);
}
}
/// <summary>
/// Callback for displaying the Column Picker.
/// </summary>
/// <param name="sender">The send object.</param>
/// <param name="e">The Event RoutedEventArgs.</param>
internal void OnColumnPicker(object sender, RoutedEventArgs e)
{
ColumnPicker columnPicker = new ColumnPicker(
this.Columns, this.AvailableColumns);
columnPicker.Owner = Window.GetWindow((DependencyObject)sender);
bool? retval = columnPicker.ShowDialog();
if (true != retval)
{
return;
}
this.canChangeColumns = true;
try
{
this.Columns.Clear();
ObservableCollection<InnerListColumn> newColumns = columnPicker.SelectedColumns;
Debug.Assert(null != newColumns, "SelectedColumns not found");
foreach (InnerListColumn column in newColumns)
{
Debug.Assert(column.Visible);
// 185977: ML InnerListGridView.PopulateColumns(): Always set Width on new columns
// Workaround to GridView issue suggested by Ben Carter
// Issue: Once a column has been added to a GridView
// and then removed, auto-sizing does not work
// after it is added back.
// Solution: Remove the column, change the width,
// add the column back, then change the width back.
double width = column.Width;
column.Width = 0d;
this.Columns.Add(column);
column.Width = width;
}
}
finally
{
this.canChangeColumns = false;
}
}
/// <summary>
/// Called when Columns changes so we can check we are the ones changing it.
/// </summary>
/// <param name="sender">The collection changing.</param>
/// <param name="e">The event parameters.</param>
private void Columns_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
switch (e.Action)
{
// Move happens in the GUI drag and drop operation, so we have to allow it.
case NotifyCollectionChangedAction.Move:
return;
// default means all other operations (Add, Move, Replace and Reset) those are reserved.
// only we should do it, as we keep AvailableColumns in sync with columns
default:
if (!this.canChangeColumns)
{
throw new NotSupportedException(
String.Format(
CultureInfo.InvariantCulture,
InvariantResources.CannotModified,
InvariantResources.Columns,
"AvailableColumns"));
}
break;
}
}
/// <summary>
/// Called when the AvailableColumns changes to pass through the VisibleColumns to Columns.
/// </summary>
/// <param name="sender">The collection changing.</param>
/// <param name="e">The event parameters.</param>
private void AvailableColumns_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
this.AddOrRemoveNotifications(e);
this.SynchronizeColumns();
}
/// <summary>
/// Called from availableColumns_CollectionChanged to add or remove the notifications
/// used to track the Visible property.
/// </summary>
/// <param name="e">The parameter passed to availableColumns_CollectionChanged.</param>
private void AddOrRemoveNotifications(NotifyCollectionChangedEventArgs e)
{
if (e.Action != NotifyCollectionChangedAction.Move)
{
if (e.OldItems != null)
{
foreach (InnerListColumn oldColumn in e.OldItems)
{
((INotifyPropertyChanged)oldColumn).PropertyChanged -= this.Column_PropertyChanged;
}
}
if (e.NewItems != null)
{
foreach (InnerListColumn newColumn in e.NewItems)
{
((INotifyPropertyChanged)newColumn).PropertyChanged += this.Column_PropertyChanged;
}
}
}
}
/// <summary>
/// Synchronizes AvailableColumns and Columns preserving the order from Columns that
/// comes from the user moving Columns around.
/// </summary>
private void SynchronizeColumns()
{
this.canChangeColumns = true;
try
{
// Add to listViewColumns all Visible columns in availableColumns not already in listViewColumns
foreach (InnerListColumn column in this.AvailableColumns)
{
if (column.Visible && !this.Columns.Contains(column))
{
this.Columns.Add(column);
}
}
// Remove all columns which are not visible or removed from Available columns.
for (int i = this.Columns.Count - 1; i >= 0; i--)
{
InnerListColumn listViewColumn = (InnerListColumn)this.Columns[i];
if (!listViewColumn.Visible || !this.AvailableColumns.Contains(listViewColumn))
{
this.Columns.RemoveAt(i);
}
}
}
finally
{
this.canChangeColumns = false;
}
}
/// <summary>
/// Called when the Visible property of a column changes.
/// </summary>
/// <param name="sender">The column whose property changed.</param>
/// <param name="e">The event parameters.</param>
private void Column_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == InnerListColumn.VisibleProperty.Name)
{
this.SynchronizeColumns();
}
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Windows;
using System.Windows.Controls;
using Microsoft.PythonTools.Interpreter;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudioTools;
using Task = System.Threading.Tasks.Task;
namespace Microsoft.PythonTools.Intellisense {
/// <summary>
/// A wrapper around the default completion control. This control simply adds a warning which informs
/// the user if the intellisense database is not currently up-to-date. We embed the normal completion
/// control (wherever it comes from, we import it via MEF) into our control.
///
/// This control forwards calls from IIntellisenseCommandTarget and IMouseProcessor onto the inner
/// control.
/// </summary>
public partial class CompletionControl : ContentControl, IIntellisenseCommandTarget, IMouseProcessor, IDisposable {
public static readonly object HotTrackBrushKey = VsBrushes.ToolWindowTabMouseOverTextKey;
private static readonly DependencyPropertyKey WarningVisibilityPropertyKey = DependencyProperty.RegisterReadOnly("WarningVisibility", typeof(Visibility), typeof(CompletionControl), new PropertyMetadata(Visibility.Visible));
public static readonly DependencyProperty WarningVisibilityProperty = WarningVisibilityPropertyKey.DependencyProperty;
private readonly IServiceProvider _serviceProvider;
public CompletionControl(IServiceProvider serviceProvider, UIElement view, ICompletionSession session) {
_serviceProvider = serviceProvider;
InitializeComponent();
Content = view;
var fact = session.TextView.GetAnalyzerAtCaret(serviceProvider)?.InterpreterFactory as IPythonInterpreterFactoryWithDatabase;
if (fact == null) {
SetValue(WarningVisibilityPropertyKey, Visibility.Collapsed);
} else {
SetValue(WarningVisibilityPropertyKey, fact.IsCurrent ? Visibility.Collapsed : Visibility.Visible);
}
}
private void OnSizeChanged(object sender, SizeChangedEventArgs e) {
// force the inner presenter to not re-size to a smaller size. The inner presenter
// will then force the tab controls to not re-size keeping the completion list
// to a fixed size.
// http://pytools.codeplex.com/workitem/554
var content = Content as ContentControl;
if (content != null && (content.Width < ActualWidth || double.IsNaN(content.Width))) {
content.Width = content.MinWidth = ActualWidth;
}
}
private async void Button_GotFocus(object sender, RoutedEventArgs e) {
// HACK: Handling GotFocus because this is the only event we get
// when clicking on the button - the VS text editor somehow absorbs
// all the rest...
// Short delay to ensure the completion control has lost focus,
// otherwise the environment list will be hidden immediately.
await Task.Delay(50);
// Should already be on the UI thread, but we'll invoke to be safe
_serviceProvider.GetUIThread().Invoke(() => {
_serviceProvider.ShowInterpreterList();
});
}
#region IIntellisenseCommandTarget Members
public bool ExecuteKeyboardCommand(IntellisenseKeyboardCommand command) {
IIntellisenseCommandTarget target = Content as IIntellisenseCommandTarget;
if (target != null) {
return target.ExecuteKeyboardCommand(command);
}
return false;
}
#endregion
#region IMouseProcessor Members
public void PostprocessDragEnter(DragEventArgs e) {
IMouseProcessor processor = Content as IMouseProcessor;
if (processor != null) {
processor.PostprocessDragEnter(e);
}
}
public void PostprocessDragLeave(DragEventArgs e) {
IMouseProcessor processor = Content as IMouseProcessor;
if (processor != null) {
processor.PostprocessDragLeave(e);
}
}
public void PostprocessDragOver(DragEventArgs e) {
IMouseProcessor processor = Content as IMouseProcessor;
if (processor != null) {
processor.PostprocessDragOver(e);
}
}
public void PostprocessDrop(DragEventArgs e) {
IMouseProcessor processor = Content as IMouseProcessor;
if (processor != null) {
processor.PostprocessDrop(e);
}
}
public void PostprocessGiveFeedback(GiveFeedbackEventArgs e) {
IMouseProcessor processor = Content as IMouseProcessor;
if (processor != null) {
processor.PostprocessGiveFeedback(e);
}
}
public void PostprocessMouseDown(System.Windows.Input.MouseButtonEventArgs e) {
IMouseProcessor processor = Content as IMouseProcessor;
if (processor != null) {
processor.PostprocessMouseDown(e);
}
}
public void PostprocessMouseEnter(System.Windows.Input.MouseEventArgs e) {
IMouseProcessor processor = Content as IMouseProcessor;
if (processor != null) {
processor.PostprocessMouseEnter(e);
}
}
public void PostprocessMouseLeave(System.Windows.Input.MouseEventArgs e) {
IMouseProcessor processor = Content as IMouseProcessor;
if (processor != null) {
processor.PostprocessMouseLeave(e);
}
}
public void PostprocessMouseLeftButtonDown(System.Windows.Input.MouseButtonEventArgs e) {
IMouseProcessor processor = Content as IMouseProcessor;
if (processor != null) {
processor.PostprocessMouseLeftButtonDown(e);
}
}
public void PostprocessMouseLeftButtonUp(System.Windows.Input.MouseButtonEventArgs e) {
IMouseProcessor processor = Content as IMouseProcessor;
if (processor != null) {
processor.PostprocessMouseLeftButtonUp(e);
}
}
public void PostprocessMouseMove(System.Windows.Input.MouseEventArgs e) {
IMouseProcessor processor = Content as IMouseProcessor;
if (processor != null) {
processor.PostprocessMouseMove(e);
}
}
public void PostprocessMouseRightButtonDown(System.Windows.Input.MouseButtonEventArgs e) {
IMouseProcessor processor = Content as IMouseProcessor;
if (processor != null) {
processor.PostprocessMouseRightButtonDown(e);
}
}
public void PostprocessMouseRightButtonUp(System.Windows.Input.MouseButtonEventArgs e) {
IMouseProcessor processor = Content as IMouseProcessor;
if (processor != null) {
processor.PostprocessMouseRightButtonUp(e);
}
}
public void PostprocessMouseUp(System.Windows.Input.MouseButtonEventArgs e) {
IMouseProcessor processor = Content as IMouseProcessor;
if (processor != null) {
processor.PostprocessMouseUp(e);
}
}
public void PostprocessMouseWheel(System.Windows.Input.MouseWheelEventArgs e) {
IMouseProcessor processor = Content as IMouseProcessor;
if (processor != null) {
processor.PostprocessMouseWheel(e);
}
}
public void PostprocessQueryContinueDrag(QueryContinueDragEventArgs e) {
IMouseProcessor processor = Content as IMouseProcessor;
if (processor != null) {
processor.PostprocessQueryContinueDrag(e);
}
}
public void PreprocessDragEnter(DragEventArgs e) {
IMouseProcessor processor = Content as IMouseProcessor;
if (processor != null) {
processor.PreprocessDragEnter(e);
}
}
public void PreprocessDragLeave(DragEventArgs e) {
IMouseProcessor processor = Content as IMouseProcessor;
if (processor != null) {
processor.PreprocessDragLeave(e);
}
}
public void PreprocessDragOver(DragEventArgs e) {
IMouseProcessor processor = Content as IMouseProcessor;
if (processor != null) {
processor.PreprocessDragOver(e);
}
}
public void PreprocessDrop(DragEventArgs e) {
IMouseProcessor processor = Content as IMouseProcessor;
if (processor != null) {
processor.PreprocessDrop(e);
}
}
public void PreprocessGiveFeedback(GiveFeedbackEventArgs e) {
IMouseProcessor processor = Content as IMouseProcessor;
if (processor != null) {
processor.PreprocessGiveFeedback(e);
}
}
public void PreprocessMouseDown(System.Windows.Input.MouseButtonEventArgs e) {
IMouseProcessor processor = Content as IMouseProcessor;
if (processor != null) {
processor.PreprocessMouseDown(e);
}
}
public void PreprocessMouseEnter(System.Windows.Input.MouseEventArgs e) {
IMouseProcessor processor = Content as IMouseProcessor;
if (processor != null) {
processor.PreprocessMouseEnter(e);
}
}
public void PreprocessMouseLeave(System.Windows.Input.MouseEventArgs e) {
IMouseProcessor processor = Content as IMouseProcessor;
if (processor != null) {
processor.PreprocessMouseLeave(e);
}
}
public void PreprocessMouseLeftButtonDown(System.Windows.Input.MouseButtonEventArgs e) {
IMouseProcessor processor = Content as IMouseProcessor;
if (processor != null) {
processor.PreprocessMouseLeftButtonDown(e);
}
}
public void PreprocessMouseLeftButtonUp(System.Windows.Input.MouseButtonEventArgs e) {
IMouseProcessor processor = Content as IMouseProcessor;
if (processor != null) {
processor.PreprocessMouseLeftButtonUp(e);
}
}
public void PreprocessMouseMove(System.Windows.Input.MouseEventArgs e) {
IMouseProcessor processor = Content as IMouseProcessor;
if (processor != null) {
processor.PreprocessMouseMove(e);
}
}
public void PreprocessMouseRightButtonDown(System.Windows.Input.MouseButtonEventArgs e) {
IMouseProcessor processor = Content as IMouseProcessor;
if (processor != null) {
processor.PreprocessMouseRightButtonDown(e);
}
}
public void PreprocessMouseRightButtonUp(System.Windows.Input.MouseButtonEventArgs e) {
IMouseProcessor processor = Content as IMouseProcessor;
if (processor != null) {
processor.PreprocessMouseRightButtonUp(e);
}
}
public void PreprocessMouseUp(System.Windows.Input.MouseButtonEventArgs e) {
IMouseProcessor processor = Content as IMouseProcessor;
if (processor != null) {
processor.PreprocessMouseUp(e);
}
}
public void PreprocessMouseWheel(System.Windows.Input.MouseWheelEventArgs e) {
IMouseProcessor processor = Content as IMouseProcessor;
if (processor != null) {
processor.PreprocessMouseWheel(e);
}
}
public void PreprocessQueryContinueDrag(QueryContinueDragEventArgs e) {
IMouseProcessor processor = Content as IMouseProcessor;
if (processor != null) {
processor.PreprocessQueryContinueDrag(e);
}
}
#endregion
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing) {
if (disposing) {
Content = null;
}
}
}
}
| |
//
// Controls sample in C#
//
using System;
using MonoTouch.UIKit;
using MonoTouch.Foundation;
using System.Drawing;
public partial class ControlsViewController : UITableViewController {
//
// This datasource describes how the UITableView should render the
// contents. We have a number of sections determined by the
// samples in our container class, and 2 rows per section:
//
// Row 0: the actual styled button
// Row 1: the text information about the button
//
class DataSource : UITableViewDataSource {
ControlsViewController cvc;
static NSString kDisplayCell_ID = new NSString ("DisplayCellID");
static NSString kSourceCell_ID = new NSString ("SourceCellID");
public DataSource (ControlsViewController cvc)
{
this.cvc = cvc;
}
public override int NumberOfSections (UITableView tableView)
{
return cvc.samples.Length;
}
public override string TitleForHeader (UITableView tableView, int section)
{
return cvc.samples [section].Title;
}
public override int RowsInSection (UITableView tableView, int section)
{
return 2;
}
public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
{
UITableViewCell cell;
if (indexPath.Row == 0){
cell = tableView.DequeueReusableCell (kDisplayCell_ID);
if (cell == null){
cell = new UITableViewCell (UITableViewCellStyle.Default, kDisplayCell_ID);
cell.SelectionStyle = UITableViewCellSelectionStyle.None;
} else {
// The cell is being recycled, remove the old content
UIView viewToRemove = cell.ContentView.ViewWithTag (kViewTag);
if (viewToRemove != null)
viewToRemove.RemoveFromSuperview ();
}
cell.TextLabel.Text = cvc.samples [indexPath.Section].Label;
cell.ContentView.AddSubview (cvc.samples [indexPath.Section].Control);
} else {
cell = tableView.DequeueReusableCell (kSourceCell_ID);
if (cell == null){
// Construct the cell with reusability (the second argument is not null)
cell = new UITableViewCell (UITableViewCellStyle.Default, kSourceCell_ID);
cell.SelectionStyle = UITableViewCellSelectionStyle.None;
var label = cell.TextLabel;
label.Opaque = false;
label.TextAlignment = UITextAlignment.Center;
label.TextColor = UIColor.Gray;
label.Lines = 2;
label.HighlightedTextColor = UIColor.Black;
label.Font = UIFont.SystemFontOfSize (12f);
}
cell.TextLabel.Text = cvc.samples [indexPath.Section].Source;
}
return cell;
}
}
class TableDelegate : UITableViewDelegate {
public override float GetHeightForRow (UITableView tableView, NSIndexPath indexPath)
{
// First row is always 50 pixes, second row 38
return indexPath.Row == 0 ? 50f : 38f;
}
}
// Load our definition from the NIB file
public ControlsViewController () : base ("ControlsViewController", null)
{
}
// For tagging our embedded controls at cell recylce time.
const int kViewTag = 1;
UIControl SwitchControl ()
{
var sw = new UISwitch (new RectangleF (198f, 12f, 94f, 27f)){
BackgroundColor = UIColor.Clear,
Tag = kViewTag
};
sw.ValueChanged += delegate {
// The enum variant causes a full-aot crash
Console.WriteLine ("New state: {0}", (int) sw.State);
};
return sw;
}
UIControl SliderControl ()
{
var slider = new UISlider (new RectangleF (174f, 12f, 120f, 7f)){
BackgroundColor = UIColor.Clear,
MinValue = 0f,
MaxValue = 100f,
Continuous = true,
Value = 50f,
Tag = kViewTag
};
slider.ValueChanged += delegate {
Console.WriteLine ("New value {0}", slider.Value);
};
return slider;
}
UIControl CustomSliderControl ()
{
var cslider = new UISlider (new RectangleF (174f, 12f, 120f, 7f)){
BackgroundColor = UIColor.Clear,
MinValue = 0f,
MaxValue = 100f,
Continuous = true,
Value = 50f,
Tag = kViewTag
};
var left = UIImage.FromFile ("orangeslide.png");
left = left.StretchableImage (10, 0);
var right = UIImage.FromFile ("yellowslide.png");
right = right.StretchableImage (10, 0);
cslider.SetThumbImage (UIImage.FromFile ("slider_ball.png"), UIControlState.Normal);
cslider.SetMinTrackImage (left, UIControlState.Normal);
cslider.SetMaxTrackImage (right, UIControlState.Normal);
cslider.ValueChanged += delegate {
Console.WriteLine ("New value {0}", cslider.Value);
};
return cslider;
}
UIControl PageControl ()
{
var page = new UIPageControl (new RectangleF (120f, 14f, 178f, 20f)){
BackgroundColor = UIColor.Gray,
Pages = 10,
Tag = kViewTag
};
page.TouchUpInside += delegate {
Console.WriteLine ("Current page: {0}", page.CurrentPage);
};
return page;
}
UIView ProgressIndicator ()
{
var pind = new UIActivityIndicatorView (new RectangleF (265f, 12f, 40f, 40f)){
ActivityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray,
AutoresizingMask = UIViewAutoresizing.FlexibleLeftMargin |
UIViewAutoresizing.FlexibleRightMargin |
UIViewAutoresizing.FlexibleTopMargin |
UIViewAutoresizing.FlexibleBottomMargin,
Tag = kViewTag
};
pind.StartAnimating ();
pind.SizeToFit ();
return pind;
}
UIView ProgressBar ()
{
return new UIProgressView (new RectangleF (126f, 20f, 160f, 24f)){
Style = UIProgressViewStyle.Default,
Progress = 0.5f,
Tag = kViewTag
};
}
struct ControlSample {
public string Title, Label, Source;
public UIView Control;
public ControlSample (string t, string l, string s, UIView c)
{
Title = t;
Label = l;
Source = s;
Control = c;
}
}
ControlSample [] samples;
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
Title = "Controls";
samples = new ControlSample [] {
new ControlSample ("UISwitch", "Standard Switch", "controls.cs: SwitchControl ()", SwitchControl ()),
new ControlSample ("UISlider", "Standard Slider", "controls.cs: SliderControl ()", SliderControl ()),
new ControlSample ("UISlider", "Customized Slider", "controls.cs: CustomSliderControl ()", CustomSliderControl ()),
new ControlSample ("UIPageControl", "Ten Pages", "controls.cs: PageControl ()", PageControl ()),
new ControlSample ("UIActivityIndicatorView", "Style Gray", "controls.cs: ProgressIndicator ()", ProgressIndicator ()),
new ControlSample ("UIProgressView", "Style Default", "controls.cs: ProgressBar ()", ProgressBar ()),
};
TableView.DataSource = new DataSource (this);
TableView.Delegate = new TableDelegate ();
}
}
| |
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>
/// The place where a person lives.
/// </summary>
public class Residence_Core : TypeCore, IPlace
{
public Residence_Core()
{
this._TypeId = 227;
this._Id = "Residence";
this._Schema_Org_Url = "http://schema.org/Residence";
string label = "";
GetLabel(out label, "Residence", typeof(Residence_Core));
this._Label = label;
this._Ancestors = new int[]{266,206};
this._SubTypes = new int[]{17,111,241};
this._SuperTypes = new int[]{206};
this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196};
}
/// <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 basic containment relation between places.
/// </summary>
private ContainedIn_Core containedIn;
public ContainedIn_Core ContainedIn
{
get
{
return containedIn;
}
set
{
containedIn = value;
SetPropertyInstance(containedIn);
}
}
/// <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>
/// 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>
/// 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>
/// 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>
/// The name of the item.
/// </summary>
private Name_Core name;
public Name_Core Name
{
get
{
return name;
}
set
{
name = value;
SetPropertyInstance(name);
}
}
/// <summary>
/// Photographs of this place.
/// </summary>
private Photos_Core photos;
public Photos_Core Photos
{
get
{
return photos;
}
set
{
photos = value;
SetPropertyInstance(photos);
}
}
/// <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);
}
}
}
}
| |
// 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.Net.Security;
using System.Net.Sockets;
using System.Net.Test.Common;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Http.Functional.Tests
{
public class HttpClientHandler_SslProtocols_Test
{
[Fact]
public void DefaultProtocols_MatchesExpected()
{
using (var handler = new HttpClientHandler())
{
Assert.Equal(SslProtocols.None, handler.SslProtocols);
}
}
[Theory]
[InlineData(SslProtocols.None)]
[InlineData(SslProtocols.Tls)]
[InlineData(SslProtocols.Tls11)]
[InlineData(SslProtocols.Tls12)]
[InlineData(SslProtocols.Tls | SslProtocols.Tls11)]
[InlineData(SslProtocols.Tls11 | SslProtocols.Tls12)]
[InlineData(SslProtocols.Tls | SslProtocols.Tls12)]
[InlineData(SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12)]
public void SetGetProtocols_Roundtrips(SslProtocols protocols)
{
using (var handler = new HttpClientHandler())
{
handler.SslProtocols = protocols;
Assert.Equal(protocols, handler.SslProtocols);
}
}
[ConditionalFact(nameof(BackendSupportsSslConfiguration))]
public async Task SetProtocols_AfterRequest_ThrowsException()
{
using (var handler = new HttpClientHandler() { ServerCertificateCustomValidationCallback = LoopbackServer.AllowAllCertificates })
using (var client = new HttpClient(handler))
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
await TestHelper.WhenAllCompletedOrAnyFailed(
LoopbackServer.ReadRequestAndSendResponseAsync(server),
client.GetAsync(url));
});
Assert.Throws<InvalidOperationException>(() => handler.SslProtocols = SslProtocols.Tls12);
}
}
[Theory]
[InlineData(~SslProtocols.None)]
#pragma warning disable 0618 // obsolete warning
[InlineData(SslProtocols.Ssl2)]
[InlineData(SslProtocols.Ssl3)]
[InlineData(SslProtocols.Ssl2 | SslProtocols.Ssl3)]
[InlineData(SslProtocols.Ssl2 | SslProtocols.Ssl3 | SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12)]
#pragma warning restore 0618
public void DisabledProtocols_SetSslProtocols_ThrowsException(SslProtocols disabledProtocols)
{
using (var handler = new HttpClientHandler())
{
Assert.Throws<NotSupportedException>(() => handler.SslProtocols = disabledProtocols);
}
}
[ConditionalTheory(nameof(BackendSupportsSslConfiguration))]
[InlineData(SslProtocols.Tls, false)]
[InlineData(SslProtocols.Tls, true)]
[InlineData(SslProtocols.Tls11, false)]
[InlineData(SslProtocols.Tls11, true)]
[InlineData(SslProtocols.Tls12, false)]
[InlineData(SslProtocols.Tls12, true)]
public async Task GetAsync_AllowedSSLVersion_Succeeds(SslProtocols acceptedProtocol, bool requestOnlyThisProtocol)
{
using (var handler = new HttpClientHandler() { ServerCertificateCustomValidationCallback = LoopbackServer.AllowAllCertificates })
using (var client = new HttpClient(handler))
{
if (requestOnlyThisProtocol)
{
handler.SslProtocols = acceptedProtocol;
}
var options = new LoopbackServer.Options { UseSsl = true, SslProtocols = acceptedProtocol };
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
await TestHelper.WhenAllCompletedOrAnyFailed(
LoopbackServer.ReadRequestAndSendResponseAsync(server, options: options),
client.GetAsync(url));
}, options);
}
}
public readonly static object [][] SupportedSSLVersionServers =
{
new object[] {"TLSv1.0", Configuration.Http.TLSv10RemoteServer},
new object[] {"TLSv1.1", Configuration.Http.TLSv11RemoteServer},
new object[] {"TLSv1.2", Configuration.Http.TLSv12RemoteServer},
};
// This test is logically the same as the above test, albeit using remote servers
// instead of local ones. We're keeping it for now (as outerloop) because it helps
// to validate against another SSL implementation that what we mean by a particular
// TLS version matches that other implementation.
[OuterLoop] // avoid www.ssllabs.com dependency in innerloop
[Theory]
[MemberData(nameof(SupportedSSLVersionServers))]
public async Task GetAsync_SupportedSSLVersion_Succeeds(string name, string url)
{
using (var client = new HttpClient())
{
(await client.GetAsync(url)).Dispose();
}
}
public readonly static object[][] NotSupportedSSLVersionServers =
{
new object[] {"SSLv2", Configuration.Http.SSLv2RemoteServer},
new object[] {"SSLv3", Configuration.Http.SSLv3RemoteServer},
};
// It would be easy to remove the dependency on these remote servers if we didn't
// explicitly disallow creating SslStream with SSLv2/3. Since we explicitly throw
// when trying to use such an SslStream, we can't stand up a localhost server that
// only speaks those protocols.
[OuterLoop] // avoid www.ssllabs.com dependency in innerloop
[Theory]
[MemberData(nameof(NotSupportedSSLVersionServers))]
public async Task GetAsync_UnsupportedSSLVersion_Throws(string name, string url)
{
using (var client = new HttpClient())
{
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(url));
}
}
[ConditionalFact(nameof(BackendSupportsSslConfiguration), nameof(SslDefaultsToTls12))]
public async Task GetAsync_NoSpecifiedProtocol_DefaultsToTls12()
{
using (var handler = new HttpClientHandler() { ServerCertificateCustomValidationCallback = LoopbackServer.AllowAllCertificates })
using (var client = new HttpClient(handler))
{
var options = new LoopbackServer.Options { UseSsl = true };
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
await TestHelper.WhenAllCompletedOrAnyFailed(
client.GetAsync(url),
LoopbackServer.AcceptSocketAsync(server, async (s, stream, reader, writer) =>
{
Assert.Equal(SslProtocols.Tls12, Assert.IsType<SslStream>(stream).SslProtocol);
await LoopbackServer.ReadWriteAcceptedAsync(s, reader, writer);
}, options));
}, options);
}
}
[ConditionalTheory(nameof(BackendSupportsSslConfiguration))]
[InlineData(SslProtocols.Tls11, SslProtocols.Tls, typeof(IOException))]
[InlineData(SslProtocols.Tls12, SslProtocols.Tls11, typeof(IOException))]
[InlineData(SslProtocols.Tls, SslProtocols.Tls12, typeof(AuthenticationException))]
public async Task GetAsync_AllowedSSLVersionDiffersFromServer_ThrowsException(
SslProtocols allowedProtocol, SslProtocols acceptedProtocol, Type exceptedServerException)
{
using (var handler = new HttpClientHandler() { SslProtocols = allowedProtocol, ServerCertificateCustomValidationCallback = LoopbackServer.AllowAllCertificates })
using (var client = new HttpClient(handler))
{
var options = new LoopbackServer.Options { UseSsl = true, SslProtocols = acceptedProtocol };
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
await TestHelper.WhenAllCompletedOrAnyFailed(
Assert.ThrowsAsync(exceptedServerException, () => LoopbackServer.ReadRequestAndSendResponseAsync(server, options: options)),
Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(url)));
}, options);
}
}
[ActiveIssue(8538, PlatformID.Windows)]
[Fact]
public async Task GetAsync_DisallowTls10_AllowTls11_AllowTls12()
{
using (var handler = new HttpClientHandler() { SslProtocols = SslProtocols.Tls11 | SslProtocols.Tls12, ServerCertificateCustomValidationCallback = LoopbackServer.AllowAllCertificates })
using (var client = new HttpClient(handler))
{
if (BackendSupportsSslConfiguration)
{
LoopbackServer.Options options = new LoopbackServer.Options { UseSsl = true };
options.SslProtocols = SslProtocols.Tls;
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
await TestHelper.WhenAllCompletedOrAnyFailed(
Assert.ThrowsAsync<IOException>(() => LoopbackServer.ReadRequestAndSendResponseAsync(server, options: options)),
Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(url)));
}, options);
foreach (var prot in new[] { SslProtocols.Tls11, SslProtocols.Tls12 })
{
options.SslProtocols = prot;
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
await TestHelper.WhenAllCompletedOrAnyFailed(
LoopbackServer.ReadRequestAndSendResponseAsync(server, options: options),
client.GetAsync(url));
}, options);
}
}
else
{
await Assert.ThrowsAnyAsync<NotSupportedException>(() => client.GetAsync($"http://{Guid.NewGuid().ToString()}/"));
}
}
}
private static bool SslDefaultsToTls12 => !PlatformDetection.IsWindows7;
// TLS 1.2 may not be enabled on Win7
// https://technet.microsoft.com/en-us/library/dn786418.aspx#BKMK_SchannelTR_TLS12
private static bool BackendSupportsSslConfiguration =>
RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ||
(CurlSslVersionDescription()?.StartsWith("OpenSSL") ?? false);
[DllImport("System.Net.Http.Native", EntryPoint = "HttpNative_GetSslVersionDescription")]
private static extern string CurlSslVersionDescription();
}
}
| |
using System;
using System.Windows.Forms;
using System.Drawing;
using System.ComponentModel;
using System.Collections;
namespace fyiReporting.RdlDesign
{
internal partial class FindTab : System.Windows.Forms.Form
{
#region Windows Form Designer generated code
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox txtFind;
private System.Windows.Forms.RadioButton radioUp;
private System.Windows.Forms.RadioButton radioDown;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.CheckBox chkCase;
public System.Windows.Forms.TabPage tabGoTo;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.TextBox txtLine;
private System.Windows.Forms.Button btnNext;
private RdlEditPreview rdlEdit;
private System.Windows.Forms.Button btnGoto;
private System.Windows.Forms.Button btnCancel;
public System.Windows.Forms.TabPage tabReplace;
private System.Windows.Forms.Button btnFindNext;
private System.Windows.Forms.CheckBox chkMatchCase;
private System.Windows.Forms.Button btnReplaceAll;
private System.Windows.Forms.Button btnReplace;
private System.Windows.Forms.TextBox txtFindR;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox txtReplace;
private System.Windows.Forms.Button bCloseReplace;
private System.Windows.Forms.Button bCloseGoto;
public System.Windows.Forms.TabControl tcFRG;
private System.ComponentModel.Container components = null;
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FindTab));
this.tcFRG = new System.Windows.Forms.TabControl();
this.tabFind = new System.Windows.Forms.TabPage();
this.btnCancel = new System.Windows.Forms.Button();
this.btnNext = new System.Windows.Forms.Button();
this.chkCase = new System.Windows.Forms.CheckBox();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.radioUp = new System.Windows.Forms.RadioButton();
this.radioDown = new System.Windows.Forms.RadioButton();
this.label1 = new System.Windows.Forms.Label();
this.txtFind = new System.Windows.Forms.TextBox();
this.tabReplace = new System.Windows.Forms.TabPage();
this.bCloseReplace = new System.Windows.Forms.Button();
this.btnFindNext = new System.Windows.Forms.Button();
this.chkMatchCase = new System.Windows.Forms.CheckBox();
this.btnReplaceAll = new System.Windows.Forms.Button();
this.btnReplace = new System.Windows.Forms.Button();
this.txtFindR = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.txtReplace = new System.Windows.Forms.TextBox();
this.tabGoTo = new System.Windows.Forms.TabPage();
this.bCloseGoto = new System.Windows.Forms.Button();
this.txtLine = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.btnGoto = new System.Windows.Forms.Button();
this.tcFRG.SuspendLayout();
this.tabFind.SuspendLayout();
this.groupBox1.SuspendLayout();
this.tabReplace.SuspendLayout();
this.tabGoTo.SuspendLayout();
this.SuspendLayout();
//
// tcFRG
//
this.tcFRG.Controls.Add(this.tabFind);
this.tcFRG.Controls.Add(this.tabReplace);
this.tcFRG.Controls.Add(this.tabGoTo);
resources.ApplyResources(this.tcFRG, "tcFRG");
this.tcFRG.Name = "tcFRG";
this.tcFRG.SelectedIndex = 0;
this.tcFRG.SelectedIndexChanged += new System.EventHandler(this.tcFRG_SelectedIndexChanged);
this.tcFRG.Enter += new System.EventHandler(this.tcFRG_Enter);
//
// tabFind
//
this.tabFind.Controls.Add(this.btnCancel);
this.tabFind.Controls.Add(this.btnNext);
this.tabFind.Controls.Add(this.chkCase);
this.tabFind.Controls.Add(this.groupBox1);
this.tabFind.Controls.Add(this.label1);
this.tabFind.Controls.Add(this.txtFind);
resources.ApplyResources(this.tabFind, "tabFind");
this.tabFind.Name = "tabFind";
this.tabFind.Tag = "find";
//
// btnCancel
//
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
resources.ApplyResources(this.btnCancel, "btnCancel");
this.btnCancel.Name = "btnCancel";
this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
//
// btnNext
//
resources.ApplyResources(this.btnNext, "btnNext");
this.btnNext.Name = "btnNext";
this.btnNext.Click += new System.EventHandler(this.btnNext_Click);
//
// chkCase
//
resources.ApplyResources(this.chkCase, "chkCase");
this.chkCase.Name = "chkCase";
//
// groupBox1
//
this.groupBox1.Controls.Add(this.radioUp);
this.groupBox1.Controls.Add(this.radioDown);
resources.ApplyResources(this.groupBox1, "groupBox1");
this.groupBox1.Name = "groupBox1";
this.groupBox1.TabStop = false;
//
// radioUp
//
resources.ApplyResources(this.radioUp, "radioUp");
this.radioUp.Name = "radioUp";
//
// radioDown
//
this.radioDown.Checked = true;
resources.ApplyResources(this.radioDown, "radioDown");
this.radioDown.Name = "radioDown";
this.radioDown.TabStop = true;
//
// label1
//
resources.ApplyResources(this.label1, "label1");
this.label1.Name = "label1";
//
// txtFind
//
resources.ApplyResources(this.txtFind, "txtFind");
this.txtFind.Name = "txtFind";
this.txtFind.TextChanged += new System.EventHandler(this.txtFind_TextChanged);
//
// tabReplace
//
this.tabReplace.Controls.Add(this.bCloseReplace);
this.tabReplace.Controls.Add(this.btnFindNext);
this.tabReplace.Controls.Add(this.chkMatchCase);
this.tabReplace.Controls.Add(this.btnReplaceAll);
this.tabReplace.Controls.Add(this.btnReplace);
this.tabReplace.Controls.Add(this.txtFindR);
this.tabReplace.Controls.Add(this.label3);
this.tabReplace.Controls.Add(this.label2);
this.tabReplace.Controls.Add(this.txtReplace);
resources.ApplyResources(this.tabReplace, "tabReplace");
this.tabReplace.Name = "tabReplace";
this.tabReplace.Tag = "replace";
//
// bCloseReplace
//
resources.ApplyResources(this.bCloseReplace, "bCloseReplace");
this.bCloseReplace.Name = "bCloseReplace";
this.bCloseReplace.Click += new System.EventHandler(this.btnCancel_Click);
//
// btnFindNext
//
resources.ApplyResources(this.btnFindNext, "btnFindNext");
this.btnFindNext.Name = "btnFindNext";
this.btnFindNext.Click += new System.EventHandler(this.btnFindNext_Click);
//
// chkMatchCase
//
resources.ApplyResources(this.chkMatchCase, "chkMatchCase");
this.chkMatchCase.Name = "chkMatchCase";
//
// btnReplaceAll
//
resources.ApplyResources(this.btnReplaceAll, "btnReplaceAll");
this.btnReplaceAll.Name = "btnReplaceAll";
this.btnReplaceAll.Click += new System.EventHandler(this.btnReplaceAll_Click);
//
// btnReplace
//
resources.ApplyResources(this.btnReplace, "btnReplace");
this.btnReplace.Name = "btnReplace";
this.btnReplace.Click += new System.EventHandler(this.btnReplace_Click);
//
// txtFindR
//
resources.ApplyResources(this.txtFindR, "txtFindR");
this.txtFindR.Name = "txtFindR";
this.txtFindR.TextChanged += new System.EventHandler(this.txtFindR_TextChanged);
//
// label3
//
resources.ApplyResources(this.label3, "label3");
this.label3.Name = "label3";
//
// label2
//
resources.ApplyResources(this.label2, "label2");
this.label2.Name = "label2";
//
// txtReplace
//
resources.ApplyResources(this.txtReplace, "txtReplace");
this.txtReplace.Name = "txtReplace";
//
// tabGoTo
//
this.tabGoTo.Controls.Add(this.bCloseGoto);
this.tabGoTo.Controls.Add(this.txtLine);
this.tabGoTo.Controls.Add(this.label4);
this.tabGoTo.Controls.Add(this.btnGoto);
resources.ApplyResources(this.tabGoTo, "tabGoTo");
this.tabGoTo.Name = "tabGoTo";
this.tabGoTo.Tag = "goto";
//
// bCloseGoto
//
resources.ApplyResources(this.bCloseGoto, "bCloseGoto");
this.bCloseGoto.Name = "bCloseGoto";
this.bCloseGoto.Click += new System.EventHandler(this.btnCancel_Click);
//
// txtLine
//
resources.ApplyResources(this.txtLine, "txtLine");
this.txtLine.Name = "txtLine";
//
// label4
//
resources.ApplyResources(this.label4, "label4");
this.label4.Name = "label4";
//
// btnGoto
//
resources.ApplyResources(this.btnGoto, "btnGoto");
this.btnGoto.Name = "btnGoto";
this.btnGoto.Click += new System.EventHandler(this.btnGoto_Click);
//
// FindTab
//
resources.ApplyResources(this, "$this");
this.CancelButton = this.btnCancel;
this.Controls.Add(this.tcFRG);
this.Name = "FindTab";
this.TopMost = true;
this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.FindTab_FormClosed);
this.tcFRG.ResumeLayout(false);
this.tabFind.ResumeLayout(false);
this.tabFind.PerformLayout();
this.groupBox1.ResumeLayout(false);
this.tabReplace.ResumeLayout(false);
this.tabReplace.PerformLayout();
this.tabGoTo.ResumeLayout(false);
this.tabGoTo.PerformLayout();
this.ResumeLayout(false);
}
#endregion
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
public TabPage tabFind;
}
}
| |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Text;
namespace LearningRegistryCache2.App_Code.DataManagers
{
public class BaseDataManager
{
private string _connString;
protected string ConnString
{
get { return this._connString; }
set { this._connString = value; }
}
public static string DEFAULT_GUID = "00000000-0000-0000-0000-000000000000";
public BaseDataManager()
{
ConnString = ConfigurationManager.ConnectionStrings["dbConString"].ConnectionString;
}
public bool DoesDataSetHaveRows(DataSet ds)
{
if (ds != null && ds.Tables.Count != 0 && ds.Tables[0].Rows.Count != 0)
{
return true;
}
else
{
return false;
}
}
public string GetRowColumn(DataRow dr, string fieldName, string defaultValue)
{
string colValue = defaultValue;
try
{
colValue = dr[fieldName].ToString();
}
catch (Exception ex)
{
colValue = defaultValue;
}
return colValue;
}
public int GetRowColumn(DataRow dr, string fieldName, int defaultValue)
{
int colValue = defaultValue;
try
{
colValue = int.Parse(GetRowColumn(dr, fieldName, ""));
}
catch (Exception ex)
{
colValue = defaultValue;
}
return colValue;
}
public decimal GetRowColumn(DataRow dr, string fieldName, decimal defaultValue)
{
decimal colValue = defaultValue;
try
{
colValue = decimal.Parse(GetRowColumn(dr, fieldName, ""));
}
catch (Exception ex)
{
colValue = defaultValue;
}
return colValue;
}
public bool GetRowColumn(DataRow dr, string fieldName, bool defaultValue)
{
bool colValue = defaultValue;
try
{
colValue = bool.Parse(GetRowColumn(dr, fieldName, ""));
}
catch (Exception ex)
{
colValue = defaultValue;
}
return colValue;
}
public DateTime GetRowColumn(DataRow dr, string fieldName, DateTime defaultValue)
{
DateTime colValue = defaultValue;
try
{
colValue = DateTime.Parse(GetRowColumn(dr, fieldName, ""));
}
catch (Exception ex)
{
colValue = defaultValue;
}
return colValue;
}
public static DateTime ConvertLRTimeToDateTime(string timeToConvert)
{
timeToConvert = timeToConvert.Replace("T", " ");
timeToConvert = timeToConvert.Replace("Z", "");
return DateTime.Parse(timeToConvert);
}
#region Logging - keep in sync with methods in UtilityManager until cleaned up or replaced
/// <summary>
/// Format an exception and message, and then log it
/// </summary>
/// <param name="ex">Exception</param>
/// <param name="message">Additional message regarding the exception</param>
public static void LogError( Exception ex, string message )
{
string user = "";
string sessionId = "unknown";
string remoteIP = "unknown";
string path = "unknown";
string queryString = "unknown";
string mcmsUrl = "unknown";
string parmsString = "";
try
{
} catch
{
//eat any additional exception
}
try
{
string errMsg = message +
"\r\nType: " + ex.GetType().ToString() +
"\r\nException: " + ex.Message.ToString() +
"\r\nStack Trace: " + ex.StackTrace.ToString() +
"\r\nServer\\Template: " + path ;
if ( parmsString.Length > 0 )
errMsg += "\r\nParameters: " + parmsString;
LogError( errMsg );
} catch
{
//eat any additional exception
}
} //
/// <summary>
/// Write the message to the log file.
/// </summary>
/// <remarks>
/// The message will be appended to the log file only if the flag "logErrors" (AppSetting) equals yes.
/// The log file is configured in the web.config, appSetting: "error.log.path"
/// </remarks>
/// <param name="message">Message to be logged.</param>
public static void LogError( string message )
{
if ( GetAppKeyValue( "notifyOnException", "no" ).ToLower() == "yes" )
{
LogError( message, true );
} else
{
LogError( message, false );
}
} //
/// <summary>
/// Write the message to the log file.
/// </summary>
/// <remarks>
/// The message will be appended to the log file only if the flag "logErrors" (AppSetting) equals yes.
/// The log file is configured in the web.config, appSetting: "error.log.path"
/// </remarks>
/// <param name="message">Message to be logged.</param>
/// <param name="notifyAdmin"></param>
public static void LogError( string message, bool notifyAdmin )
{
if ( GetAppKeyValue( "logErrors" ).ToString().Equals( "yes" ) )
{
try
{
//string logFile = GetAppKeyValue("error.log.path","C:\\VOS_LOGS.txt");
string datePrefix = System.DateTime.Today.ToString( "u" ).Substring( 0, 10 );
string logFile = GetAppKeyValue( "path.error.log", "C:\\VOS_LOGS.txt" );
string outputFile = logFile.Replace( "[date]", datePrefix );
StreamWriter file = File.AppendText( outputFile );
file.WriteLine( DateTime.Now + ": " + message );
file.WriteLine( "---------------------------------------------------------------------" );
file.Close();
if ( notifyAdmin )
{
if ( GetAppKeyValue( "notifyOnException", "no" ).ToLower() == "yes" )
{
//NotifyAdmin( "workNet Exception encountered", message );
}
}
} catch
{
//eat any additional exception
}
}
} //
#endregion
#region === Application Keys Methods ===
/// <summary>
/// Gets the value of an application key from web.config. Returns blanks if not found
/// </summary>
/// <remarks>This property is explicitly thread safe.</remarks>
public static string GetAppKeyValue( string keyName )
{
return GetAppKeyValue( keyName, "" );
} //
/// <summary>
/// Gets the value of an application key from web.config. Returns the default value if not found
/// </summary>
/// <remarks>This property is explicitly thread safe.</remarks>
public static string GetAppKeyValue( string keyName, string defaultValue )
{
string appValue = "";
try
{
appValue = System.Configuration.ConfigurationManager.AppSettings[ keyName ];
if ( appValue == null )
appValue = defaultValue;
} catch
{
appValue = defaultValue;
}
return appValue;
} //
public static int GetAppKeyValue( string keyName, int defaultValue )
{
int appValue = -1;
try
{
appValue = Int32.Parse( System.Configuration.ConfigurationManager.AppSettings[ keyName ] );
// If we get here, then number is an integer, otherwise we will use the default
} catch
{
appValue = defaultValue;
}
return appValue;
} //
#endregion
}
}
| |
using System;
using System.CodeDom;
using System.Linq;
namespace InRuleLabs.AuthoringExtensions.GenerateSDKCode.Features.Rendering
{
public class CodeMethodVariableReferenceEx
{
public CodeMemberMethodEx Method;
public CodeExpression Variable;
public CodeTypeDeclarationEx OuterClass { get { return this.Method.OuterClass; } }
public string VariableName;
public CodeMethodVariableReferenceEx(CodeMemberMethodEx method, CodeExpression variable)
{
Method = method;
Variable = variable;
}
public CodeMethodVariableReferenceEx(CodeMemberMethodEx method, CodeVariableReferenceExpression variable) : this(method, (CodeExpression)variable)
{
VariableName = variable.VariableName;
}
public void SetProperty(string name, CodeExpression value)
{
Method.AddSetProperty(Variable, name, value);
}
//public void SetProperty(string name, string value)
//{
// Method.AddSetProperty(Variable, name, value.ToCodeExpression(this.OuterClass));
//}
//public void SetProperty(string name, Guid value)
//{
// Method.AddSetProperty(Variable, name, value.ToCodeExpression(this.OuterClass));
//}
//public void SetProperty(string name, ValueType value)
//{
// Method.AddSetProperty(Variable, name, value.ToCodeExpression(this.OuterClass));
//}
//public void SetNameProperty(string value)
//{
// SetProperty("Name", value);
//}
public CodeMethodVariableReferenceEx GetPropertyReference(string entities)
{
return new CodeMethodVariableReferenceEx(this.Method, new CodePropertyReferenceExpression(Variable, entities));
}
public void AddInvokeMethodStatement(string methodName, params CodeExpression[] parms)
{
var invokeMethod = new CodeMethodInvokeExpression(this.Variable, methodName, parms);
Method.Statements.Add(invokeMethod);
}
public void AddAsReturnStatement()
{
Method.AddReturnStatment(Variable);
}
public void AddLiteralStatement(string literal)
{
Method.Statements.Add(new CodeSnippetStatement() { Value = literal });
}
public CodeMethodVariableReferenceEx DeclareVariable(string variableName, Type type, CodeExpression value)
{
var ret = this.Method.AddMethodVariable(variableName, type, value);
return new CodeMethodVariableReferenceEx(this.Method, ret);
}
public CodeMethodVariableReferenceEx GetIndexer(params CodeExpression[] indicies)
{
var ret = new CodeIndexerExpression(this.Variable, indicies);
return new CodeMethodVariableReferenceEx(this.Method, ret);
}
public CodeMethodVariableReferenceEx GetIndexer(params CodeMethodVariableReferenceEx[] indicies)
{
var ret = new CodeIndexerExpression(this.Variable, indicies.Select(i => i.Variable).ToArray());
return new CodeMethodVariableReferenceEx(this.Method, ret);
}
//public void SetIndexerValue(string key, string value)
//{
// var ret = new CodeIndexerExpression(this.Variable, key.ToCodeExpression(this.OuterClass));
// var setProp = new CodeAssignStatement(ret, value.ToCodeExpression(this.OuterClass));
// this.Method.Statements.Add(setProp);
//}
public void SetIndexerValue(CodeExpression key, CodeExpression value)
{
var ret = new CodeIndexerExpression(this.Variable, key);
var setProp = new CodeAssignStatement(ret, value);
this.Method.Statements.Add(setProp);
}
//public void AddSetValueIfNotEqualTo(CodeTypeDeclarationEx outerClass, object sourceDef, PropertyInfo propInfo, string value)
//{
// var propertyValue = (String)propInfo.GetValue(sourceDef);
// if (propertyValue != value)
// {
// AddSetValueFromProperty(outerClass, sourceDef, propInfo);
// }
//}
//public void AddSetValueIfSpecified(CodeTypeDeclarationEx outerClass, object sourceDef, PropertyInfo propInfo)
//{
// var target = this;
// var specifiedName = propInfo.Name + "Specified";
// var specifiedProperty = sourceDef.GetType().GetProperty(specifiedName);
// if (specifiedProperty == null || (bool)specifiedProperty.GetValue(sourceDef))
// {
// AddSetValueFromProperty(outerClass, sourceDef, propInfo);
// }
//}
////public void AddSetValueIfSpecified(CodeTypeDeclarationEx outerClass, object sourceDef, FieldInfo propInfo)
//{
// var target = this;
// var specifiedName = propInfo.Name + "Specified";
// var specifiedProperty = sourceDef.GetType().GetProperty(specifiedName);
// if (specifiedProperty == null || (bool)specifiedProperty.GetValue(sourceDef))
// {
// AddSetValueFromProperty(outerClass, sourceDef, propInfo);
// }
//}
//public void AddSetValueFromProperty(CodeTypeDeclarationEx outerClass, object sourceDef, PropertyInfo propInfo)
//{
// try
// {
// AddSetValueFromProperty_Internal(outerClass, propInfo.Name, propInfo.PropertyType, new Func<object>(() => propInfo.GetValue(sourceDef)));
// }
// catch (Exception ex)
// {
// var propValue = ex.Message;
// this.AddLiteralStatement(String.Format("{0}.UNHANDLED1(\"{1}\", {2});",
// this.VariableName,
// propInfo.Name, propValue));
// }
//}
//public void AddSetValueFromProperty(CodeTypeDeclarationEx outerClass, object sourceDef, FieldInfo propInfo)
//{
// try
// {
// AddSetValueFromProperty_Internal(outerClass, propInfo.Name, propInfo.FieldType, new Func<object>(() => propInfo.GetValue(sourceDef)));
// }
// catch (Exception ex)
// {
// var propValue = ex.Message;
// this.AddLiteralStatement(String.Format("{0}.UNHANDLED2(\"{1}\", {2});",
// this.VariableName,
// propInfo.Name, propValue));
// }
//}
//private void AddSetValueFromProperty_Internal(CodeTypeDeclarationEx outerClass, string propertyName, Type propertyType, Func<object> getValue)
//{
// var target = this;
// if (propertyType == typeof(object) || propertyType.IsAbstract)
// {
// //When object try and get the actual value to get the type and call recursivly
// var value = getValue();
// if (value == null)
// {
// return;
// }
// AddSetValueFromProperty_Internal(outerClass, propertyName, value.GetType(), new Func<object>(() => value));
// return;
// }
// if (propertyType == typeof(int))
// {
// target.SetProperty(propertyName, (int)getValue());
// }
// else if (propertyType == typeof(string))
// {
// target.SetProperty(propertyName, (string)getValue());
// }
// else if (propertyType == typeof(bool))
// {
// target.SetProperty(propertyName, (bool)getValue());
// }
// else if (propertyType == typeof(DateTime))
// {
// target.SetProperty(propertyName, ((DateTime)getValue()).ToCodeExpression(this.OuterClass));
// }
// else if (propertyType == typeof(long))
// {
// target.SetProperty(propertyName, (long)getValue());
// }
// else if (propertyType == typeof(Guid))
// {
// target.SetProperty(propertyName, (Guid)getValue());
// }
// else if (typeof(Enum).IsAssignableFrom(propertyType))
// {
// target.SetProperty(propertyName, (Enum)getValue());
// }
// else if (propertyType == typeof(ValueListReferenceDef))
// {
// var typedPropValue = (ValueListReferenceDef)getValue();
// if (typedPropValue != null)
// {
// var factoryMethod = RenderValueListReferenceDef.Render(outerClass, (ValueListReferenceDef)getValue());
// target.SetProperty(propertyName, factoryMethod);
// }
// }
// else if (propertyType == typeof(VocabularyDef))
// {
// var factoryMethod = RenderVocabularyDef.Render(outerClass, (VocabularyDef)getValue());
// target.SetProperty(propertyName, factoryMethod);
// }
// else if (propertyType == typeof(CalcDef))
// {
// if (getValue() != null)
// {
// var typedPropValue = (CalcDef)getValue();
// if (!string.IsNullOrEmpty(typedPropValue.FormulaText))
// {
// var factoryMethod = RenderCalcDef.Render(outerClass, (CalcDef)getValue());
// target.SetProperty(propertyName, factoryMethod);
// }
// }
// }
// else if (propertyType == typeof(StringCollection))
// {
// var typedPropValue = (StringCollection)getValue();
// var currValue = getValue();
// if (currValue == null)
// {
// target.SetProperty(propertyName, typeof(StringCollection).CallCodeConstructor());
// }
// var collection = target.GetPropertyReference(propertyName);
// List<CodeExpression> vals = new List<CodeExpression>();
// foreach (var val in typedPropValue)
// {
// vals.Add(val.ToCodeExpression(this.OuterClass));
// }
// var array = new CodeArrayCreateExpression(typeof(String[]).ToCodeTypeReference(), vals.ToArray());
// collection.AddInvokeMethodStatement("AddRange", array);
// }
// else if (TryRenderCollectionProperty<InRule.Repository.Constraints.FieldConstraintDefCollection, InRule.Repository.Constraints.FieldConstraintDef>(RenderFieldConstraintDef.Render, outerClass, propertyName, propertyType, getValue)) { }
// else if (TryRenderCollectionProperty<RuleElementDefCollection, RuleElementDef>(RenderRuleElementDef.Render, outerClass, propertyName, propertyType, getValue)) { }
// else if (TryRenderCollectionProperty<ExecuteActionParamDefCollection, ExecuteActionParamDef>(RenderExecuteActionParamDef.Render, outerClass, propertyName, propertyType, getValue)) { }
// else if (TryRenderCollectionProperty<FieldDefCollection, FieldDef>(RenderFieldDef.Render, outerClass, propertyName, propertyType, getValue)) { }
// else if (TryRenderCollectionProperty<DataElementDefCollection, DataElementDef>(RenderDataElementDef.Render, outerClass, propertyName, propertyType, getValue)) { }
// else if (TryRenderCollectionProperty<CascadedReferenceDefCollection, CascadedReferenceDef>(RenderCascadedReferenceDef.Render, outerClass, propertyName, propertyType, getValue)) { }
// else if (propertyType == typeof(InRule.Repository.RuleElements.RuleElementDef))
// {
// var typedPropValue = (InRule.Repository.RuleElements.RuleElementDef)getValue();
// if (typedPropValue != null)
// {
// target.SetProperty(propertyName, RenderRuleElementDef.Render(outerClass, typedPropValue));
// }
// }
// else if (TryRenderCollectionProperty<ValueListItemDefCollection, ValueListItemDef>((outer, def) => def.ToCodeExpression(this.OuterClass), outerClass, propertyName, propertyType, getValue)) { }
// else if (TryRenderCollectionProperty<InRule.Repository.Utilities.ExpressionDictionary, KeyValuePair<string, string>>((outer, def) => def.Key.ToCodeExpression(this.OuterClass), (outer, def) => def.Value.ToCodeExpression(this.OuterClass), outerClass, propertyName, propertyType, getValue)) { }
// else if (TryRenderCollectionProperty<TemplateAvailabilitySettingCollection, TemplateAvailabilitySetting>(RenderTemplateAvailability.Render, outerClass, propertyName, propertyType, getValue)) { }
// else if (TryRenderCollectionProperty<TemplateDefCollection, TemplateDef>(RenderTemplateDef.Render, outerClass, propertyName, propertyType, getValue)) { }
// else if (TryRenderCollectionProperty<ImpersonationDefCollection, ImpersonationDef>(RenderImpersonationDef.Render, outerClass, propertyName, propertyType, getValue)) { }
// else if (TryRenderCollectionProperty<TemplatePlaceholderDefCollection, TemplatePlaceholderDef>(RenderTemplatePlaceholderDef.Render, outerClass, propertyName, propertyType, getValue)) { }
// else if (TryRenderCollectionProperty<PlaceholderValueDefCollection, PlaceholderValueDef>(RenderPlaceholderValueDef.Render, outerClass, propertyName, propertyType, getValue)) { }
// else if (TryRenderCollectionProperty<CollectionMemberValueAssignmentDefCollection, CollectionMemberValueAssignmentDef>(RenderCollectionMemberValueAssignmentDef.Render, outerClass, propertyName, propertyType, getValue)) { }
// else if (TryRenderCollectionProperty<EndPointDefCollection, EndPointDef>(RenderEndPointDef.Render, outerClass, propertyName, propertyType, getValue)) { }
// else if (TryRenderCollectionProperty<SqlQueryParmDefCollection, SqlQueryParmDef>(RenderSqlQueryParmDef.Render, outerClass, propertyName, propertyType, getValue)) { }
// // Decision Tables
// else if (TryRenderCollectionProperty<ConditionDimensionDefCollection, ConditionDimensionDef>((outer, def) => def.ToCodeExpression(this.OuterClass), outerClass, propertyName, propertyType, getValue)) { }
// else if (TryRenderCollectionProperty<ActionDimensionDefCollection, ActionDimensionDef>(RenderActionDimensionDef.Render, outerClass, propertyName, propertyType, getValue)) { }
// else if (TryRenderCollectionProperty<DecisionDefCollection, DecisionDef>(RenderDecisionDef.Render, outerClass, propertyName, propertyType, getValue)) { }
// else if (TryRenderCollectionProperty<ConditionValueDefCollection, ConditionValueDef>(RenderConditionValueDef.Render, outerClass, propertyName, propertyType, getValue)) { }
// else if (TryRenderCollectionProperty<ActionValueDefCollection, ActionValueDef>(RenderActionValueDef.Render, outerClass, propertyName, propertyType, getValue)) { }
// else if (TryRenderCollectionProperty<ConditionNodeDefCollection, ConditionNodeDef>((outer, def) => def.ToCodeExpression(this.OuterClass), outerClass, propertyName, propertyType, getValue)) { }
// else if (TryRenderCollectionProperty<ActionNodeDefCollection, ActionNodeDef>((outer, def) => def.ToCodeExpression(this.OuterClass), outerClass, propertyName, propertyType, getValue)) { }
// else if (TryRenderCollectionProperty<InRule.Repository.Utilities.ExpressionDictionary, KeyValuePair<string, string>>((outer, def) => def.Key.ToCodeExpression(this.OuterClass), (outer, def) => def.Value.ToCodeExpression(this.OuterClass), outerClass, propertyName, propertyType, getValue)) { }
// // Data
// else if (TryRenderCollectionProperty<ExecuteSqlQueryActionParameterValueDefCollection, ExecuteSqlQueryActionParameterValueDef>((outer, def) => def.ToCodeExpression(this.OuterClass), outerClass, propertyName, propertyType, getValue)) { }
// else if (TryRenderProperty<TableSettings>((outer, def) => def.ToCodeExpression(this.OuterClass), outerClass, propertyName, propertyType, getValue)) { }
// else if (propertyType == typeof(InRule.Repository.SqlQuerySettings))
// {
// var typedPropValue = (InRule.Repository.SqlQuerySettings)getValue();
// if (typedPropValue != null)
// {
// target.SetProperty(propertyName, RenderSqlQuerySettings.Render(outerClass, typedPropValue));
// }
// }
// else if (TryRenderCollectionProperty<XmlSerializableStringDictionary, XmlSerializableStringDictionary.XmlSerializableStringDictionaryItem>((outer, def) => typeof(XmlSerializableStringDictionary.XmlSerializableStringDictionaryItem)
// .CallCodeConstructor(def.Key.ToCodeExpression(outerClass), def.Value.ToCodeExpression(outerClass)), outerClass, propertyName, propertyType, getValue)) { }
// // Rules
// else if (TryRenderCollectionProperty<NameExpressionPairDefCollection, NameExpressionPairDef>((outer, def) => def.ToCodeExpression(this.OuterClass), outerClass, propertyName, propertyType, getValue)) { }
// else if (TryRenderCollectionProperty<ExecuteMethodActionParamDefCollection, ExecuteMethodActionParamDef>((outer, def) => def.ToCodeExpression(this.OuterClass), outerClass, propertyName, propertyType, getValue)) { }
// else if (TryRenderCollectionProperty<SendMailActionAttachmentDefCollection, SendMailActionAttachmentDef>((outer, def) => def.ToCodeExpression(this.OuterClass), outerClass, propertyName, propertyType, getValue)) { }
// else if (TryRenderCollectionProperty<InRule.Repository.Classifications.ClassificationDefCollection, InRule.Repository.Classifications.ClassificationDef>((outer, def) => def.ToCodeExpression(this.OuterClass), outerClass, propertyName, propertyType, getValue)) { }
// // Schema
// else if (TryRenderCollectionProperty<TypeMappingCollection, TypeMapping>((outer, def) => def.ToCodeExpression(outerClass), outerClass, propertyName, propertyType, getValue)) { }
// // Vocabulary
// else if (TryRenderCollectionProperty<NameSortOrderDefCollection, NameSortOrderDef>((outer, def) => def.ToCodeExpression(this.OuterClass), outerClass, propertyName, propertyType, getValue)) { }
// else if (propertyType == typeof(RuleRepositoryDefBase.DefMetadataCollectionCollection))
// {
// SetPropertyForAttributes(target, outerClass, getValue());
// }
// else if (propertyType == typeof(DataSet))
// {
// var typedPropValue = (DataSet)getValue();
// if (typedPropValue != null)
// {
// if (typedPropValue.Tables.Count > 0)
// {
// target.SetProperty(propertyName, RenderDataSet.Render(outerClass, typedPropValue));
// }
// }
// }
// else if (propertyType == typeof(DataTable))
// {
// var typedPropValue = (DataTable)getValue();
// if (typedPropValue != null)
// {
// target.SetProperty(propertyName, RenderDataTable.Render(outerClass, typedPropValue));
// }
// }
// else if (typeof(InRule.Repository.RuleElements.RuleElementDef).IsAssignableFrom(propertyType))
// {
// var typedPropValue = (RuleElementDef)getValue();
// if (typedPropValue != null)
// {
// target.SetProperty(propertyName, RenderRuleElementDef.Render(outerClass, typedPropValue));
// }
// }
// else if (typeof(XmlDocumentSettings).IsAssignableFrom(propertyType))
// {
// var typedPropValue = (XmlDocumentSettings)getValue();
// if (typedPropValue != null)
// {
// target.SetProperty(propertyName, RenderXmlDocumentSettings.Render(outerClass, typedPropValue));
// }
// }
// else if (typeof(XPathQuerySettings).IsAssignableFrom(propertyType))
// {
// var typedPropValue = (XPathQuerySettings)getValue();
// if (typedPropValue != null)
// {
// target.SetProperty(propertyName, RenderXPathQuerySettings.Render(outerClass, typedPropValue));
// }
// }
// else if (typeof(string[]).IsAssignableFrom(propertyType))
// {
// var typedPropValue = (string[])getValue();
// if (typedPropValue != null)
// {
// target.SetProperty(propertyName, typedPropValue.ToCodeExpression(outerClass));
// }
// }
// else if (this.TryRenderCollectionProperty<InRule.Repository.EntityDefInfoCollection, InRule.Repository.EntityDefInfo>(RenderAssemblyDefInfo.Render, outerClass, propertyName, propertyType, getValue)) { }
// else if (this.TryRenderCollectionProperty<InRule.Repository.EndPoints.AssemblyDef.ClassInfoCollection, InRule.Repository.EndPoints.AssemblyDef.ClassInfo>(RenderAssemblyDefInfo.Render, outerClass, propertyName, propertyType, getValue)) { }
// else if (this.TryRenderCollectionProperty<InRule.Repository.WebServiceDef.OperationDefCollection, InRule.Repository.WebServiceDef.OperationDef>(RenderWebServiceDef.Render, outerClass, propertyName, propertyType, getValue)) { }
// else if (this.TryRenderCollectionProperty<InRule.Repository.WebServiceDef.ServicesDefCollection, InRule.Repository.WebServiceDef.ServicesDef>(RenderWebServiceDef.Render, outerClass, propertyName, propertyType, getValue)) { }
// else if (this.TryRenderCollectionProperty<ExecuteRulesetParameterDefCollection, ExecuteRulesetParameterDef>(RenderVocabularyElementDef.Render, outerClass, propertyName, propertyType, getValue)) { }
// else if (this.TryRenderCollectionProperty<InRule.Repository.UDFs.UdfLibraryDefCollection, InRule.Repository.UDFs.UdfLibraryDef>(RenderUdfLibraryDef.Render, outerClass, propertyName, propertyType, getValue)) { }
// else if (propertyType == typeof(InRule.Repository.XmlQualifiedNameInfo[]))
// {
// var typedPropValue = (InRule.Repository.XmlQualifiedNameInfo[])getValue();
// var value = new CodeArrayCreateExpression(typeof(InRule.Repository.XmlQualifiedNameInfo[]).ToCodeTypeReference(), typedPropValue.Select(i => RenderAssemblyDefInfo.Render(outerClass, i)).ToArray());
// target.SetProperty(propertyName, value);
// }
// else if (typeof(InRule.Repository.EntityDefsInfo).IsAssignableFrom(propertyType)
// || typeof(InRule.Repository.EndPoints.AssemblyDef.TypeConverterInfo).IsAssignableFrom(propertyType)
// || typeof(InRule.Repository.EndPoints.AssemblyDef.ClassInfo).IsAssignableFrom(propertyType)
// )
// {
// var typedPropValue = getValue();
// if (typedPropValue != null)
// {
// target.SetProperty(propertyName, RenderAssemblyDefInfo.Render(outerClass, typedPropValue));
// }
// }
// else
// {
// target.AddLiteralStatement(String.Format("Unhandled Type: '{3}' at {0}.SetProperty(\"{1}\", {2});", target.VariableName, propertyName, getValue(), propertyType.FullName));
// }
//}
//public bool TryRenderProperty<TType>(Func<CodeTypeDeclarationEx, TType, CodeExpression> render, CodeTypeDeclarationEx outerClass, string propertyName, Type propertyType, Func<object> getValue)
//{
// var target = this;
// if (typeof(TType).IsAssignableFrom(propertyType))
// {
// var typedPropValue = (TType)getValue();
// if (typedPropValue != null)
// {
// target.SetProperty(propertyName, render(outerClass, typedPropValue));
// }
// return true;
// }
// return false;
//}
//public bool TryRenderCollectionProperty<TCollection, TType>(Func<CodeTypeDeclarationEx, TType, CodeExpression> render, CodeTypeDeclarationEx outerClass, string propertyName, Type propertyType, Func<object> getValue) where TCollection : IEnumerable
//{
// var target = this;
// if (propertyType == typeof(TCollection))
// {
// var typedPropValue = (TCollection)getValue();
// if (typedPropValue != null)
// {
// foreach (TType def in typedPropValue)
// {
// target.GetPropertyReference(propertyName)
// .AddInvokeMethodStatement("Add", render(outerClass, def));
// }
// }
// return true;
// }
// return false;
//}
//public bool TryRenderCollectionProperty<TCollection, TType>(Func<CodeTypeDeclarationEx, TType, CodeExpression> renderArg1, Func<CodeTypeDeclarationEx, TType, CodeExpression> renderArg2, CodeTypeDeclarationEx outerClass, string propertyName, Type propertyType, Func<object> getValue) where TCollection : IEnumerable
//{
// var target = this;
// if (propertyType == typeof(TCollection))
// {
// var typedPropValue = (TCollection)getValue();
// if (typedPropValue != null)
// {
// foreach (TType def in typedPropValue)
// {
// target.GetPropertyReference(propertyName)
// .AddInvokeMethodStatement("Add", renderArg1(outerClass, def), renderArg2(outerClass, def));
// }
// }
// return true;
// }
// return false;
//}
////private static void SetPropertyForAttributes(CodeMethodVariableReferenceEx target, CodeTypeDeclarationEx outerClass, object propValue)
////{
//// var propCollections = (RuleRepositoryDefBase.DefMetadataCollectionCollection)propValue;
//// foreach (RuleRepositoryDefBase.DefMetadataCollectionCollection.CollectionItem propCollection in propCollections)
// {
// // DefaultAttributeGroupKey
// // ReservedInRuleAttributeGroupKey
// // ReservedInRuleTokenKey
// // ReservedInRuleVersionConversionKey
// // ReservedInRuleTemplateConversionKey
// CodeMethodVariableReferenceEx collection = null;
// if (propCollection.Key == RuleRepositoryDefBase.DefaultAttributeGroupKey)
// {
// collection = target.GetPropertyReference("Attributes");
// }
// else if (propCollection.Key == RuleRepositoryDefBase.ReservedInRuleAttributeGroupKey)
// {
// collection =
// target.GetPropertyReference("Attributes")
// .GetIndexer(
// typeof(RuleRepositoryDefBase).ToCodeTypeReference()
// .ToCodeExpression(outerClass)
// .GetCodeProperty("ReservedInRuleAttributeGroupKey"));
// }
// else if (propCollection.Key == RuleRepositoryDefBase.ReservedInRuleTokenKey)
// {
// continue; // Ignoring for now to make rendering much smaller
// collection =
// target.GetPropertyReference("Attributes")
// .GetIndexer(
// typeof(RuleRepositoryDefBase).ToCodeTypeReference()
// .ToCodeExpression(outerClass)
// .GetCodeProperty("ReservedInRuleTokenKey"));
// }
// else if (propCollection.Key == RuleRepositoryDefBase.ReservedInRuleVersionConversionKey)
// {
// collection =
// target.GetPropertyReference("Attributes")
// .GetIndexer(
// typeof(RuleRepositoryDefBase).ToCodeTypeReference()
// .ToCodeExpression(outerClass)
// .GetCodeProperty("ReservedInRuleVersionConversionKey"));
// }
// else if (propCollection.Key == RuleRepositoryDefBase.ReservedInRuleTemplateConversionKey)
// {
// collection =
// target.GetPropertyReference("Attributes")
// .GetIndexer(
// typeof(RuleRepositoryDefBase).ToCodeTypeReference()
// .ToCodeExpression(outerClass)
// .GetCodeProperty("ReservedInRuleTemplateConversionKey"));
// }
// else
// {
// var keyRef = typeof(AttributeGroupKey).CallCodeConstructor(propCollection.Key.Name.ToCodeExpression(outerClass),
// propCollection.Key.Guid.ToCodeExpression(outerClass));
// var keyRefVar = target.DeclareVariable("AttribKey_" + propCollection.Key.Name, typeof(AttributeGroupKey),
// keyRef);
// collection = target.GetPropertyReference("Attributes").GetIndexer(keyRefVar);
// }
// foreach (
// InRule.Repository.XmlSerializableStringDictionary.XmlSerializableStringDictionaryItem value in
// propCollection.Collection)
// {
// collection.SetIndexerValue(value.Key, value.Value);
// }
// int a = 1;
// }
//}
}
}
| |
// Copyright 2007-2011 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit.Transports
{
using System;
using System.Collections.Generic;
using System.Threading;
using Context;
using Loopback;
using Magnum.Extensions;
using Subscriptions.Coordinator;
/// <summary>
/// The loopback transport is a built-in transport for MassTransit that
/// works on messages in-memory. It is dependent on the <see cref="SubscriptionLoopback"/>
/// that takes care of subscribing the buses in the process
/// depending on what subscriptions are made.
/// </summary>
public class LoopbackTransport :
IDuplexTransport
{
readonly object _messageReadLock = new object();
readonly object _messageWriteLock = new object();
readonly TimeSpan _deadlockTimeout = new TimeSpan(0, 1, 0);
bool _disposed;
AutoResetEvent _messageReady = new AutoResetEvent(false);
LinkedList<LoopbackMessage> _messages = new LinkedList<LoopbackMessage>();
public LoopbackTransport(IEndpointAddress address)
{
Address = address;
}
public int Count
{
get
{
int messageCount;
if (!Monitor.TryEnter(_messageReadLock, _deadlockTimeout))
throw new Exception("Deadlock detected!");
try
{
GuardAgainstDisposed();
messageCount = _messages.Count;
}
finally
{
Monitor.Exit(_messageReadLock);
}
return messageCount;
}
}
public IEndpointAddress Address { get; private set; }
public IOutboundTransport OutboundTransport
{
get { return this; }
}
public IInboundTransport InboundTransport
{
get { return this; }
}
public void Send(ISendContext context)
{
GuardAgainstDisposed();
LoopbackMessage message = null;
try
{
message = new LoopbackMessage();
if (context.ExpirationTime.HasValue)
{
message.ExpirationTime = context.ExpirationTime.Value;
}
context.SerializeTo(message.Body);
message.ContentType = context.ContentType;
message.OriginalMessageId = context.OriginalMessageId;
if (!Monitor.TryEnter(_messageWriteLock, _deadlockTimeout))
throw new Exception("Deadlock detected!");
try
{
GuardAgainstDisposed();
_messages.AddLast(message);
}
finally
{
Monitor.Exit(_messageWriteLock);
}
Address.LogSent(message.MessageId, context.MessageType);
}
catch
{
if (message != null)
message.Dispose();
throw;
}
_messageReady.Set();
}
public void Receive(Func<IReceiveContext, Action<IReceiveContext>> callback, TimeSpan timeout)
{
int messageCount = Count;
bool waited = false;
if (messageCount == 0)
{
if (!_messageReady.WaitOne(timeout, true))
return;
waited = true;
}
bool monitorExitNeeded = true;
if (!Monitor.TryEnter(_messageReadLock, timeout))
return;
try
{
for (LinkedListNode<LoopbackMessage> iterator = _messages.First;
iterator != null;
iterator = iterator.Next)
{
if (iterator.Value != null)
{
LoopbackMessage message = iterator.Value;
if (message.ExpirationTime.HasValue && message.ExpirationTime <= DateTime.UtcNow)
{
if (!Monitor.TryEnter(_messageWriteLock, _deadlockTimeout))
throw new Exception("Deadlock detected!");
try
{
_messages.Remove(iterator);
}
finally
{
Monitor.Exit(_messageWriteLock);
}
return;
}
ReceiveContext context = ReceiveContext.FromBodyStream(message.Body);
context.SetMessageId(message.MessageId);
context.SetContentType(message.ContentType);
context.SetOriginalMessageId(message.OriginalMessageId);
if (message.ExpirationTime.HasValue)
context.SetExpirationTime(message.ExpirationTime.Value);
Action<IReceiveContext> receive = callback(context);
if (receive == null)
continue;
if (!Monitor.TryEnter(_messageWriteLock, _deadlockTimeout))
throw new Exception("Deadlock detected!");
try
{
_messages.Remove(iterator);
}
finally
{
Monitor.Exit(_messageWriteLock);
}
using (message)
{
Monitor.Exit(_messageReadLock);
monitorExitNeeded = false;
receive(context);
return;
}
}
}
if (waited)
return;
// we read to the end and none were accepted, so we are going to wait until we get another in the queue
// make any other potential readers wait as well
_messageReady.WaitOne(timeout, true);
}
finally
{
if (monitorExitNeeded)
Monitor.Exit(_messageReadLock);
}
}
public void Dispose()
{
Dispose(true);
}
void GuardAgainstDisposed()
{
if (_disposed)
throw new ObjectDisposedException("The transport has already been disposed: " + Address);
}
void Dispose(bool disposing)
{
if (_disposed)
return;
if (disposing)
{
lock (_messageReadLock)
{
lock (_messageWriteLock)
{
_messages.Each(x => x.Dispose());
_messages.Clear();
_messages = null;
}
}
_messageReady.Close();
using (_messageReady)
{
}
_messageReady = null;
}
_disposed = true;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.ApiManagement
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Azure.OData;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for LoggerOperations.
/// </summary>
public static partial class LoggerOperationsExtensions
{
/// <summary>
/// Lists a collection of loggers in the specified service instance.
/// <see href="https://docs.microsoft.com/en-us/azure/api-management/api-management-howto-log-event-hubs" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
public static IPage<LoggerContract> ListByService(this ILoggerOperations operations, string resourceGroupName, string serviceName, ODataQuery<LoggerContract> odataQuery = default(ODataQuery<LoggerContract>))
{
return ((ILoggerOperations)operations).ListByServiceAsync(resourceGroupName, serviceName, odataQuery).GetAwaiter().GetResult();
}
/// <summary>
/// Lists a collection of loggers in the specified service instance.
/// <see href="https://docs.microsoft.com/en-us/azure/api-management/api-management-howto-log-event-hubs" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<LoggerContract>> ListByServiceAsync(this ILoggerOperations operations, string resourceGroupName, string serviceName, ODataQuery<LoggerContract> odataQuery = default(ODataQuery<LoggerContract>), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByServiceWithHttpMessagesAsync(resourceGroupName, serviceName, odataQuery, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets the details of the logger specified by its identifier.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='loggerid'>
/// Logger identifier. Must be unique in the API Management service instance.
/// </param>
public static LoggerContract Get(this ILoggerOperations operations, string resourceGroupName, string serviceName, string loggerid)
{
return operations.GetAsync(resourceGroupName, serviceName, loggerid).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the details of the logger specified by its identifier.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='loggerid'>
/// Logger identifier. Must be unique in the API Management service instance.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<LoggerContract> GetAsync(this ILoggerOperations operations, string resourceGroupName, string serviceName, string loggerid, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, serviceName, loggerid, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates or Updates a logger.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='loggerid'>
/// Logger identifier. Must be unique in the API Management service instance.
/// </param>
/// <param name='parameters'>
/// Create parameters.
/// </param>
public static LoggerContract CreateOrUpdate(this ILoggerOperations operations, string resourceGroupName, string serviceName, string loggerid, LoggerContract parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, serviceName, loggerid, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or Updates a logger.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='loggerid'>
/// Logger identifier. Must be unique in the API Management service instance.
/// </param>
/// <param name='parameters'>
/// Create parameters.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<LoggerContract> CreateOrUpdateAsync(this ILoggerOperations operations, string resourceGroupName, string serviceName, string loggerid, LoggerContract parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, serviceName, loggerid, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates an existing logger.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='loggerid'>
/// Logger identifier. Must be unique in the API Management service instance.
/// </param>
/// <param name='parameters'>
/// Update parameters.
/// </param>
/// <param name='ifMatch'>
/// The entity state (Etag) version of the logger to update. A value of "*" can
/// be used for If-Match to unconditionally apply the operation.
/// </param>
public static void Update(this ILoggerOperations operations, string resourceGroupName, string serviceName, string loggerid, LoggerUpdateContract parameters, string ifMatch)
{
operations.UpdateAsync(resourceGroupName, serviceName, loggerid, parameters, ifMatch).GetAwaiter().GetResult();
}
/// <summary>
/// Updates an existing logger.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='loggerid'>
/// Logger identifier. Must be unique in the API Management service instance.
/// </param>
/// <param name='parameters'>
/// Update parameters.
/// </param>
/// <param name='ifMatch'>
/// The entity state (Etag) version of the logger to update. A value of "*" can
/// be used for If-Match to unconditionally apply the operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task UpdateAsync(this ILoggerOperations operations, string resourceGroupName, string serviceName, string loggerid, LoggerUpdateContract parameters, string ifMatch, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.UpdateWithHttpMessagesAsync(resourceGroupName, serviceName, loggerid, parameters, ifMatch, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Deletes the specified logger.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='loggerid'>
/// Logger identifier. Must be unique in the API Management service instance.
/// </param>
/// <param name='ifMatch'>
/// The entity state (Etag) version of the logger to delete. A value of "*" can
/// be used for If-Match to unconditionally apply the operation.
/// </param>
public static void Delete(this ILoggerOperations operations, string resourceGroupName, string serviceName, string loggerid, string ifMatch)
{
operations.DeleteAsync(resourceGroupName, serviceName, loggerid, ifMatch).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified logger.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='loggerid'>
/// Logger identifier. Must be unique in the API Management service instance.
/// </param>
/// <param name='ifMatch'>
/// The entity state (Etag) version of the logger to delete. A value of "*" can
/// be used for If-Match to unconditionally apply the operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this ILoggerOperations operations, string resourceGroupName, string serviceName, string loggerid, string ifMatch, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(resourceGroupName, serviceName, loggerid, ifMatch, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Lists a collection of loggers in the specified service instance.
/// <see href="https://docs.microsoft.com/en-us/azure/api-management/api-management-howto-log-event-hubs" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<LoggerContract> ListByServiceNext(this ILoggerOperations operations, string nextPageLink)
{
return operations.ListByServiceNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Lists a collection of loggers in the specified service instance.
/// <see href="https://docs.microsoft.com/en-us/azure/api-management/api-management-howto-log-event-hubs" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<LoggerContract>> ListByServiceNextAsync(this ILoggerOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByServiceNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
/*
* CompareInfo.cs - Implementation of the
* "System.Globalization.CompareInfo" class.
*
* Copyright (C) 2001, 2002, 2003 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.Globalization
{
using System.Text;
using System.Reflection;
using System.Runtime.Serialization;
public class CompareInfo : IDeserializationCallback
{
// Culture that this comparison object is attached to.
private int culture;
// Global compare object for the invariant culture.
private static CompareInfo invariantCompare;
// Programmers cannot create instances of this class according
// to the specification, even though it has virtual methods!
// In fact, we _can_ inherit it through "_I18NCompareInfo",
// but that is private to this implementation and should not be
// used by application programmers.
internal CompareInfo(int culture)
{
this.culture = culture;
}
// Get the invariant CompareInfo object.
internal static CompareInfo InvariantCompareInfo
{
get
{
lock(typeof(CompareInfo))
{
if(invariantCompare == null)
{
invariantCompare = new CompareInfo(0x007F);
}
return invariantCompare;
}
}
}
// Get the comparison information for a specific culture.
public static CompareInfo GetCompareInfo(int culture)
{
return (new CultureInfo(culture)).CompareInfo;
}
public static CompareInfo GetCompareInfo(String culture)
{
if(culture == null)
{
throw new ArgumentNullException("culture");
}
#if CONFIG_REFLECTION
return (new CultureInfo(culture)).CompareInfo;
#else
return InvariantCompareInfo;
#endif
}
#if CONFIG_REFLECTION
public static CompareInfo GetCompareInfo(int culture, Assembly assembly)
{
if(assembly == null)
{
throw new ArgumentNullException("assembly");
}
else if(assembly != typeof(Object).Module.Assembly)
{
throw new ArgumentException
(_("Arg_MustBeCoreLib"), "assembly");
}
return GetCompareInfo(culture);
}
public static CompareInfo GetCompareInfo(String culture, Assembly assembly)
{
if(assembly == null)
{
throw new ArgumentNullException("assembly");
}
else if(assembly != typeof(Object).Module.Assembly)
{
throw new ArgumentException
(_("Arg_MustBeCoreLib"), "assembly");
}
return GetCompareInfo(culture);
}
#endif // CONFIG_REFLECTION
// Get the identifier for this comparison object's culture.
public int LCID
{
get
{
return culture;
}
}
// Compare two strings.
public virtual int Compare(String string1, String string2)
{
return DefaultCompare(string1, 0,
((string1 != null) ? string1.Length : 0),
string2, 0,
((string2 != null) ? string2.Length : 0),
CompareOptions.None);
}
public virtual int Compare(String string1, String string2,
CompareOptions options)
{
return DefaultCompare(string1, 0,
((string1 != null) ? string1.Length : 0),
string2, 0,
((string2 != null) ? string2.Length : 0),
options);
}
public virtual int Compare(String string1, int offset1,
String string2, int offset2)
{
return DefaultCompare(string1, offset1,
((string1 != null) ?
(string1.Length - offset1) : 0),
string2, offset2,
((string2 != null) ?
(string2.Length - offset2) : 0),
CompareOptions.None);
}
public virtual int Compare(String string1, int offset1,
String string2, int offset2,
CompareOptions options)
{
return DefaultCompare(string1, offset1,
((string1 != null) ?
(string1.Length - offset1) : 0),
string2, offset2,
((string2 != null) ?
(string2.Length - offset2) : 0),
options);
}
public virtual int Compare(String string1, int offset1, int length1,
String string2, int offset2, int length2)
{
return DefaultCompare(string1, offset1, length1,
string2, offset2, length2,
CompareOptions.None);
}
public virtual int Compare(String string1, int offset1, int length1,
String string2, int offset2, int length2,
CompareOptions options)
{
return DefaultCompare(string1, offset1, length1,
string2, offset2, length2, options);
}
// Default "Compare" implementation that uses I18N to do the work.
private int DefaultCompare(String string1, int offset1, int length1,
String string2, int offset2, int length2,
CompareOptions options)
{
if(offset1 < 0)
{
throw new ArgumentOutOfRangeException
("offset1", _("ArgRange_StringIndex"));
}
if(offset2 < 0)
{
throw new ArgumentOutOfRangeException
("offset2", _("ArgRange_StringIndex"));
}
if(length1 < 0)
{
throw new ArgumentOutOfRangeException
("length1", _("ArgRange_StringRange"));
}
if(length2 < 0)
{
throw new ArgumentOutOfRangeException
("length2", _("ArgRange_StringRange"));
}
if(string1 != null && string1.Length != 0)
{
if(offset1 >= string1.Length)
{
throw new ArgumentOutOfRangeException
("offset1", _("ArgRange_StringIndex"));
}
if(length1 > (string1.Length - offset1))
{
throw new ArgumentOutOfRangeException
("length1", _("ArgRange_StringRange"));
}
}
else
{
if(offset1 > 0)
{
throw new ArgumentOutOfRangeException
("offset1", _("ArgRange_StringIndex"));
}
if(length1 > 0)
{
throw new ArgumentOutOfRangeException
("length1", _("ArgRange_StringRange"));
}
}
if(string2 != null && string2.Length != 0)
{
if(offset2 >= string2.Length)
{
throw new ArgumentOutOfRangeException
("offset2", _("ArgRange_StringIndex"));
}
if(length2 > (string2.Length - offset2))
{
throw new ArgumentOutOfRangeException
("length2", _("ArgRange_StringRange"));
}
}
else
{
if(offset2 > 0)
{
throw new ArgumentOutOfRangeException
("offset2", _("ArgRange_StringIndex"));
}
if(length2 > 0)
{
throw new ArgumentOutOfRangeException
("length2", _("ArgRange_StringRange"));
}
}
#if CONFIG_REFLECTION
if(this is _I18NCompareInfo)
{
// Use the I18N-supplied comparison routine.
return ((_I18NCompareInfo)this).CompareImpl
(string1, offset1, length1,
string2, offset2, length2, options);
}
else
#endif
{
// Use the invariant comparison method in the engine.
return String.CompareInternal
(string1, offset1, length1,
string2, offset2, length2,
((options & CompareOptions.IgnoreCase) != 0));
}
}
// Determine if two CompareInfo objects are equal.
public override bool Equals(Object obj)
{
CompareInfo other = (obj as CompareInfo);
if(other != null)
{
return (LCID == other.LCID);
}
else
{
return false;
}
}
// Get a hash code for this object.
public override int GetHashCode()
{
return LCID;
}
#if !ECMA_COMPAT
// Get the sort key for a string.
public virtual SortKey GetSortKey(String source)
{
return GetSortKey(source, CompareOptions.None);
}
public virtual SortKey GetSortKey(String source, CompareOptions options)
{
if(source == null)
{
throw new ArgumentNullException("source");
}
if(this is _I18NCompareInfo)
{
// Ask the subclass for the raw sort key data.
return new SortKey(((_I18NCompareInfo)this).GetSortKeyImpl
(source, options), source);
}
else
{
// Return the invariant sort key information.
if((options & CompareOptions.IgnoreCase) != 0)
{
return new SortKey
(Encoding.UTF8.GetBytes
(CultureInfo.InvariantCulture.TextInfo
.ToLower(source)), source);
}
else
{
return new SortKey
(Encoding.UTF8.GetBytes(source), source);
}
}
}
#endif // !ECMA_COMPAT
// Search for a specific character in a string.
public virtual int IndexOf(String source, char value)
{
if(source == null)
{
throw new ArgumentNullException("source");
}
return IndexOf(source, value, 0, source.Length,
CompareOptions.None);
}
public virtual int IndexOf(String source, char value,
CompareOptions options)
{
if(source == null)
{
throw new ArgumentNullException("source");
}
return IndexOf(source, value, 0, source.Length, options);
}
public virtual int IndexOf(String source, char value, int startIndex)
{
if(source == null)
{
throw new ArgumentNullException("source");
}
return IndexOf(source, value, startIndex,
source.Length - startIndex,
CompareOptions.None);
}
public virtual int IndexOf(String source, char value, int startIndex,
CompareOptions options)
{
if(source == null)
{
throw new ArgumentNullException("source");
}
return IndexOf(source, value, startIndex,
source.Length - startIndex, options);
}
public virtual int IndexOf(String source, char value,
int startIndex, int count)
{
return IndexOf(source, value, startIndex, count,
CompareOptions.None);
}
public virtual int IndexOf(String source, char value,
int startIndex, int count,
CompareOptions options)
{
// This may be overridden in subclasses with a more
// efficient implementation if desired.
return IndexOf(source, new String(value, 1),
startIndex, count, options);
}
// Search for a specific substring in a string.
public virtual int IndexOf(String source, String value)
{
if(source == null)
{
throw new ArgumentNullException("source");
}
return IndexOf(source, value, 0, source.Length,
CompareOptions.None);
}
public virtual int IndexOf(String source, String value,
CompareOptions options)
{
if(source == null)
{
throw new ArgumentNullException("source");
}
return IndexOf(source, value, 0, source.Length, options);
}
public virtual int IndexOf(String source, String value, int startIndex)
{
if(source == null)
{
throw new ArgumentNullException("source");
}
return IndexOf(source, value, startIndex,
source.Length - startIndex,
CompareOptions.None);
}
public virtual int IndexOf(String source, String value, int startIndex,
CompareOptions options)
{
if(source == null)
{
throw new ArgumentNullException("source");
}
return IndexOf(source, value, startIndex,
source.Length - startIndex, options);
}
public virtual int IndexOf(String source, String value,
int startIndex, int count)
{
return IndexOf(source, value, startIndex, count,
CompareOptions.None);
}
public virtual int IndexOf(String source, String value,
int startIndex, int count,
CompareOptions options)
{
if(source == null)
{
throw new ArgumentNullException("source");
}
if(value == null)
{
throw new ArgumentNullException("value");
}
if(startIndex < 0)
{
throw new ArgumentOutOfRangeException
("startIndex", _("ArgRange_StringIndex"));
}
if(count < 0 || (source.Length - startIndex) < count)
{
throw new ArgumentOutOfRangeException
("count", _("ArgRange_StringRange"));
}
int vlen = value.Length;
while(count >= vlen)
{
if(Compare(source, startIndex, vlen,
value, 0, vlen, options) == 0)
{
return startIndex;
}
++startIndex;
--count;
}
return -1;
}
// Determine if one string is a prefix of another.
public virtual bool IsPrefix(String source, String prefix)
{
return IsPrefix(source, prefix, CompareOptions.None);
}
public virtual bool IsPrefix(String source, String prefix,
CompareOptions options)
{
if(source == null)
{
throw new ArgumentNullException("source");
}
if(prefix == null)
{
throw new ArgumentNullException("prefix");
}
if(source.Length < prefix.Length)
{
return false;
}
else
{
return (Compare(source, 0, prefix.Length, prefix, 0,
prefix.Length, options) == 0);
}
}
// Determine if one string is a suffix of another.
public virtual bool IsSuffix(String source, String suffix)
{
return IsSuffix(source, suffix, CompareOptions.None);
}
public virtual bool IsSuffix(String source, String suffix,
CompareOptions options)
{
if(source == null)
{
throw new ArgumentNullException("source");
}
if(suffix == null)
{
throw new ArgumentNullException("suffix");
}
if(source.Length < suffix.Length)
{
return false;
}
else
{
return (Compare(source, source.Length - suffix.Length,
suffix.Length, suffix, 0,
suffix.Length, options) == 0);
}
}
// Search backwards for a specific character in a string.
public virtual int LastIndexOf(String source, char value)
{
if(source == null)
{
throw new ArgumentNullException("source");
}
return LastIndexOf(source, value, 0, source.Length,
CompareOptions.None);
}
public virtual int LastIndexOf(String source, char value,
CompareOptions options)
{
if(source == null)
{
throw new ArgumentNullException("source");
}
return LastIndexOf(source, value, 0, source.Length, options);
}
public virtual int LastIndexOf(String source, char value, int startIndex)
{
if(source == null)
{
throw new ArgumentNullException("source");
}
return LastIndexOf(source, value, startIndex,
source.Length - startIndex,
CompareOptions.None);
}
public virtual int LastIndexOf(String source, char value, int startIndex,
CompareOptions options)
{
if(source == null)
{
throw new ArgumentNullException("source");
}
return LastIndexOf(source, value, startIndex,
source.Length - startIndex, options);
}
public virtual int LastIndexOf(String source, char value,
int startIndex, int count)
{
return LastIndexOf(source, value, startIndex, count,
CompareOptions.None);
}
public virtual int LastIndexOf(String source, char value,
int startIndex, int count,
CompareOptions options)
{
// This may be overridden in subclasses with a more
// efficient implementation if desired.
return LastIndexOf(source, new String(value, 1),
startIndex, count, options);
}
// Search backwards for a specific substring in a string.
public virtual int LastIndexOf(String source, String value)
{
if(source == null)
{
throw new ArgumentNullException("source");
}
return LastIndexOf(source, value, 0, source.Length,
CompareOptions.None);
}
public virtual int LastIndexOf(String source, String value,
CompareOptions options)
{
if(source == null)
{
throw new ArgumentNullException("source");
}
return LastIndexOf(source, value, 0, source.Length, options);
}
public virtual int LastIndexOf(String source, String value, int startIndex)
{
if(source == null)
{
throw new ArgumentNullException("source");
}
return LastIndexOf(source, value, startIndex,
source.Length - startIndex,
CompareOptions.None);
}
public virtual int LastIndexOf(String source, String value, int startIndex,
CompareOptions options)
{
if(source == null)
{
throw new ArgumentNullException("source");
}
return LastIndexOf(source, value, startIndex,
source.Length - startIndex, options);
}
public virtual int LastIndexOf(String source, String value,
int startIndex, int count)
{
return LastIndexOf(source, value, startIndex, count,
CompareOptions.None);
}
public virtual int LastIndexOf(String source, String value,
int startIndex, int count,
CompareOptions options)
{
if(source == null)
{
throw new ArgumentNullException("source");
}
if(value == null)
{
throw new ArgumentNullException("value");
}
if(startIndex < 0)
{
throw new ArgumentOutOfRangeException
("startIndex", _("ArgRange_StringIndex"));
}
if(count < 0 || (startIndex - count) < -1)
{
throw new ArgumentOutOfRangeException
("count", _("ArgRange_StringRange"));
}
int vlen = value.Length;
if(vlen == 0)
{
return 0;
}
while(count >= vlen)
{
if(Compare(source, startIndex - vlen + 1, vlen,
value, 0, vlen, options) == 0)
{
return startIndex - vlen + 1;
}
--startIndex;
--count;
}
return -1;
}
// Implement IDeserializationCallback.
void IDeserializationCallback.OnDeserialization(Object sender)
{
// Nothing to do here.
}
// Convert this object into a string.
public override String ToString()
{
return "[CompareInfo:" + culture.ToString("x") + "]";
}
}; // class CompareInfo
}; // namespace System.Globalization
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Targets.Wrappers
{
using System;
using System.ComponentModel;
using System.Threading;
using NLog.Common;
using NLog.Internal;
/// <summary>
/// A target that buffers log events and sends them in batches to the wrapped target.
/// </summary>
/// <seealso href="https://github.com/nlog/nlog/wiki/BufferingWrapper-target">Documentation on NLog Wiki</seealso>
[Target("BufferingWrapper", IsWrapper = true)]
public class BufferingTargetWrapper : WrapperTargetBase
{
private LogEventInfoBuffer _buffer;
private Timer _flushTimer;
private readonly object _lockObject = new object();
/// <summary>
/// Initializes a new instance of the <see cref="BufferingTargetWrapper" /> class.
/// </summary>
public BufferingTargetWrapper()
: this(null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="BufferingTargetWrapper" /> class.
/// </summary>
/// <param name="name">Name of the target.</param>
/// <param name="wrappedTarget">The wrapped target.</param>
public BufferingTargetWrapper(string name, Target wrappedTarget)
: this(wrappedTarget)
{
Name = name;
}
/// <summary>
/// Initializes a new instance of the <see cref="BufferingTargetWrapper" /> class.
/// </summary>
/// <param name="wrappedTarget">The wrapped target.</param>
public BufferingTargetWrapper(Target wrappedTarget)
: this(wrappedTarget, 100)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="BufferingTargetWrapper" /> class.
/// </summary>
/// <param name="wrappedTarget">The wrapped target.</param>
/// <param name="bufferSize">Size of the buffer.</param>
public BufferingTargetWrapper(Target wrappedTarget, int bufferSize)
: this(wrappedTarget, bufferSize, -1)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="BufferingTargetWrapper" /> class.
/// </summary>
/// <param name="wrappedTarget">The wrapped target.</param>
/// <param name="bufferSize">Size of the buffer.</param>
/// <param name="flushTimeout">The flush timeout.</param>
public BufferingTargetWrapper(Target wrappedTarget, int bufferSize, int flushTimeout)
: this(wrappedTarget, bufferSize, flushTimeout, BufferingTargetWrapperOverflowAction.Flush)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="BufferingTargetWrapper" /> class.
/// </summary>
/// <param name="wrappedTarget">The wrapped target.</param>
/// <param name="bufferSize">Size of the buffer.</param>
/// <param name="flushTimeout">The flush timeout.</param>
/// <param name="overflowAction">The action to take when the buffer overflows.</param>
public BufferingTargetWrapper(Target wrappedTarget, int bufferSize, int flushTimeout, BufferingTargetWrapperOverflowAction overflowAction)
{
WrappedTarget = wrappedTarget;
BufferSize = bufferSize;
FlushTimeout = flushTimeout;
SlidingTimeout = true;
OverflowAction = overflowAction;
}
/// <summary>
/// Gets or sets the number of log events to be buffered.
/// </summary>
/// <docgen category='Buffering Options' order='100' />
[DefaultValue(100)]
public int BufferSize { get; set; }
/// <summary>
/// Gets or sets the timeout (in milliseconds) after which the contents of buffer will be flushed
/// if there's no write in the specified period of time. Use -1 to disable timed flushes.
/// </summary>
/// <docgen category='Buffering Options' order='100' />
[DefaultValue(-1)]
public int FlushTimeout { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to use sliding timeout.
/// </summary>
/// <remarks>
/// This value determines how the inactivity period is determined. If sliding timeout is enabled,
/// the inactivity timer is reset after each write, if it is disabled - inactivity timer will
/// count from the first event written to the buffer.
/// </remarks>
/// <docgen category='Buffering Options' order='100' />
[DefaultValue(true)]
public bool SlidingTimeout { get; set; }
/// <summary>
/// Gets or sets the action to take if the buffer overflows.
/// </summary>
/// <remarks>
/// Setting to <see cref="BufferingTargetWrapperOverflowAction.Discard"/> will replace the
/// oldest event with new events without sending events down to the wrapped target, and
/// setting to <see cref="BufferingTargetWrapperOverflowAction.Flush"/> will flush the
/// entire buffer to the wrapped target.
/// </remarks>
/// <docgen category='Buffering Options' order='100' />
[DefaultValue("Flush")]
public BufferingTargetWrapperOverflowAction OverflowAction { get; set; }
/// <summary>
/// Flushes pending events in the buffer (if any), followed by flushing the WrappedTarget.
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
protected override void FlushAsync(AsyncContinuation asyncContinuation)
{
WriteEventsInBuffer("Flush Async");
base.FlushAsync(asyncContinuation);
}
/// <summary>
/// Initializes the target.
/// </summary>
protected override void InitializeTarget()
{
base.InitializeTarget();
_buffer = new LogEventInfoBuffer(BufferSize, false, 0);
InternalLogger.Trace("BufferingWrapper(Name={0}): Create Timer", Name);
_flushTimer = new Timer(FlushCallback, null, Timeout.Infinite, Timeout.Infinite);
}
/// <summary>
/// Closes the target by flushing pending events in the buffer (if any).
/// </summary>
protected override void CloseTarget()
{
var currentTimer = _flushTimer;
if (currentTimer != null)
{
_flushTimer = null;
if (currentTimer.WaitForDispose(TimeSpan.FromSeconds(1)))
{
if (OverflowAction == BufferingTargetWrapperOverflowAction.Discard)
{
_buffer.GetEventsAndClear();
}
else
{
WriteEventsInBuffer("Closing Target");
}
}
}
base.CloseTarget();
}
/// <summary>
/// Adds the specified log event to the buffer and flushes
/// the buffer in case the buffer gets full.
/// </summary>
/// <param name="logEvent">The log event.</param>
protected override void Write(AsyncLogEventInfo logEvent)
{
PrecalculateVolatileLayouts(logEvent.LogEvent);
int count = _buffer.Append(logEvent);
if (count >= BufferSize)
{
// If the OverflowAction action is set to "Discard", the buffer will automatically
// roll over the oldest item.
if (OverflowAction == BufferingTargetWrapperOverflowAction.Flush)
{
WriteEventsInBuffer("Exceeding BufferSize");
}
}
else
{
if (FlushTimeout > 0 && (SlidingTimeout || count == 1))
{
// reset the timer on first item added to the buffer or whenever SlidingTimeout is set to true
_flushTimer.Change(FlushTimeout, -1);
}
}
}
private void FlushCallback(object state)
{
bool lockTaken = false;
try
{
int timeoutMilliseconds = Math.Min(FlushTimeout / 2, 100);
lockTaken = Monitor.TryEnter(_lockObject, timeoutMilliseconds);
if (lockTaken)
{
if (_flushTimer == null)
return;
WriteEventsInBuffer(null);
}
else
{
if (_buffer.Count > 0)
_flushTimer?.Change(FlushTimeout, -1); // Schedule new retry timer
}
}
catch (Exception exception)
{
InternalLogger.Error(exception, "BufferingWrapper(Name={0}): Error in flush procedure.", Name);
if (exception.MustBeRethrownImmediately())
{
throw; // Throwing exceptions here will crash the entire application (.NET 2.0 behavior)
}
}
finally
{
if (lockTaken)
{
Monitor.Exit(_lockObject);
}
}
}
private void WriteEventsInBuffer(string reason)
{
if (WrappedTarget == null)
{
InternalLogger.Error("BufferingWrapper(Name={0}): WrappedTarget is NULL", Name);
return;
}
lock (_lockObject)
{
AsyncLogEventInfo[] logEvents = _buffer.GetEventsAndClear();
if (logEvents.Length > 0)
{
if (reason != null)
InternalLogger.Trace("BufferingWrapper(Name={0}): Writing {1} events ({2})", Name, logEvents.Length, reason);
WrappedTarget.WriteAsyncLogEvents(logEvents);
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using MeasurePortal.Models;
using MeasurePortal.Models.ManageViewModels;
using MeasurePortal.Services;
namespace MeasurePortal.Controllers
{
[Authorize]
public class ManageController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly IEmailSender _emailSender;
private readonly ISmsSender _smsSender;
private readonly ILogger _logger;
public ManageController(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
IEmailSender emailSender,
ISmsSender smsSender,
ILoggerFactory loggerFactory)
{
_userManager = userManager;
_signInManager = signInManager;
_emailSender = emailSender;
_smsSender = smsSender;
_logger = loggerFactory.CreateLogger<ManageController>();
}
//
// GET: /Manage/Index
[HttpGet]
public async Task<IActionResult> Index(ManageMessageId? message = null)
{
ViewData["StatusMessage"] =
message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
: message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
: message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set."
: message == ManageMessageId.Error ? "An error has occurred."
: message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added."
: message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed."
: "";
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var model = new IndexViewModel
{
HasPassword = await _userManager.HasPasswordAsync(user),
PhoneNumber = await _userManager.GetPhoneNumberAsync(user),
TwoFactor = await _userManager.GetTwoFactorEnabledAsync(user),
Logins = await _userManager.GetLoginsAsync(user),
BrowserRemembered = await _signInManager.IsTwoFactorClientRememberedAsync(user)
};
return View(model);
}
//
// POST: /Manage/RemoveLogin
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> RemoveLogin(RemoveLoginViewModel account)
{
ManageMessageId? message = ManageMessageId.Error;
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.RemoveLoginAsync(user, account.LoginProvider, account.ProviderKey);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
message = ManageMessageId.RemoveLoginSuccess;
}
}
return RedirectToAction(nameof(ManageLogins), new { Message = message });
}
//
// GET: /Manage/AddPhoneNumber
public IActionResult AddPhoneNumber()
{
return View();
}
//
// POST: /Manage/AddPhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> AddPhoneNumber(AddPhoneNumberViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// Generate the token and send it
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var code = await _userManager.GenerateChangePhoneNumberTokenAsync(user, model.PhoneNumber);
await _smsSender.SendSmsAsync(model.PhoneNumber, "Your security code is: " + code);
return RedirectToAction(nameof(VerifyPhoneNumber), new { PhoneNumber = model.PhoneNumber });
}
//
// POST: /Manage/EnableTwoFactorAuthentication
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> EnableTwoFactorAuthentication()
{
var user = await GetCurrentUserAsync();
if (user != null)
{
await _userManager.SetTwoFactorEnabledAsync(user, true);
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(1, "User enabled two-factor authentication.");
}
return RedirectToAction(nameof(Index), "Manage");
}
//
// POST: /Manage/DisableTwoFactorAuthentication
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DisableTwoFactorAuthentication()
{
var user = await GetCurrentUserAsync();
if (user != null)
{
await _userManager.SetTwoFactorEnabledAsync(user, false);
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(2, "User disabled two-factor authentication.");
}
return RedirectToAction(nameof(Index), "Manage");
}
//
// GET: /Manage/VerifyPhoneNumber
[HttpGet]
public async Task<IActionResult> VerifyPhoneNumber(string phoneNumber)
{
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var code = await _userManager.GenerateChangePhoneNumberTokenAsync(user, phoneNumber);
// Send an SMS to verify the phone number
return phoneNumber == null ? View("Error") : View(new VerifyPhoneNumberViewModel { PhoneNumber = phoneNumber });
}
//
// POST: /Manage/VerifyPhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> VerifyPhoneNumber(VerifyPhoneNumberViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.ChangePhoneNumberAsync(user, model.PhoneNumber, model.Code);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.AddPhoneSuccess });
}
}
// If we got this far, something failed, redisplay the form
ModelState.AddModelError(string.Empty, "Failed to verify phone number");
return View(model);
}
//
// POST: /Manage/RemovePhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> RemovePhoneNumber()
{
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.SetPhoneNumberAsync(user, null);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.RemovePhoneSuccess });
}
}
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error });
}
//
// GET: /Manage/ChangePassword
[HttpGet]
public IActionResult ChangePassword()
{
return View();
}
//
// POST: /Manage/ChangePassword
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ChangePassword(ChangePasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(3, "User changed their password successfully.");
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.ChangePasswordSuccess });
}
AddErrors(result);
return View(model);
}
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error });
}
//
// GET: /Manage/SetPassword
[HttpGet]
public IActionResult SetPassword()
{
return View();
}
//
// POST: /Manage/SetPassword
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SetPassword(SetPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.AddPasswordAsync(user, model.NewPassword);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.SetPasswordSuccess });
}
AddErrors(result);
return View(model);
}
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error });
}
//GET: /Manage/ManageLogins
[HttpGet]
public async Task<IActionResult> ManageLogins(ManageMessageId? message = null)
{
ViewData["StatusMessage"] =
message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
: message == ManageMessageId.AddLoginSuccess ? "The external login was added."
: message == ManageMessageId.Error ? "An error has occurred."
: "";
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var userLogins = await _userManager.GetLoginsAsync(user);
var otherLogins = _signInManager.GetExternalAuthenticationSchemes().Where(auth => userLogins.All(ul => auth.AuthenticationScheme != ul.LoginProvider)).ToList();
ViewData["ShowRemoveButton"] = user.PasswordHash != null || userLogins.Count > 1;
return View(new ManageLoginsViewModel
{
CurrentLogins = userLogins,
OtherLogins = otherLogins
});
}
//
// POST: /Manage/LinkLogin
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult LinkLogin(string provider)
{
// Request a redirect to the external login provider to link a login for the current user
var redirectUrl = Url.Action("LinkLoginCallback", "Manage");
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl, _userManager.GetUserId(User));
return Challenge(properties, provider);
}
//
// GET: /Manage/LinkLoginCallback
[HttpGet]
public async Task<ActionResult> LinkLoginCallback()
{
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var info = await _signInManager.GetExternalLoginInfoAsync(await _userManager.GetUserIdAsync(user));
if (info == null)
{
return RedirectToAction(nameof(ManageLogins), new { Message = ManageMessageId.Error });
}
var result = await _userManager.AddLoginAsync(user, info);
var message = result.Succeeded ? ManageMessageId.AddLoginSuccess : ManageMessageId.Error;
return RedirectToAction(nameof(ManageLogins), new { Message = message });
}
#region Helpers
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
public enum ManageMessageId
{
AddPhoneSuccess,
AddLoginSuccess,
ChangePasswordSuccess,
SetTwoFactorSuccess,
SetPasswordSuccess,
RemoveLoginSuccess,
RemovePhoneSuccess,
Error
}
private Task<ApplicationUser> GetCurrentUserAsync()
{
return _userManager.GetUserAsync(HttpContext.User);
}
#endregion
}
}
| |
#region Apache License, Version 2.0
//
// 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
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using log4net;
using NPanday.Model.Pom;
namespace NPanday.Utils
{
public class PomHelperUtility
{
private static readonly ILog log = LogManager.GetLogger(typeof(PomHelperUtility));
private FileInfo pom;
public bool isWebRefEmpty = false;
RspUtility rspUtil = new RspUtility();
public PomHelperUtility(FileInfo solutionFile, FileInfo projectFile)
{
FileInfo pomFile = PomHelperUtility.FindPomFileUntil(
projectFile.Directory,
solutionFile.Directory);
this.pom = pomFile;
}
public PomHelperUtility(string pom)
{
this.pom = new FileInfo(pom);
}
public PomHelperUtility(FileInfo pom)
{
this.pom = pom;
}
public DirectoryInfo SourceDirectory
{
get
{
string src = GetPomXPathExprValue(@"//pom:project/pom:build/pom:sourceDirectory");
return GetBuildSrcDir(src, false);
}
}
public string ArtifactId
{
get
{
return GetPomXPathExprValue(@"//pom:project/pom:artifactId");
}
}
public string GroupId
{
get
{
return GetPomXPathExprValue(@"//pom:project/pom:groupId");
}
}
public string Version
{
get
{
return GetPomXPathExprValue(@"//pom:project/pom:version");
}
}
public string Packaging
{
get
{
return GetPomXPathExprValue(@"//pom:project/pom:packaging");
}
}
public bool HasPlugin(string pluginGroupId, string pluginArtifactId)
{
NPanday.Model.Pom.Model model = ReadPomAsModel();
return FindPlugin(model, pluginGroupId, pluginArtifactId) != null;
}
public static Plugin FindPlugin(NPanday.Model.Pom.Model model, string groupId, string artifactId)
{
if (model.build.plugins == null)
{
return null;
}
foreach (Plugin plugin in model.build.plugins)
{
if (groupId.ToLower().Equals(plugin.groupId.ToLower(), StringComparison.InvariantCultureIgnoreCase) && artifactId.ToLower().Equals(plugin.artifactId.ToLower(), StringComparison.InvariantCultureIgnoreCase))
{
return plugin;
}
}
return null;
}
public void AddPlugin(string groupId, string artifactId, string version, bool extensions, PluginConfiguration pluginConf, string pluginGoal)
{
NPanday.Model.Pom.Model model = ReadPomAsModel();
List<NPanday.Model.Pom.Plugin> plugins = new List<NPanday.Model.Pom.Plugin>();
if (model.build.plugins != null)
{
plugins.AddRange(model.build.plugins);
}
// Add NPanday compile plugin
NPanday.Model.Pom.Plugin plugin = new NPanday.Model.Pom.Plugin();
plugin.groupId = groupId;
plugin.artifactId = artifactId;
plugin.version = version;
plugin.extensions = extensions;
if (pluginConf != null)
{
plugin.configuration = pluginConf;
}
if (null != pluginGoal || !String.Empty.Equals(pluginGoal))
{
addPluginExecution(plugin, pluginGoal, null);
}
plugins.Add(plugin);
model.build.plugins = plugins.ToArray();
WriteModelToPom(model);
}
public void AddPlugin(string groupId, string artifactId, string version, bool extensions, PluginConfiguration pluginConf)
{
AddPlugin(groupId, artifactId, version, extensions, pluginConf, null);
}
public DirectoryInfo TestSourceDirectory
{
get
{
string src = GetPomXPathExprValue(@"//pom:project/pom:build/pom:testSourceDirectory");
return GetBuildSrcDir(src, true);
}
}
private DirectoryInfo GetBuildSrcDir(string src, bool testSource)
{
string[] defTestSources = { "src/test/csharp", "src/test/vb" };
string[] defSrcSources = { "src/main/csharp", "src/main/vb" };
string[] defaultDirs = testSource ? defTestSources : defSrcSources;
if (string.IsNullOrEmpty(src) && "csharp".Equals(NPandayCompilerPluginLanguage, StringComparison.OrdinalIgnoreCase))
{
src = defaultDirs[0];
}
if (string.IsNullOrEmpty(src) && "vb".Equals(NPandayCompilerPluginLanguage, StringComparison.OrdinalIgnoreCase))
{
src = defaultDirs[1];
}
// check for default folders
if (string.IsNullOrEmpty(src))
{
foreach (string defDir in defaultDirs)
{
DirectoryInfo d = new DirectoryInfo(pom.Directory.FullName + @"\" + defDir);
if (d.Exists)
{
src = defDir;
break;
}
}
}
// set the default: where language is c#,
// if incase language is not found
if (string.IsNullOrEmpty(src))
{
src = defaultDirs[0];
}
// if relative path, concatinate the folder of the pom
if (IsRelativePath(src))
{
src = pom.Directory.FullName + @"\" + src;
}
return new DirectoryInfo(new DirectoryInfo(src).FullName);
}
public string NPandayCompilerPluginLanguage
{
get
{
string lang = GetNPandayCompilerPluginConfigurationValue("language");
if (string.IsNullOrEmpty(lang))
{
return null;
}
else if ("vb".Equals(lang, StringComparison.OrdinalIgnoreCase))
{
return "vb";
}
else if ("csharp".Equals(lang, StringComparison.OrdinalIgnoreCase)
|| "cs".Equals(lang, StringComparison.OrdinalIgnoreCase)
|| "c#".Equals(lang, StringComparison.OrdinalIgnoreCase))
{
return "csharp";
}
return lang;
}
}
public string CompilerPluginConfigurationKeyfile
{
get
{
string key = GetNPandayCompilerPluginConfigurationValue("keyfile");
if (IsRelativePath(key))
{
return NormalizeFileToWindowsStyle(new FileInfo(pom.Directory.FullName + @"\" + key).FullName);
}
return key;
}
set
{
if (string.IsNullOrEmpty(value))
{
SetNPandayCompilerPluginConfigurationValue("keyfile", null);
return;
}
string str = "";
if (IsRelativePath(value))
{
FileInfo f = new FileInfo(pom.Directory + @"\" + value);
str = GetRelativePathFromPom(f);
}
else
{
FileInfo f = new FileInfo(value);
str = GetRelativePathFromPom(f);
}
SetNPandayCompilerPluginConfigurationValue("keyfile", str);
}
}
public string GetNPandayCompilerPluginConfigurationValue(string config)
{
return GetPomXPathExprValue(@"//pom:project/pom:build/pom:plugins[./pom:plugin/pom:groupId = 'org.apache.npanday.plugins' and ./pom:plugin/pom:artifactId = 'maven-compile-plugin'][1]/pom:plugin/pom:configuration/pom:" + config);
}
private string PomNamespaceURI
{
get
{
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(pom.FullName);
return xmlDocument.DocumentElement.NamespaceURI;
}
}
public NPanday.Model.Pom.Model ReadPomAsModel()
{
return PomHelperUtility.ReadPomAsModel(this.pom);
}
public static NPanday.Model.Pom.Model ReadPomAsModel(FileInfo pomfile)
{
if (!pomfile.Exists)
{
throw new Exception("Pom file not found: " + pomfile.FullName);
}
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(pomfile.FullName);
String namespaceUri = xmlDocument.DocumentElement.NamespaceURI;
if (string.IsNullOrEmpty(namespaceUri))
{
xmlDocument.DocumentElement.SetAttribute("xmlns", "http://maven.apache.org/POM/4.0.0");
xmlDocument.Save(pomfile.FullName);
}
XmlTextReader reader = null;
NPanday.Model.Pom.Model model = null;
try
{
reader = new XmlTextReader(pomfile.FullName);
reader.WhitespaceHandling = WhitespaceHandling.Significant;
reader.Normalization = true;
reader.XmlResolver = null;
XmlSerializer serializer = new XmlSerializer(typeof(NPanday.Model.Pom.Model));
if (!serializer.CanDeserialize(reader))
{
throw new Exception(string.Format("Pom File ({0}) Reading Error, Pom File might contain invalid or malformed data", pomfile.FullName));
}
model = (NPanday.Model.Pom.Model)serializer.Deserialize(reader);
}
catch
{
throw;
}
finally
{
try
{
if (reader != null)
{
reader.Close();
((IDisposable)reader).Dispose();
}
}
catch
{
log.Warn("Failed to close stream reader after accessing pom.xml.");
}
}
return model;
}
public void WriteModelToPom(NPanday.Model.Pom.Model model)
{
PomHelperUtility.WriteModelToPom(this.pom, model);
}
public bool IsWebReferenceEmpty()
{
string[] directories;
if (Directory.Exists(pom.DirectoryName + "/Web References"))
directories = Directory.GetDirectories(pom.DirectoryName + "/Web References");
else
directories = Directory.GetDirectories(pom.DirectoryName + "/App_WebReferences");
bool isEmpty = false;
if (directories.Length == 0)
{
isEmpty = true;
}
return isEmpty;
}
public void DeletePlugin(Plugin plugin)
{
NPanday.Model.Pom.Model model = ReadPomAsModel();
List<NPanday.Model.Pom.Plugin> plugins = new List<NPanday.Model.Pom.Plugin>();
if (model.build.plugins != null)
{
foreach (Plugin item in model.build.plugins)
{
if (!item.artifactId.Equals(plugin.artifactId))
{
plugins.Add(item);
}
}
}
model.build.plugins = plugins.ToArray();
WriteModelToPom(model);
}
public static void WriteModelToPom(FileInfo pomFile, NPanday.Model.Pom.Model model)
{
if (!pomFile.Directory.Exists)
{
pomFile.Directory.Create();
}
TextWriter writer = null;
XmlSerializer serializer = null;
try
{
writer = new StreamWriter(pomFile.FullName);
serializer = new XmlSerializer(typeof(NPanday.Model.Pom.Model));
serializer.Serialize(writer, model);
}
catch
{
throw;
}
finally
{
try
{
if (writer != null)
{
writer.Close();
writer.Dispose();
}
}
catch
{
log.Warn("Failed to close stream writer after writing to pom.xml.");
}
}
}
public void SetNPandayCompilerPluginConfigurationValue(string config, string value)
{
NPanday.Model.Pom.Model model = ReadPomAsModel();
if (model.build == null)
{
model.build = new NPanday.Model.Pom.Build();
}
NPanday.Model.Pom.Plugin compilePlugin = null;
List<NPanday.Model.Pom.Plugin> plugins = new List<NPanday.Model.Pom.Plugin>();
if (model.build.plugins != null)
{
foreach (NPanday.Model.Pom.Plugin plugin in model.build.plugins)
{
if ("org.apache.npanday.plugins".Equals(plugin.groupId)
&& "maven-compile-plugin".Equals(plugin.artifactId))
{
compilePlugin = plugin;
}
plugins.Add(plugin);
}
}
if (compilePlugin == null)
{
compilePlugin = new NPanday.Model.Pom.Plugin();
compilePlugin.groupId = "org.apache.npanday.plugins";
compilePlugin.artifactId = "maven-compile-plugin";
compilePlugin.extensions = true;
plugins.Add(compilePlugin);
}
XmlElement configElement = null;
List<XmlElement> elems = new List<XmlElement>();
if (compilePlugin.configuration != null && compilePlugin.configuration.Any != null)
{
foreach (XmlElement el in compilePlugin.configuration.Any)
{
if (config.Equals(el.Name))
{
configElement = el;
}
elems.Add(el);
}
}
else
{
compilePlugin.configuration = new NPanday.Model.Pom.PluginConfiguration();
}
if (configElement == null)
{
XmlDocument xmlDocument = new XmlDocument();
//configElement = xmlDocument.CreateElement(config, @"http://maven.apache.org/POM/4.0.0");
configElement = xmlDocument.CreateElement(config, PomNamespaceURI);
configElement.RemoveAll();
elems.Add(configElement);
}
configElement.InnerText = value;
if (string.IsNullOrEmpty(value))
{
elems.Remove(configElement);
}
compilePlugin.configuration.Any = elems.ToArray();
model.build.plugins = plugins.ToArray();
WriteModelToPom(model);
}
private bool IsRelativePath(string path)
{
if (string.IsNullOrEmpty(path))
{
return false;
}
// in windows full path contains : eg. c:\ or d:\
return !path.Contains(":");
}
// @"//pom:project/pom:build/pom:plugins[./pom:plugin/pom:groupId = 'org.apache.npanday.plugins' and ./pom:plugin/pom:artifactId = 'maven-compile-plugin'][1]/pom:plugin/pom:configuration/pom:keyfile"
public string GetPomXPathExprValue(string xpath_expr)
{
try
{
if (!pom.Exists)
{
throw new Exception("Pom file not found: File = " + pom.FullName);
}
String pomFileName = pom.FullName;
System.Xml.XmlDocument xmldoc = new System.Xml.XmlDocument();
xmldoc.Load(pomFileName);
System.Xml.XmlNamespaceManager xmlnsManager = new System.Xml.XmlNamespaceManager(xmldoc.NameTable);
//xmlnsManager.AddNamespace("pom", "http://maven.apache.org/POM/4.0.0");
xmlnsManager.AddNamespace("pom", PomNamespaceURI);
System.Xml.XmlNodeList valueList = xmldoc.SelectNodes(xpath_expr, xmlnsManager);
foreach (System.Xml.XmlNode val in valueList)
{
return (val.InnerText);
}
}
catch (Exception)
{
return null;
}
// try without the namespace if value is not found
if (!string.IsNullOrEmpty(xpath_expr) && xpath_expr.Contains("pom:"))
{
return GetPomXPathExprValue(xpath_expr.Replace("pom:", ""));
}
return null;
}
public string GetRelativePathFromPom(FileInfo file)
{
return PomHelperUtility.GetRelativePath(pom.Directory, file);
}
public string GetRelativePathFromPom(DirectoryInfo dir)
{
return PomHelperUtility.GetRelativePath(pom.Directory, dir);
}
public string GetRelativePathFromPom(string filename)
{
return PomHelperUtility.GetRelativePath(pom.Directory, new FileInfo(filename));
}
public bool IsPomDependency(NPanday.Model.Pom.Dependency dependency)
{
return IsPomDependency(dependency.groupId, dependency.artifactId, dependency.version);
}
public bool IsPomDependency(string artifactId)
{
return IsPomDependency(null, artifactId, null);
}
public bool IsPomDependency(string groupId, string artifactId)
{
return IsPomDependency(groupId, artifactId, null);
}
public bool IsPomDependency(string groupId, string artifactId, string version)
{
// consider groupId and version if not empty
if (!string.IsNullOrEmpty(groupId)
&& !string.IsNullOrEmpty(version))
{
return !string.IsNullOrEmpty
(
GetPomXPathExprValue(
string.Format("//pom:project/pom:dependencies/pom:dependency[./pom:artifactId = '{0}' and ./pom:groupId = '{1}' and ./pom:version = '{2}'][1]/pom:artifactId",
artifactId,
groupId,
version)
)
);
}
// consider groupId
else if (!string.IsNullOrEmpty(groupId))
{
return !string.IsNullOrEmpty
(
GetPomXPathExprValue(
string.Format("//pom:project/pom:dependencies/pom:dependency[./pom:artifactId = '{0}' and ./pom:groupId = '{1}'][1]/pom:artifactId",
artifactId,
groupId)
)
);
}
// consider version
else if (!string.IsNullOrEmpty(version))
{
return !string.IsNullOrEmpty
(
GetPomXPathExprValue(
string.Format("//pom:project/pom:dependencies/pom:dependency[./pom:artifactId = '{0}' and ./pom:version = '{1}'][1]/pom:artifactId",
artifactId,
version)
)
);
}
// just the artifact
else if (!string.IsNullOrEmpty(artifactId))
{
return !string.IsNullOrEmpty
(
GetPomXPathExprValue(
string.Format("//pom:project/pom:dependencies/pom:dependency[translate(./pom:artifactId, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') = '{0}'][1]/pom:artifactId",
artifactId.ToLower())
)
);
}
return false;
}
public void RemovePomDependency(NPanday.Model.Pom.Dependency dependency)
{
RemovePomDependency(dependency.groupId, dependency.artifactId, dependency.version);
}
public void RemovePomDependency(string artifactId)
{
RemovePomDependency(null, artifactId, null);
}
public void RemovePomDependency(string groupId, string artifactId)
{
RemovePomDependency(groupId, artifactId, null);
}
public void RemovePomDependency(string groupId, string artifactId, string version)
{
if (string.IsNullOrEmpty(artifactId))
{
throw new Exception("Pom Dependency Removal Error, artifactId paramter must not be null");
}
if (!IsPomDependency(groupId, artifactId, version))
{
throw new Exception(string.Format("Pom Doesnot have a dependency {0}:{1}:{2}", groupId, artifactId, version));
}
NPanday.Model.Pom.Model model = ReadPomAsModel();
List<Dependency> newDependencies = new List<Dependency>();
if (model.dependencies != null)
{
foreach (Dependency dependency in model.dependencies)
{
if (artifactId.ToLower().Equals(dependency.artifactId.ToLower(), StringComparison.InvariantCultureIgnoreCase))
{
// consider groupId and version if not empty
if (!string.IsNullOrEmpty(groupId)
&& !string.IsNullOrEmpty(version))
{
if (!(groupId.Equals(groupId) && version.Equals(version)))
{
newDependencies.Add(dependency);
}
}
// consider groupId
else if (!string.IsNullOrEmpty(groupId))
{
if (!groupId.Equals(groupId))
{
newDependencies.Add(dependency);
}
}
// consider version
else if (!string.IsNullOrEmpty(version))
{
if (!groupId.Equals(groupId))
{
newDependencies.Add(dependency);
}
}
}
else
{
newDependencies.Add(dependency);
}
}
model.dependencies = newDependencies.ToArray();
WriteModelToPom(model);
}
}
public void AddPomDependency(string groupId, string artifactId)
{
AddPomDependency(groupId, artifactId, null, "dotnet-library", null, null);
}
public void AddPomDependency(string groupId, string artifactId, string version)
{
AddPomDependency(groupId, artifactId, version, "dotnet-library", null, null);
}
public void AddPomDependency(string groupId, string artifactId, string version, string type, string scope, string systemPath)
{
NPanday.Model.Pom.Dependency dependency = new NPanday.Model.Pom.Dependency(); ;
dependency.artifactId = artifactId;
dependency.groupId = groupId;
dependency.version = version;
dependency.type = type;
dependency.scope = scope;
if (!string.IsNullOrEmpty(systemPath))
{
dependency.systemPath = new FileInfo(systemPath).FullName;
}
AddPomDependency(dependency);
}
public void AddPomDependency(NPanday.Model.Pom.Dependency dependency)
{
if ("vb".Equals(NPandayCompilerPluginLanguage))
{
if (rspUtil.IsVbcRspIncluded(dependency.artifactId))
return;
}
else
{
if (rspUtil.IsCscRspIncluded((dependency.artifactId)))
return;
}
if (IsPomDependency(dependency))
{
throw new Exception(string.Format(
"Error in Adding Artifact Dependency [groupId: {0}, artifactId:{1}, version:{2}], \nDependency already exists in the Pom dependencies",
dependency.groupId,
dependency.artifactId,
dependency.version));
}
NPanday.Model.Pom.Model model = ReadPomAsModel();
List<Dependency> dependencies = new List<Dependency>();
if (model.dependencies != null)
{
dependencies.AddRange(model.dependencies);
}
dependencies.Add(dependency);
model.dependencies = dependencies.ToArray();
WriteModelToPom(model);
}
public static FileInfo FindPomFileUntil(DirectoryInfo start, DirectoryInfo until)
{
if (start == null || until == null)
{
throw new NullReferenceException("Null Reference Exception: start and until parameter must not be null");
}
DirectoryInfo currentDir = start;
FileInfo pomFile = new FileInfo(currentDir + @"\pom.xml");
// check if both parent and current directory is in the same folder
if (!until.Root.FullName.Equals(start.Root.FullName, StringComparison.OrdinalIgnoreCase) || !until.Exists || !start.Exists)
{
// they are not in the same root directory or, until or start directory does not exists
throw new Exception(string.Format("Folders are not on the same drive: {0} is not in the same disk drive with {1}", until.FullName, start.FullName));
}
if (!start.FullName.StartsWith(until.FullName))
{
// start is not a sub Directory of until
throw new Exception(string.Format("Folder is not a subdirectory: {0} is not a subdirectory of {1}", start.FullName, until.FullName));
}
while (!until.FullName.Equals(currentDir.FullName, StringComparison.OrdinalIgnoreCase))
{
pomFile = new FileInfo(currentDir.FullName + @"\pom.xml");
if (pomFile.Exists)
{
return pomFile;
}
currentDir = currentDir.Parent;
}
pomFile = new FileInfo(currentDir.FullName + @"\pom.xml");
if (pomFile.Exists)
{
return pomFile;
}
throw new Exception(string.Format("Pom file not found: pom.xml not found from folder: {0} down to folder: {1}", start.FullName, until.FullName));
}
public static string GetRelativePath(DirectoryInfo baseDir, DirectoryInfo dir)
{
if (dir == null)
{
return null;
}
// if the file is not on the same root with the baseDir
// then return the file, its point less to get its relative path
// since they are not in the same root
if (baseDir == null || !baseDir.Root.FullName.Equals(dir.Root.FullName, StringComparison.OrdinalIgnoreCase))
{
return dir.ToString();
}
DirectoryInfo commonDir = GetCommonDirectory(baseDir, dir);
string relative = "";
string[] baseArr = RemoveCommonDirAndTokenize(commonDir, baseDir);
foreach (string b in baseArr)
{
relative += @"..\";
}
string[] fileArr = RemoveCommonDirAndTokenize(commonDir, dir);
foreach (string f in fileArr)
{
relative += f + @"\";
}
return NormalizeFileToWindowsStyle(relative);
}
public static string GetRelativePath(DirectoryInfo baseDir, FileInfo file)
{
return NormalizeFileToWindowsStyle(GetRelativePath(baseDir, file.Directory) + @"\" + file.Name);
}
public static DirectoryInfo GetCommonDirectory(DirectoryInfo dir1, DirectoryInfo dir2)
{
string strDir = "";
string[] arrDir1 = NormalizeFileToWindowsStyle(dir1).FullName.Split('\\');
string[] arrDir2 = NormalizeFileToWindowsStyle(dir2).FullName.Split('\\');
int len = (arrDir1.Length < arrDir2.Length ? arrDir1.Length : arrDir2.Length);
if (len == 0)
{
return dir1.Root;
}
for (int i = 0; i < len; i++)
{
if (!arrDir1[i].Equals(arrDir2[i], StringComparison.OrdinalIgnoreCase))
{
break;
}
strDir += arrDir1[i] + @"\";
}
return new DirectoryInfo(strDir);
}
private static string[] RemoveCommonDirAndTokenize(DirectoryInfo commonDir, FileInfo file)
{
string[] arrcommonDir = NormalizeFileToWindowsStyle(commonDir).FullName.Split('\\');
string[] arrdir = NormalizeFileToWindowsStyle(file).FullName.Split('\\');
string[] str = new string[arrdir.Length - arrcommonDir.Length];
for (int i = arrcommonDir.Length, j = 0; i < arrdir.Length; i++, j++)
{
str[j] = arrdir[i];
}
return str;
}
private static string[] RemoveCommonDirAndTokenize(DirectoryInfo commonDir, DirectoryInfo dir)
{
return RemoveCommonDirAndTokenize(commonDir, new FileInfo(dir.FullName));
}
public static string NormalizeFileToWindowsStyle(string fileName)
{
if (string.IsNullOrEmpty(fileName))
{
return fileName;
}
fileName = fileName.Replace('/', '\\');
// remove all instance of double slashes
while (fileName.Contains("\\\\"))
{
fileName = fileName.Replace("\\\\", "\\");
}
if (!fileName.EndsWith("..\\") && fileName.EndsWith("\\"))
{
fileName = fileName.Substring(0, fileName.Length - 1);
}
// remove slash \ if its on the first char
if (fileName.StartsWith("\\"))
{
fileName = fileName.Substring(1);
}
return fileName;
}
public static FileInfo NormalizeFileToWindowsStyle(FileInfo file)
{
return new FileInfo(NormalizeFileToWindowsStyle(file.ToString()));
}
public static DirectoryInfo NormalizeFileToWindowsStyle(DirectoryInfo dir)
{
return new DirectoryInfo(NormalizeFileToWindowsStyle(dir.ToString()));
}
#region AddWebReference
public void AddWebReference(string name, string path, string output)
{
NPanday.Model.Pom.Model model = ReadPomAsModel();
if (!isWebRefExistingInPom(path, model))
{
bool hasWSDLPlugin = false;
if (model != null && model.build != null && model.build.plugins != null)
{
foreach (Plugin plugin in model.build.plugins)
{
if (isWsdlPlugin(plugin))
{
hasWSDLPlugin = true;
addPluginExecution(plugin, "wsdl", null);
addWebConfiguration(plugin, "webreferences", name, path, output);
}
}
if (!hasWSDLPlugin)
{
Plugin webReferencePlugin = addPlugin(model,
"org.apache.npanday.plugins",
"maven-wsdl-plugin",
null,
false
);
addPluginExecution(webReferencePlugin, "wsdl", null);
addWebConfiguration(webReferencePlugin, "webreferences", name, path, output);
}
}
foreach (Plugin plugin in model.build.plugins)
{
if ("org.apache.npanday.plugins".Equals(plugin.groupId.ToLower(), StringComparison.InvariantCultureIgnoreCase)
&& "maven-compile-plugin".Equals(plugin.artifactId.ToLower(), StringComparison.InvariantCultureIgnoreCase))
{
if (plugin.configuration == null || plugin.configuration.Any == null)
{
break;
}
XmlElement[] elems = ((XmlElement[])plugin.configuration.Any);
for (int count = elems.Length; count-- > 0; )
{
if ("includeSources".Equals(elems[count].Name))
{
XmlDocument xmlDocument = new XmlDocument();
XmlElement elem = xmlDocument.CreateElement("includeSources", @"http://maven.apache.org/POM/4.0.0");
//LOOP THROUGH EXISTING AND ADD
//GET .CS FILE AND ADD
foreach (XmlNode n in elems[count].ChildNodes)
{
if ("includeSource".Equals(n.Name))
{
XmlNode node = xmlDocument.CreateNode(XmlNodeType.Element, n.Name, @"http://maven.apache.org/POM/4.0.0");
node.InnerText = n.InnerText.Replace("\\","/");
if ((!elem.InnerXml.Contains(node.InnerText)) && (!node.InnerText.Contains(".disco")))
{
elem.AppendChild(node);
}
}
}
DirectoryInfo fullPath = new FileInfo(Path.Combine(pom.Directory.FullName, path.Trim('\r', ' ', '\n'))).Directory;
foreach (FileInfo file in fullPath.GetFiles("*.cs"))
{
XmlNode node = xmlDocument.CreateNode(XmlNodeType.Element, "includeSource", @"http://maven.apache.org/POM/4.0.0");
node.InnerText = GetRelativePath(pom.Directory, file);
node.InnerText = node.InnerText.Replace("\\", "/");
if (!elem.InnerText.Contains(node.InnerText))
{
elem.AppendChild(node);
}
}
foreach (FileInfo file in fullPath.GetFiles("*.vb"))
{
XmlNode node = xmlDocument.CreateNode(XmlNodeType.Element, "includeSource", @"http://maven.apache.org/POM/4.0.0");
node.InnerText = GetRelativePath(pom.Directory, file);
node.InnerText = node.InnerText.Replace("\\", "/");
if (!elem.InnerText.Contains(node.InnerText))
{
elem.AppendChild(node);
}
}
elems[count] = elem;
break;
}
}
}
}
WriteModelToPom(model);
}
}
Plugin addPlugin(NPanday.Model.Pom.Model model, string groupId, string artifactId, string version, bool extensions)
{
List<NPanday.Model.Pom.Plugin> plugins = new List<NPanday.Model.Pom.Plugin>();
if (model.build.plugins != null)
{
plugins.AddRange(model.build.plugins);
}
// Add NPanday compile plugin
NPanday.Model.Pom.Plugin plugin = new NPanday.Model.Pom.Plugin();
plugin.groupId = groupId;
plugin.artifactId = artifactId;
plugin.version = version;
plugin.extensions = extensions;
plugins.Add(plugin);
model.build.plugins = plugins.ToArray();
return plugin;
}
public void AddMavenCompilePluginConfiguration(string pluginGroupId, string pluginArtifactId, string confPropCollection, string confProp, string confPropVal)
{
NPanday.Model.Pom.Model model = ReadPomAsModel();
bool configExists = false;
foreach (Plugin plugin in model.build.plugins)
{
XmlDocument xmlDocument = new XmlDocument();
if (pluginGroupId.Equals(plugin.groupId.ToLower(), StringComparison.InvariantCultureIgnoreCase)
&& pluginArtifactId.Equals(plugin.artifactId.ToLower(), StringComparison.InvariantCultureIgnoreCase))
{
if (plugin.configuration == null && plugin.configuration.Any == null)
{
return;
}
XmlElement[] elems = ((XmlElement[])plugin.configuration.Any);
for (int count = elems.Length; count-- > 0; )
{
if (confPropCollection.Equals(elems[count].Name))
{
XmlElement elem = xmlDocument.CreateElement(confPropCollection, @"http://maven.apache.org/POM/4.0.0");
//Loop throught existing item and
//append everything including the newly added item
foreach (XmlNode n in elems[count].ChildNodes)
{
if (confProp.Equals(n.Name))
{
XmlNode node = xmlDocument.CreateNode(XmlNodeType.Element, n.Name, @"http://maven.apache.org/POM/4.0.0");
node.InnerText = n.InnerText.Replace("\\", "/");
elem.AppendChild(node);
if (n.InnerText.Equals(confPropVal))
{
configExists = true;
}
}
}
if (!configExists)
{
XmlNode nodeAdded = xmlDocument.CreateNode(XmlNodeType.Element, confProp, @"http://maven.apache.org/POM/4.0.0");
nodeAdded.InnerText = confPropVal.Replace("\\", "/");
elem.AppendChild(nodeAdded);
elems[count] = elem;
}
break;
}
}
}
}
WriteModelToPom(model);
}
public void RenameMavenCompilePluginConfiguration(string pluginGroupId, string pluginArtifactId, string confPropCollection, string confProp, string confPropVal, string newPropVal)
{
NPanday.Model.Pom.Model model = ReadPomAsModel();
foreach (Plugin plugin in model.build.plugins)
{
XmlDocument xmlDocument = new XmlDocument();
if (pluginGroupId.Equals(plugin.groupId.ToLower(), StringComparison.InvariantCultureIgnoreCase)
&& pluginArtifactId.Equals(plugin.artifactId.ToLower(), StringComparison.InvariantCultureIgnoreCase))
{
if (plugin.configuration == null && plugin.configuration.Any == null)
{
return;
}
XmlElement[] elems = ((XmlElement[])plugin.configuration.Any);
for (int count = elems.Length; count-- > 0; )
{
if (confPropCollection.Equals(elems[count].Name))
{
XmlElement elem = xmlDocument.CreateElement(confPropCollection, @"http://maven.apache.org/POM/4.0.0");
//Loop throught existing item and
//append everything except for the item to change
//check for the item and change it
foreach (XmlNode n in elems[count].ChildNodes)
{
if (confProp.Equals(n.Name))
{
XmlNode node = xmlDocument.CreateNode(XmlNodeType.Element, n.Name, @"http://maven.apache.org/POM/4.0.0");
if (n.InnerText.Equals(confPropVal))
{
node.InnerText = newPropVal;
}
else
{
node.InnerText = n.InnerText;
}
elem.AppendChild(node);
}
}
elems[count] = elem;
break;
}
}
}
}
WriteModelToPom(model);
}
public void RemoveMavenCompilePluginConfiguration(string pluginGroupId, string pluginArtifactId, string confPropCollection, string confProp, string confPropVal)
{
NPanday.Model.Pom.Model model = ReadPomAsModel();
foreach (Plugin plugin in model.build.plugins)
{
XmlDocument xmlDocument = new XmlDocument();
if (pluginGroupId.Equals(plugin.groupId.ToLower(), StringComparison.InvariantCultureIgnoreCase)
&& pluginArtifactId.Equals(plugin.artifactId.ToLower(), StringComparison.InvariantCultureIgnoreCase))
{
if (plugin.configuration == null && plugin.configuration.Any == null)
{
return;
}
XmlElement[] elems = ((XmlElement[])plugin.configuration.Any);
for (int count = elems.Length; count-- > 0; )
{
if (confPropCollection.Equals(elems[count].Name))
{
XmlElement elem = xmlDocument.CreateElement(confPropCollection, @"http://maven.apache.org/POM/4.0.0");
//Loop throught existing item and
//append everything except for the item to change
//check for the item and change it
foreach (XmlNode n in elems[count].ChildNodes)
{
if (confProp.Equals(n.Name))
{
XmlNode node = xmlDocument.CreateNode(XmlNodeType.Element, n.Name, @"http://maven.apache.org/POM/4.0.0");
if (!n.InnerText.Equals(confPropVal))
{
node.InnerText = n.InnerText;
elem.AppendChild(node);
}
}
}
elems[count] = elem;
break;
}
}
}
}
WriteModelToPom(model);
}
public void AddMavenResxPluginConfiguration(string pluginGroupId, string pluginArtifactId, string confPropCollection, string confProp, string sourceFile, string resxName)
{
NPanday.Model.Pom.Model model = ReadPomAsModel();
foreach (Plugin plugin in model.build.plugins)
{
XmlDocument xmlDocument = new XmlDocument();
if (pluginGroupId.Equals(plugin.groupId.ToLower(), StringComparison.InvariantCultureIgnoreCase)
&& pluginArtifactId.Equals(plugin.artifactId.ToLower(), StringComparison.InvariantCultureIgnoreCase))
{
if (plugin.configuration == null && plugin.configuration.Any == null)
{
return;
}
XmlElement[] elems = ((XmlElement[])plugin.configuration.Any);
for (int count = elems.Length; count-- > 0; )//(XmlElement elem in ((XmlElement[])plugin.configuration.Any))
{
if (confPropCollection.Equals(elems[count].Name))
{
XmlElement elem = xmlDocument.CreateElement(confPropCollection, @"http://maven.apache.org/POM/4.0.0");
//Loop throught existing item and
//append everything including the newly added item
foreach (XmlNode n in elems[count].ChildNodes)
{
if (confProp.Equals(n.Name))
{
XmlNode node = xmlDocument.CreateNode(XmlNodeType.Element, n.Name, @"http://maven.apache.org/POM/4.0.0");
XmlNodeList nList = n.ChildNodes;
foreach (XmlNode nChild in nList)
{
XmlNode innerChild = xmlDocument.CreateNode(XmlNodeType.Element, nChild.Name, @"http://maven.apache.org/POM/4.0.0");
innerChild.InnerText = nChild.InnerText;
node.AppendChild(innerChild);
}
elem.AppendChild(node);
}
}
XmlNode confPropNode = xmlDocument.CreateNode(XmlNodeType.Element, confProp, @"http://maven.apache.org/POM/4.0.0");
XmlNode nodeSourceFile = xmlDocument.CreateNode(XmlNodeType.Element, "sourceFile", @"http://maven.apache.org/POM/4.0.0");
XmlNode nodeResxName = xmlDocument.CreateNode(XmlNodeType.Element, "name", @"http://maven.apache.org/POM/4.0.0");
nodeSourceFile.InnerText = sourceFile;
nodeResxName.InnerText = resxName;
confPropNode.AppendChild(nodeSourceFile);
confPropNode.AppendChild(nodeResxName);
elem.AppendChild(confPropNode);
elems[count] = elem;
break;
}
}
}
}
WriteModelToPom(model);
}
public void RenameMavenResxPluginConfiguration(string pluginGroupId, string pluginArtifactId, string confPropCollection, string confProp, string sourceFile, string resxName, string newSourceFile, string newResxName)
{
NPanday.Model.Pom.Model model = ReadPomAsModel();
foreach (Plugin plugin in model.build.plugins)
{
XmlDocument xmlDocument = new XmlDocument();
if (pluginGroupId.Equals(plugin.groupId.ToLower(), StringComparison.InvariantCultureIgnoreCase)
&& pluginArtifactId.Equals(plugin.artifactId.ToLower(), StringComparison.InvariantCultureIgnoreCase))
{
if (plugin.configuration == null && plugin.configuration.Any == null)
{
return;
}
XmlElement[] elems = ((XmlElement[])plugin.configuration.Any);
for (int count = elems.Length; count-- > 0; )//(XmlElement elem in ((XmlElement[])plugin.configuration.Any))
{
if (confPropCollection.Equals(elems[count].Name))
{
XmlElement elem = xmlDocument.CreateElement(confPropCollection, @"http://maven.apache.org/POM/4.0.0");
//Loop throught existing item and
//append everything including the newly added item
foreach (XmlNode n in elems[count].ChildNodes)
{
if (confProp.Equals(n.Name))
{
XmlNode node = xmlDocument.CreateNode(XmlNodeType.Element, n.Name, @"http://maven.apache.org/POM/4.0.0");
XmlNodeList nList = n.ChildNodes;
foreach (XmlNode nChild in nList)
{
XmlNode innerChild = xmlDocument.CreateNode(XmlNodeType.Element, nChild.Name, @"http://maven.apache.org/POM/4.0.0");
if (nChild.InnerText.Equals(sourceFile) && nChild.Name.Equals("sourceFile"))
{
innerChild.InnerText = newSourceFile;
}
else if (nChild.InnerText.Equals(resxName) && nChild.Name.Equals("name"))
{
innerChild.InnerText = newResxName;
}
else
{
innerChild.InnerText = nChild.InnerText;
}
node.AppendChild(innerChild);
}
elem.AppendChild(node);
}
}
elems[count] = elem;
break;
}
}
}
}
WriteModelToPom(model);
}
public void RemoveMavenResxPluginConfiguration(string pluginGroupId, string pluginArtifactId, string confPropCollection, string confProp, string sourceFile, string resxName)
{
NPanday.Model.Pom.Model model = ReadPomAsModel();
foreach (Plugin plugin in model.build.plugins)
{
XmlDocument xmlDocument = new XmlDocument();
if (pluginGroupId.Equals(plugin.groupId.ToLower(), StringComparison.InvariantCultureIgnoreCase)
&& pluginArtifactId.Equals(plugin.artifactId.ToLower(), StringComparison.InvariantCultureIgnoreCase))
{
if (plugin.configuration == null && plugin.configuration.Any == null)
{
return;
}
XmlElement[] elems = ((XmlElement[])plugin.configuration.Any);
for (int count = elems.Length; count-- > 0; )//(XmlElement elem in ((XmlElement[])plugin.configuration.Any))
{
if (confPropCollection.Equals(elems[count].Name))
{
XmlElement elem = xmlDocument.CreateElement(confPropCollection, @"http://maven.apache.org/POM/4.0.0");
//Loop throught existing item and
//append everything including the newly added item
foreach (XmlNode n in elems[count].ChildNodes)
{
if (confProp.Equals(n.Name))
{
XmlNode node = xmlDocument.CreateNode(XmlNodeType.Element, n.Name, @"http://maven.apache.org/POM/4.0.0");
XmlNodeList nList = n.ChildNodes;
foreach (XmlNode nChild in nList)
{
XmlNode innerChild = xmlDocument.CreateNode(XmlNodeType.Element, nChild.Name, @"http://maven.apache.org/POM/4.0.0");
if (nChild.Name.Equals("sourceFile"))
{
if (!nChild.InnerText.Equals(sourceFile))
{
innerChild.InnerText = nChild.InnerText;
node.AppendChild(innerChild);
}
}
if (nChild.Name.Equals("name"))
{
if (!nChild.InnerText.Equals(resxName))
{
innerChild.InnerText = nChild.InnerText;
node.AppendChild(innerChild);
}
}
}
if (node.HasChildNodes)
{
elem.AppendChild(node);
}
}
}
elems[count] = elem;
break;
}
}
}
}
WriteModelToPom(model);
}
void addPluginExecution(Plugin plugin, string goal, string phase)
{
if (string.IsNullOrEmpty(goal))
{
// there is nothing to write
return;
}
if (!isExistingPluginExecution(plugin, goal))
{
List<PluginExecution> list = new List<PluginExecution>();
if (plugin.executions == null)
{
plugin.executions = new List<PluginExecution>().ToArray();
list.AddRange(plugin.executions);
}
else
{
list.AddRange(plugin.executions);
}
PluginExecution exe = new PluginExecution();
exe.goals = new string[] { goal };
list.Add(exe);
plugin.executions = list.ToArray();
}
}
bool isExistingPluginExecution(Plugin plugin, string goal)
{
if (plugin.executions == null)
return false;
foreach (PluginExecution execution in plugin.executions)
{
foreach (string existingGoal in execution.goals)
{
if (existingGoal.Equals(goal))
return true;
}
}
return false;
}
bool isWsdlPlugin(Plugin plugin)
{
return (!string.IsNullOrEmpty(plugin.groupId) &&
!string.IsNullOrEmpty(plugin.artifactId) &&
plugin.groupId.Equals("org.apache.npanday.plugins") &&
plugin.artifactId.Equals("maven-wsdl-plugin"));
}
void addWebConfiguration(Plugin plugin, string parentTag, string name, string path, string output)
{
if (string.IsNullOrEmpty(parentTag))
{
// there is nothing to write
return;
}
if (string.IsNullOrEmpty(name))
{
// there is nothing to write
return;
}
if (string.IsNullOrEmpty(path))
{
// there is nothing to write
return;
}
if (string.IsNullOrEmpty(output))
{
int endIndex = path.LastIndexOf('\\');
if (endIndex < 0)
{
output = path;
}
else
{
output = path.Substring(0, endIndex);
}
}
if (plugin.configuration == null)
{
plugin.configuration = new PluginConfiguration();
}
List<XmlElement> elems = new List<XmlElement>();
if (plugin.configuration.Any != null)
{
elems.AddRange(plugin.configuration.Any);
}
XmlElement elem = getWebReferencesElement(elems.ToArray(), "webreferences");
XmlDocument xmlDocument = new XmlDocument();
XmlNode node = xmlDocument.CreateNode(XmlNodeType.Element, "webreference", @"http://maven.apache.org/POM/4.0.0");
XmlNode nodeName = xmlDocument.CreateNode(XmlNodeType.Element, "namespace", @"http://maven.apache.org/POM/4.0.0");
XmlNode nodePath = xmlDocument.CreateNode(XmlNodeType.Element, "path", @"http://maven.apache.org/POM/4.0.0");
XmlNode nodeOutput = xmlDocument.CreateNode(XmlNodeType.Element, "output", @"http://maven.apache.org/POM/4.0.0");
nodeName.InnerText = name;
nodePath.InnerText = path != null ? path.Replace("\\", "/") : path;
nodeOutput.InnerText = output != null ? output.Replace("\\", "/") : output;
node.AppendChild(nodeName);
node.AppendChild(nodePath);
node.AppendChild(nodeOutput);
if (elem == null)
{
elem = xmlDocument.CreateElement(parentTag, @"http://maven.apache.org/POM/4.0.0");
elem.AppendChild(node);
elems.Add(elem);
}
else
{
elem.AppendChild(elem.OwnerDocument.ImportNode(node, true));
}
plugin.configuration.Any = elems.ToArray();
}
XmlElement getWebReferencesElement(XmlElement[] elems, string elementName)
{
foreach (XmlElement elem in elems)
{
if (!string.IsNullOrEmpty(elem.Name) && elem.Name.ToLower().Equals(elementName.ToLower(), StringComparison.InvariantCultureIgnoreCase))
return elem;
}
return null;
}
#endregion
#region RemoveWebReference
public void RemoveWebReference(string path, string name)
{
NPanday.Model.Pom.Model model = ReadPomAsModel();
if (model != null && model.build != null && model.build.plugins != null)
{
foreach (Plugin plugin in model.build.plugins)
{
if (isWsdlPlugin(plugin))
{
removeWebConfiguration(plugin, name);
if (!isWebRefEmpty)
{
WriteModelToPom(model);
}
}
if ("org.apache.npanday.plugins".Equals(plugin.groupId.ToLower(), StringComparison.InvariantCultureIgnoreCase)
&& "maven-compile-plugin".Equals(plugin.artifactId.ToLower(), StringComparison.InvariantCultureIgnoreCase))
{
XmlElement[] elems = ((XmlElement[])plugin.configuration.Any);
for (int count = elems.Length; count-- > 0; )
{
if ("includeSources".Equals(elems[count].Name))
{
XmlDocument xmlDocument = new XmlDocument();
XmlElement elem = xmlDocument.CreateElement("includeSources", @"http://maven.apache.org/POM/4.0.0");
//LOOP THROUGH EXISTING AND ADD IF ITS NOT A WEBREFERENCE
string compareStr = GetRelativePath(pom.Directory, new DirectoryInfo(path));
foreach (XmlNode n in elems[count].ChildNodes)
{
if ("includeSource".Equals(n.Name))
{
if (n.InnerText != null && !n.InnerText.Trim().StartsWith(compareStr.Replace("\\", "/")))
{
if (!n.InnerText.Contains(name))
{
XmlNode node = xmlDocument.CreateNode(XmlNodeType.Element, n.Name, @"http://maven.apache.org/POM/4.0.0");
node.InnerText = n.InnerText;
elem.AppendChild(node);
}
}
}
}
elems[count] = elem;
WriteModelToPom(model);
break;
}
}
}
}
}
}
void removeWebConfiguration(Plugin plugin, string name)
{
if (string.IsNullOrEmpty(name))
{
//nothing to remove
return;
}
XmlElement[] elems;
if (plugin.configuration.Any != null)
{
elems = plugin.configuration.Any;
foreach (XmlElement elem in elems)
{
XmlNode removeMe = null;
if (!string.IsNullOrEmpty(elem.Name) &&
elem.Name.ToLower().Equals("webreferences", StringComparison.InvariantCultureIgnoreCase))
{
foreach (XmlNode node in elem.ChildNodes)
{
if (node.Name.ToLower().Equals("webreference", StringComparison.InvariantCultureIgnoreCase))
{
foreach (XmlNode node1 in node.ChildNodes)
{
if (node1.Name.ToLower().Equals("namespace", StringComparison.InvariantCultureIgnoreCase) &&
node1.InnerText.ToLower().Equals(name.ToLower(), StringComparison.InvariantCultureIgnoreCase))
{
removeMe = node;
break;
}
}
}
}
}
if (removeMe != null)
{
elem.RemoveChild(removeMe);
}
if (elem.InnerText.Equals(string.Empty))
{
isWebRefEmpty = true;
}
}
if (isWebRefEmpty)
{
DeletePlugin(plugin);
}
}
}
#endregion
#region RenameWebReference
public void RenameWebReference(string fullpath, string oldName, string newName, string path, string output)
{
string compareStr = Path.Combine(fullpath.Substring(0, fullpath.LastIndexOf("\\")), oldName);
RemoveWebReference(compareStr, oldName);
AddWebReference(newName, path, output);
}
#endregion
//check if web reference is existing
public bool isWebRefExisting(string name)
{
bool exists = false;
StreamReader sr = new StreamReader(pom.FullName);
String temp = sr.ReadLine();
try
{
while (temp != null)
{
if (temp.Contains(name + ".wsdl"))
{
exists = true;
break;
}
temp = sr.ReadLine();
}
}
catch
{
throw;
}
finally
{
try
{
sr.Close();
sr.Dispose();
}
catch
{ }
}
return exists;
}
public bool isWebRefExistingInPom(string path, NPanday.Model.Pom.Model model)
{
bool exists = false;
List<NPanday.Model.Pom.Plugin> plugins = new List<NPanday.Model.Pom.Plugin>();
if (model.build.plugins != null)
{
foreach (Plugin item in model.build.plugins)
{
if (item.artifactId.Equals("maven-wsdl-plugin") && item.configuration != null)
{
List<XmlElement> elems = new List<XmlElement>();
elems.AddRange(item.configuration.Any);
XmlElement elem = getWebReferencesElement(elems.ToArray(), "webreferences");
if (elem.InnerXml.Contains(path.Replace("\\", "/")))
{
exists = true;
}
}
}
}
return exists;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="BrowserDefinition.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.Configuration {
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Configuration;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.Compilation;
using System.Web.UI;
using System.Web.Util;
using System.Xml;
using System.Globalization;
//
//
// <browsers>
// <browser id="XXX" parentID="YYY">
// <identification>
// <userAgent match="xxx" />
// <header name="HTTP_X_JPHONE_DISPLAY" match="xxx" />
// <capability name="majorVersion" match="^6$" />
// </identification>
// <capture>
// <header name="HTTP_X_UP_DEVCAP_NUMSOFTKEYS" match="?'softkeys'\d+)" />
// </capture>
// <capabilities>
// <mobileDeviceManufacturer>OpenWave</mobileDeviceManufacturer>
// <numberOfSoftKeys>$(softkeys)</numberOfSoftKeys>
// </capabilities>
// <controlAdapters>
// <adapter controlType="System.Web.UI.WebControls.Image"
// adapterType="System.Web.UI.WebControls.Adapters.Html32ImageAdapter" />
// </controlAdapters>
// </browser>
// </browsers>
internal class BrowserDefinition {
internal static string MakeValidTypeNameFromString(string s) {
if (s == null) {
return s;
}
s = s.ToLower(CultureInfo.InvariantCulture);
StringBuilder sb = new StringBuilder();
for (int i=0; i<s.Length; i++) {
// To be CLS-compliant (CS3008), public method name cannot starts with _{digit}
if (i == 0) {
if(Char.IsDigit(s[0])) {
sb.Append("N");
}
else if(Char.IsLetter(s[0])) {
sb.Append(s.Substring(0, 1).ToUpper(CultureInfo.InvariantCulture));
continue;
}
}
if (Char.IsLetterOrDigit(s[i]) || s[i] == '_') {
sb.Append(s[i]);
}
else {
//
sb.Append('A');
}
}
return sb.ToString();
}
// _idHeaderChecks are the header name and match string for <identification>
private ArrayList _idHeaderChecks;
//_idCapabilityChecks are the capability name and match string for <identification>
private ArrayList _idCapabilityChecks;
//_captureHeaderChecks are the header name and match string for <capture>
private ArrayList _captureHeaderChecks;
//_captureCapabilityChecks are the capability name and match string for <capture>
private ArrayList _captureCapabilityChecks;
private AdapterDictionary _adapters;
private string _id;
private string _parentID;
private string _name;
private string _parentName;
private NameValueCollection _capabilities;
private BrowserDefinitionCollection _browsers;
private BrowserDefinitionCollection _gateways;
private BrowserDefinitionCollection _refBrowsers;
private BrowserDefinitionCollection _refGateways;
private XmlNode _node;
private bool _isRefID = false;
private bool _isDeviceNode;
private bool _isDefaultBrowser;
private string _htmlTextWriterString;
private int _depth = 0;
internal BrowserDefinition(XmlNode node) : this(node, false) {
}
internal BrowserDefinition(XmlNode node, bool isDefaultBrowser) {
if (node == null)
throw new ArgumentNullException("node");
_capabilities = new NameValueCollection();
_idHeaderChecks = new ArrayList();
_idCapabilityChecks = new ArrayList();
_captureHeaderChecks = new ArrayList();
_captureCapabilityChecks = new ArrayList();
_adapters = new AdapterDictionary();
_browsers = new BrowserDefinitionCollection();
_gateways = new BrowserDefinitionCollection();
_refBrowsers = new BrowserDefinitionCollection();
_refGateways = new BrowserDefinitionCollection();
_node = node;
_isDefaultBrowser = isDefaultBrowser;
string refID = null;
HandlerBase.GetAndRemoveNonEmptyStringAttribute(node, "id", ref _id);
HandlerBase.GetAndRemoveNonEmptyStringAttribute(node, "refID", ref refID);
if((refID != null) && (_id != null)) {
throw new ConfigurationErrorsException(SR.GetString(SR.Browser_mutually_exclusive_attributes, "id", "refID"), node);
}
if (_id != null) {
if (!System.CodeDom.Compiler.CodeGenerator.IsValidLanguageIndependentIdentifier(_id)) {
throw new ConfigurationErrorsException(SR.GetString(SR.Browser_InvalidID, "id", _id), node);
}
}
else {
if (refID == null) {
if (this is GatewayDefinition) {
throw new ConfigurationErrorsException(SR.GetString(SR.Browser_attributes_required, "gateway", "refID", "id"), node);
}
throw new ConfigurationErrorsException(SR.GetString(SR.Browser_attributes_required, "browser", "refID", "id"), node);
}
else {
if (!System.CodeDom.Compiler.CodeGenerator.IsValidLanguageIndependentIdentifier(refID)) {
throw new ConfigurationErrorsException(SR.GetString(SR.Browser_InvalidID, "refID", refID), node);
}
}
_parentID = refID;
_isRefID = true;
_id = refID;
if (this is GatewayDefinition) {
_name = "refgatewayid$";
}
else {
_name = "refbrowserid$";
}
String parentID = null;
HandlerBase.GetAndRemoveNonEmptyStringAttribute(node, "parentID", ref parentID);
if ((parentID != null) && (parentID.Length != 0)) {
throw new ConfigurationErrorsException(SR.GetString(SR.Browser_mutually_exclusive_attributes, "parentID", "refID"), node);
}
}
_name = MakeValidTypeNameFromString(_id + _name);
if(!_isRefID) {
// Not a default browser definition
if (!("Default".Equals(_id))) {
HandlerBase.GetAndRemoveNonEmptyStringAttribute(node, "parentID", ref _parentID);
}
// Make sure parentID is not specified on default browser
else {
HandlerBase.GetAndRemoveNonEmptyStringAttribute(node, "parentID", ref _parentID);
if (_parentID != null)
throw new ConfigurationErrorsException(
SR.GetString(SR.Browser_parentID_applied_to_default), node);
}
}
_parentName = MakeValidTypeNameFromString(_parentID);
if(_id.IndexOf(" ", StringComparison.Ordinal) != -1) {
throw new ConfigurationErrorsException(SR.GetString(SR.Space_attribute, "id " + _id), node);
}
foreach(XmlNode child in node.ChildNodes) {
if(child.NodeType != XmlNodeType.Element) {
continue;
}
switch (child.Name) {
case "identification":
// refID nodes do not allow <identification>
if (_isRefID) {
throw new ConfigurationErrorsException(SR.GetString(SR.Browser_refid_prohibits_identification), node);
}
this.ProcessIdentificationNode(child, BrowserCapsElementType.Identification);
break;
case "capture":
this.ProcessCaptureNode(child, BrowserCapsElementType.Capture);
break;
case "capabilities":
this.ProcessCapabilitiesNode(child);
break;
case "controlAdapters":
this.ProcessControlAdaptersNode(child);
break;
case "sampleHeaders":
break;
default:
throw new ConfigurationErrorsException(SR.GetString(SR.Browser_invalid_element, child.Name), node);
}
}
}
public bool IsDefaultBrowser {
get {
return _isDefaultBrowser;
}
}
public BrowserDefinitionCollection Browsers {
get {
return _browsers;
}
}
public BrowserDefinitionCollection RefBrowsers {
get {
return _refBrowsers;
}
}
public BrowserDefinitionCollection RefGateways {
get {
return _refGateways;
}
}
public BrowserDefinitionCollection Gateways {
get {
return _gateways;
}
}
public string ID {
get {
return _id;
}
}
public string Name {
get {
return _name;
}
}
public string ParentName {
get {
return _parentName;
}
}
// Indicate whether this node represents a real device, ie. all ancestor nodes are browser deinitions.
internal bool IsDeviceNode {
get {
return _isDeviceNode;
}
set {
_isDeviceNode = value;
}
}
internal int Depth {
get {
return _depth;
}
set {
_depth = value;
}
}
public string ParentID {
get {
return _parentID;
}
}
internal bool IsRefID {
get {
return _isRefID;
}
}
public NameValueCollection Capabilities {
get {
return _capabilities;
}
}
public ArrayList IdHeaderChecks {
get {
return _idHeaderChecks;
}
}
public ArrayList CaptureHeaderChecks {
get {
return _captureHeaderChecks;
}
}
public ArrayList IdCapabilityChecks {
get {
return _idCapabilityChecks;
}
}
public ArrayList CaptureCapabilityChecks {
get {
return _captureCapabilityChecks;
}
}
public AdapterDictionary Adapters {
get {
return _adapters;
}
}
internal XmlNode XmlNode {
get {
return _node;
}
}
public string HtmlTextWriterString {
get {
return _htmlTextWriterString;
}
}
private void DisallowNonMatchAttribute(XmlNode node) {
string check = null;
HandlerBase.GetAndRemoveStringAttribute(node, "nonMatch", ref check);
if(check != null) {
throw new ConfigurationErrorsException(SR.GetString(SR.Browser_mutually_exclusive_attributes, "match", "nonMatch"), node);
}
}
private void HandleMissingMatchAndNonMatchError(XmlNode node) {
throw new ConfigurationErrorsException(
SR.GetString(SR.Missing_required_attributes, "match", "nonMatch", node.Name),
node);
}
/*
/*
<identification>
<userAgent match="xxx" />
<header name="HTTP_X_JPHONE_DISPLAY" match="xxx" />
<capability name="majorVersion" match="^6$" />
</identification>
<capture>
<header name="HTTP_X_UP_DEVCAP_NUMSOFTKEYS" match="?'softkeys'\d+)" />
</capture>
*/
internal void ProcessIdentificationNode(XmlNode node, BrowserCapsElementType elementType) {
string match = null;
string header = null;
bool nonMatch;
bool emptyIdentification = true;
foreach(XmlNode child in node.ChildNodes) {
match = String.Empty;
nonMatch = false;
if(child.NodeType != XmlNodeType.Element) {
continue;
}
switch (child.Name) {
case "userAgent":
emptyIdentification = false;
//match the user agent
HandlerBase.GetAndRemoveNonEmptyStringAttribute(child, "match", ref match);
if (String.IsNullOrEmpty(match)) {
HandlerBase.GetAndRemoveNonEmptyStringAttribute(child, "nonMatch", ref match);
if (String.IsNullOrEmpty(match)) {
HandleMissingMatchAndNonMatchError(child);
}
nonMatch = true;
}
_idHeaderChecks.Add(new CheckPair("User-Agent", match, nonMatch));
if (nonMatch == false) {
DisallowNonMatchAttribute(child);
}
break;
case "header":
emptyIdentification = false;
//match some arbitrary header
HandlerBase.GetAndRemoveRequiredNonEmptyStringAttribute(child, "name", ref header);
HandlerBase.GetAndRemoveNonEmptyStringAttribute(child, "match", ref match);
if (String.IsNullOrEmpty(match)) {
HandlerBase.GetAndRemoveNonEmptyStringAttribute(child, "nonMatch", ref match);
if (String.IsNullOrEmpty(match)) {
HandleMissingMatchAndNonMatchError(child);
}
nonMatch = true;
}
_idHeaderChecks.Add(new CheckPair(header, match, nonMatch));
if (nonMatch == false) {
DisallowNonMatchAttribute(child);
}
break;
case "capability":
emptyIdentification = false;
//match against an already set capability
HandlerBase.GetAndRemoveRequiredNonEmptyStringAttribute(child, "name", ref header);
HandlerBase.GetAndRemoveNonEmptyStringAttribute(child, "match", ref match);
if (String.IsNullOrEmpty(match)) {
HandlerBase.GetAndRemoveNonEmptyStringAttribute(child, "nonMatch", ref match);
if (String.IsNullOrEmpty(match)) {
HandleMissingMatchAndNonMatchError(child);
}
nonMatch = true;
}
_idCapabilityChecks.Add(new CheckPair(header, match, nonMatch));
//verify that match and nonMatch are not both specified
if (nonMatch == false) {
DisallowNonMatchAttribute(child);
}
break;
default:
throw new ConfigurationErrorsException(SR.GetString(SR.Config_invalid_element, child.ToString()), child);
}
}
if (emptyIdentification) {
throw new ConfigurationErrorsException(SR.GetString(SR.Browser_empty_identification), node);
}
return;
}
internal void ProcessCaptureNode(XmlNode node, BrowserCapsElementType elementType) {
string match = null;
string header = null;
foreach(XmlNode child in node.ChildNodes) {
if(child.NodeType != XmlNodeType.Element) {
continue;
}
switch(child.Name) {
case "userAgent":
//match the user agent
HandlerBase.GetAndRemoveRequiredNonEmptyStringAttribute(child, "match", ref match);
_captureHeaderChecks.Add(new CheckPair("User-Agent", match));
break;
case "header":
//match some arbitrary header
HandlerBase.GetAndRemoveRequiredNonEmptyStringAttribute(child, "name", ref header);
HandlerBase.GetAndRemoveRequiredNonEmptyStringAttribute(child, "match", ref match);
_captureHeaderChecks.Add(new CheckPair(header, match));
break;
case "capability":
//match against an already set capability
HandlerBase.GetAndRemoveRequiredNonEmptyStringAttribute(child, "name", ref header);
HandlerBase.GetAndRemoveRequiredNonEmptyStringAttribute(child, "match", ref match);
_captureCapabilityChecks.Add(new CheckPair(header, match));
break;
default:
throw new ConfigurationErrorsException(SR.GetString(SR.Config_invalid_element, child.ToString()), child);
}
}
return;
}
/*
<capabilities>
<capability name="mobileDeviceManufacturer" value="OpenWave"</capability>
<capability name="numberOfSoftKeys" value="$(softkeys)"</capability>
</capabilities>
*/
internal void ProcessCapabilitiesNode(XmlNode node) {
foreach(XmlNode child in node.ChildNodes) {
if(child.NodeType != XmlNodeType.Element) {
continue;
}
if (child.Name != "capability") {
throw new ConfigurationErrorsException(SR.GetString(SR.Config_base_unrecognized_element), child);
}
string capabilityName = null;
string capabilityValue = null;
HandlerBase.GetAndRemoveRequiredNonEmptyStringAttribute(child, "name", ref capabilityName);
HandlerBase.GetAndRemoveRequiredStringAttribute(child, "value", ref capabilityValue);
_capabilities[capabilityName] = capabilityValue;
}
return;
}
/*
<controlAdapters>
<adapter controlType="System.Web.UI.WebControls.Image"
adapterType="System.Web.UI.WebControls.Adapters.Html32ImageAdapter" />
</controlAdapters>
*/
internal void ProcessControlAdaptersNode(XmlNode node) {
HandlerBase.GetAndRemoveStringAttribute(node, "markupTextWriterType", ref _htmlTextWriterString);
foreach(XmlNode child in node.ChildNodes) {
if(child.NodeType != XmlNodeType.Element) {
continue;
}
if(child.Name != "adapter") {
throw new ConfigurationErrorsException(SR.GetString(SR.Config_base_unrecognized_element), child);
}
XmlAttributeCollection nodeAttributes = child.Attributes;
string controlString = null;
string adapterString = null;
HandlerBase.GetAndRemoveRequiredNonEmptyStringAttribute(child, "controlType", ref controlString);
HandlerBase.GetAndRemoveRequiredStringAttribute(child, "adapterType", ref adapterString);
Type type = CheckType(controlString, typeof(Control), child);
// Normalize control type name
controlString = type.AssemblyQualifiedName;
if (!String.IsNullOrEmpty(adapterString)) {
CheckType(adapterString, typeof(System.Web.UI.Adapters.ControlAdapter), child);
}
_adapters[controlString] = adapterString;
}
return;
}
private static Type CheckType(string typeName, Type baseType, XmlNode child) {
// Use BuildManager to verify control types.
// Note for machine level browser files, this will only check assemblies in GAC.
Type type = ConfigUtil.GetType(typeName, child, true /*ignoreCase*/);
if (!baseType.IsAssignableFrom(type)) {
throw new ConfigurationErrorsException(
SR.GetString(SR.Type_doesnt_inherit_from_type, typeName,
baseType.FullName), child);
}
if (!HttpRuntime.IsTypeAllowedInConfig(type)) {
throw new ConfigurationErrorsException(
SR.GetString(SR.Type_from_untrusted_assembly, typeName), child);
}
return type;
}
internal void MergeWithDefinition(BrowserDefinition definition) {
Debug.Assert(definition.IsRefID);
// Copy the capabilities
foreach (String key in definition.Capabilities.Keys) {
this._capabilities[key] = definition.Capabilities[key];
}
// Copy the adapter definition
foreach (String key in definition.Adapters.Keys) {
this._adapters[key] = definition.Adapters[key];
}
this._htmlTextWriterString = definition.HtmlTextWriterString;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Win32.SafeHandles;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.Security.Authentication;
namespace System.Net.Security
{
//
// SecureChannel - a wrapper on SSPI based functionality.
// Provides an additional abstraction layer over SSPI for SslStream.
//
internal class SecureChannel
{
// When reading a frame from the wire first read this many bytes for the header.
internal const int ReadHeaderSize = 5;
private SafeFreeCredentials _credentialsHandle;
private SafeDeleteContext _securityContext;
private readonly string _destination;
private readonly string _hostName;
private readonly bool _serverMode;
private readonly bool _remoteCertRequired;
private readonly SslProtocols _sslProtocols;
private readonly EncryptionPolicy _encryptionPolicy;
private SslConnectionInfo _connectionInfo;
private X509Certificate _serverCertificate;
private X509Certificate _selectedClientCertificate;
private bool _isRemoteCertificateAvailable;
private readonly X509CertificateCollection _clientCertificates;
private LocalCertSelectionCallback _certSelectionDelegate;
// These are the MAX encrypt buffer output sizes, not the actual sizes.
private int _headerSize = 5; //ATTN must be set to at least 5 by default
private int _trailerSize = 16;
private int _maxDataSize = 16354;
private bool _checkCertRevocation;
private bool _checkCertName;
private bool _refreshCredentialNeeded;
internal SecureChannel(string hostname, bool serverMode, SslProtocols sslProtocols, X509Certificate serverCertificate, X509CertificateCollection clientCertificates, bool remoteCertRequired, bool checkCertName,
bool checkCertRevocationStatus, EncryptionPolicy encryptionPolicy, LocalCertSelectionCallback certSelectionDelegate)
{
GlobalLog.Enter("SecureChannel#" + Logging.HashString(this) + "::.ctor", "hostname:" + hostname + " #clientCertificates=" + ((clientCertificates == null) ? "0" : clientCertificates.Count.ToString(NumberFormatInfo.InvariantInfo)));
if (Logging.On)
{
Logging.PrintInfo(Logging.Web, this, ".ctor", "hostname=" + hostname + ", #clientCertificates=" + ((clientCertificates == null) ? "0" : clientCertificates.Count.ToString(NumberFormatInfo.InvariantInfo)) + ", encryptionPolicy=" + encryptionPolicy);
}
SSPIWrapper.VerifyPackageInfo(GlobalSSPI.SSPISecureChannel);
_destination = hostname;
GlobalLog.Assert(hostname != null, "SecureChannel#{0}::.ctor()|hostname == null", Logging.HashString(this));
_hostName = hostname;
_serverMode = serverMode;
_sslProtocols = sslProtocols;
_serverCertificate = serverCertificate;
_clientCertificates = clientCertificates;
_remoteCertRequired = remoteCertRequired;
_securityContext = null;
_checkCertRevocation = checkCertRevocationStatus;
_checkCertName = checkCertName;
_certSelectionDelegate = certSelectionDelegate;
_refreshCredentialNeeded = true;
_encryptionPolicy = encryptionPolicy;
GlobalLog.Leave("SecureChannel#" + Logging.HashString(this) + "::.ctor");
}
//
// SecureChannel properties
//
// LocalServerCertificate - local certificate for server mode channel
// LocalClientCertificate - selected certificated used in the client channel mode otherwise null
// IsRemoteCertificateAvailable - true if the remote side has provided a certificate
// HeaderSize - Header & trailer sizes used in the TLS stream
// TrailerSize -
//
internal X509Certificate LocalServerCertificate
{
get
{
return _serverCertificate;
}
}
internal X509Certificate LocalClientCertificate
{
get
{
return _selectedClientCertificate;
}
}
internal bool IsRemoteCertificateAvailable
{
get
{
return _isRemoteCertificateAvailable;
}
}
internal ChannelBinding GetChannelBinding(ChannelBindingKind kind)
{
GlobalLog.Enter("SecureChannel#" + Logging.HashString(this) + "::GetChannelBindingToken", kind.ToString());
ChannelBinding result = null;
if (_securityContext != null)
{
result = SSPIWrapper.QueryContextChannelBinding(GlobalSSPI.SSPISecureChannel, _securityContext, kind);
}
GlobalLog.Leave("SecureChannel#" + Logging.HashString(this) + "::GetChannelBindingToken", Logging.HashString(result));
return result;
}
internal bool CheckCertRevocationStatus
{
get
{
return _checkCertRevocation;
}
}
internal X509CertificateCollection ClientCertificates
{
get
{
return _clientCertificates;
}
}
internal int HeaderSize
{
get
{
return _headerSize;
}
}
internal int MaxDataSize
{
get
{
return _maxDataSize;
}
}
internal SslConnectionInfo ConnectionInfo
{
get
{
return _connectionInfo;
}
}
internal bool IsValidContext
{
get
{
return !(_securityContext == null || _securityContext.IsInvalid);
}
}
internal bool IsServer
{
get
{
return _serverMode;
}
}
internal bool RemoteCertRequired
{
get
{
return _remoteCertRequired;
}
}
internal void SetRefreshCredentialNeeded()
{
_refreshCredentialNeeded = true;
}
internal void Close()
{
if (_securityContext != null)
{
_securityContext.Dispose();
}
if (_credentialsHandle != null)
{
_credentialsHandle.Dispose();
}
}
//
// SECURITY: we open a private key container on behalf of the caller
// and we require the caller to have permission associated with that operation.
//
private X509Certificate2 EnsurePrivateKey(X509Certificate certificate)
{
if (certificate == null)
{
return null;
}
if (Logging.On)
{
Logging.PrintInfo(Logging.Web, this, SR.Format(SR.net_log_locating_private_key_for_certificate, certificate.ToString(true)));
}
try
{
string certHash = null;
// Protecting from X509Certificate2 derived classes.
X509Certificate2 certEx = MakeEx(certificate);
certHash = certEx.Thumbprint;
if (certEx != null)
{
if (certEx.HasPrivateKey)
{
if (Logging.On)
{
Logging.PrintInfo(Logging.Web, this, SR.net_log_cert_is_of_type_2);
}
return certEx;
}
if ((object)certificate != (object)certEx)
{
certEx.Dispose();
}
}
X509Certificate2Collection collectionEx;
// ELSE Try the MY user and machine stores for private key check.
// For server side mode MY machine store takes priority.
X509Store store = CertWrapper.EnsureStoreOpened(_serverMode);
if (store != null)
{
collectionEx = store.Certificates.Find(X509FindType.FindByThumbprint, certHash, false);
if (collectionEx.Count > 0 && collectionEx[0].HasPrivateKey)
{
if (Logging.On)
{
Logging.PrintInfo(Logging.Web, this, SR.Format(SR.net_log_found_cert_in_store, (_serverMode ? "LocalMachine" : "CurrentUser")));
}
return collectionEx[0];
}
}
store = CertWrapper.EnsureStoreOpened(!_serverMode);
if (store != null)
{
collectionEx = store.Certificates.Find(X509FindType.FindByThumbprint, certHash, false);
if (collectionEx.Count > 0 && collectionEx[0].HasPrivateKey)
{
if (Logging.On)
{
Logging.PrintInfo(Logging.Web, this, SR.Format(SR.net_log_found_cert_in_store, (_serverMode ? "CurrentUser" : "LocalMachine")));
}
return collectionEx[0];
}
}
}
catch (CryptographicException)
{
}
if (Logging.On)
{
Logging.PrintInfo(Logging.Web, this, SR.net_log_did_not_find_cert_in_store);
}
return null;
}
private static X509Certificate2 MakeEx(X509Certificate certificate)
{
Debug.Assert(certificate != null, "certificate != null");
if (certificate.GetType() == typeof(X509Certificate2))
{
return (X509Certificate2)certificate;
}
X509Certificate2 certificateEx = null;
try
{
if (certificate.Handle != IntPtr.Zero)
{
certificateEx = new X509Certificate2(certificate.Handle);
}
}
catch (SecurityException) { }
catch (CryptographicException) { }
return certificateEx;
}
//
// Get certificate_authorities list, according to RFC 5246, Section 7.4.4.
// Used only by client SSL code, never returns null.
//
private string[] GetRequestCertificateAuthorities()
{
string[] issuers = Array.Empty<string>();
if (IsValidContext)
{
issuers = CertWrapper.GetRequestCertificateAuthorities(_securityContext);
}
return issuers;
}
/*++
AcquireCredentials - Attempts to find Client Credential
Information, that can be sent to the server. In our case,
this is only Client Certificates, that we have Credential Info.
How it works:
case 0: Cert Selection delegate is present
Always use its result as the client cert answer.
Try to use cached credential handle whenever feasible.
Do not use cached anonymous creds if the delegate has returned null
and the collection is not empty (allow responding with the cert later).
case 1: Certs collection is empty
Always use the same statically acquired anonymous SSL Credential
case 2: Before our Connection with the Server
If we have a cached credential handle keyed by first X509Certificate
**content** in the passed collection, then we use that cached
credential and hoping to restart a session.
Otherwise create a new anonymous (allow responding with the cert later).
case 3: After our Connection with the Server (i.e. during handshake or re-handshake)
The server has requested that we send it a Certificate then
we Enumerate a list of server sent Issuers trying to match against
our list of Certificates, the first match is sent to the server.
Once we got a cert we again try to match cached credential handle if possible.
This will not restart a session but helps minimizing the number of handles we create.
In the case of an error getting a Certificate or checking its private Key we fall back
to the behavior of having no certs, case 1.
Returns: True if cached creds were used, false otherwise.
--*/
private bool AcquireClientCredentials(ref byte[] thumbPrint)
{
GlobalLog.Enter("SecureChannel#" + Logging.HashString(this) + "::AcquireClientCredentials");
// Acquire possible Client Certificate information and set it on the handle.
X509Certificate clientCertificate = null; // This is a candidate that can come from the user callback or be guessed when targeting a session restart.
ArrayList filteredCerts = new ArrayList(); // This is an intermediate client certs collection that try to use if no selectedCert is available yet.
string[] issuers = null; // This is a list of issuers sent by the server, only valid is we do know what the server cert is.
bool sessionRestartAttempt = false; // If true and no cached creds we will use anonymous creds.
if (_certSelectionDelegate != null)
{
issuers = GetRequestCertificateAuthorities();
GlobalLog.Print("SecureChannel#" + Logging.HashString(this) + "::AcquireClientCredentials() calling CertificateSelectionCallback");
X509Certificate2 remoteCert = null;
try
{
X509Certificate2Collection dummyCollection;
remoteCert = CertWrapper.GetRemoteCertificate(_securityContext, out dummyCollection);
clientCertificate = _certSelectionDelegate(_hostName, ClientCertificates, remoteCert, issuers);
}
finally
{
if (remoteCert != null)
{
remoteCert.Dispose();
}
}
if (clientCertificate != null)
{
if (_credentialsHandle == null)
{
sessionRestartAttempt = true;
}
filteredCerts.Add(clientCertificate);
if (Logging.On)
{
Logging.PrintInfo(Logging.Web, this, SR.net_log_got_certificate_from_delegate);
}
}
else
{
if (ClientCertificates.Count == 0)
{
if (Logging.On)
{
Logging.PrintInfo(Logging.Web, this, SR.net_log_no_delegate_and_have_no_client_cert);
}
sessionRestartAttempt = true;
}
else
{
if (Logging.On)
{
Logging.PrintInfo(Logging.Web, this, SR.net_log_no_delegate_but_have_client_cert);
}
}
}
}
else if (_credentialsHandle == null && _clientCertificates != null && _clientCertificates.Count > 0)
{
// This is where we attempt to restart a session by picking the FIRST cert from the collection.
// Otherwise it is either server sending a client cert request or the session is renegotiated.
clientCertificate = ClientCertificates[0];
sessionRestartAttempt = true;
if (clientCertificate != null)
{
filteredCerts.Add(clientCertificate);
}
if (Logging.On)
{
Logging.PrintInfo(Logging.Web, this, SR.Format(SR.net_log_attempting_restart_using_cert, (clientCertificate == null ? "null" : clientCertificate.ToString(true))));
}
}
else if (_clientCertificates != null && _clientCertificates.Count > 0)
{
//
// This should be a server request for the client cert sent over currently anonymous sessions.
//
issuers = GetRequestCertificateAuthorities();
if (Logging.On)
{
if (issuers == null || issuers.Length == 0)
{
Logging.PrintInfo(Logging.Web, this, SR.net_log_no_issuers_try_all_certs);
}
else
{
Logging.PrintInfo(Logging.Web, this, SR.Format(SR.net_log_server_issuers_look_for_matching_certs, issuers.Length));
}
}
for (int i = 0; i < _clientCertificates.Count; ++i)
{
//
// Make sure we add only if the cert matches one of the issuers.
// If no issuers were sent and then try all client certs starting with the first one.
//
if (issuers != null && issuers.Length != 0)
{
X509Certificate2 certificateEx = null;
X509Chain chain = null;
try
{
certificateEx = MakeEx(_clientCertificates[i]);
if (certificateEx == null)
{
continue;
}
GlobalLog.Print("SecureChannel#" + Logging.HashString(this) + "::AcquireClientCredentials() root cert:" + certificateEx.Issuer);
chain = new X509Chain();
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.IgnoreInvalidName;
chain.Build(certificateEx);
bool found = false;
//
// We ignore any errors happened with chain.
//
if (chain.ChainElements.Count > 0)
{
for (int ii = 0; ii < chain.ChainElements.Count; ++ii)
{
string issuer = chain.ChainElements[ii].Certificate.Issuer;
found = Array.IndexOf(issuers, issuer) != -1;
if (found)
{
GlobalLog.Print("SecureChannel#" + Logging.HashString(this) + "::AcquireClientCredentials() matched:" + issuer);
break;
}
GlobalLog.Print("SecureChannel#" + Logging.HashString(this) + "::AcquireClientCredentials() no match:" + issuer);
}
}
if (!found)
{
continue;
}
}
finally
{
if (chain != null)
{
chain.Dispose();
}
if (certificateEx != null && (object)certificateEx != (object)_clientCertificates[i])
{
certificateEx.Dispose();
}
}
}
if (Logging.On)
{
Logging.PrintInfo(Logging.Web, this, SR.Format(SR.net_log_selected_cert, _clientCertificates[i].ToString(true)));
}
filteredCerts.Add(_clientCertificates[i]);
}
}
bool cachedCred = false; // This is a return result from this method.
X509Certificate2 selectedCert = null; // This is a final selected cert (ensured that it does have private key with it).
clientCertificate = null;
if (Logging.On)
{
Logging.PrintInfo(Logging.Web, this, SR.Format(SR.net_log_n_certs_after_filtering, filteredCerts.Count));
if (filteredCerts.Count != 0)
{
Logging.PrintInfo(Logging.Web, this, SR.net_log_finding_matching_certs);
}
}
//
// ATTN: When the client cert was returned by the user callback OR it was guessed AND it has no private key,
// THEN anonymous (no client cert) credential will be used.
//
// SECURITY: Accessing X509 cert Credential is disabled for semitrust.
// We no longer need to demand for unmanaged code permissions.
// EnsurePrivateKey should do the right demand for us.
for (int i = 0; i < filteredCerts.Count; ++i)
{
clientCertificate = filteredCerts[i] as X509Certificate;
if ((selectedCert = EnsurePrivateKey(clientCertificate)) != null)
{
break;
}
clientCertificate = null;
selectedCert = null;
}
GlobalLog.Assert(((object)clientCertificate == (object)selectedCert) || clientCertificate.Equals(selectedCert), "AcquireClientCredentials()|'selectedCert' does not match 'clientCertificate'.");
GlobalLog.Print("SecureChannel#" + Logging.HashString(this) + "::AcquireClientCredentials() Selected Cert = " + (selectedCert == null ? "null" : selectedCert.Subject));
try
{
// Try to locate cached creds first.
//
// SECURITY: selectedCert ref if not null is a safe object that does not depend on possible **user** inherited X509Certificate type.
//
byte[] guessedThumbPrint = selectedCert == null ? null : selectedCert.GetCertHash();
SafeFreeCredentials cachedCredentialHandle = SslSessionsCache.TryCachedCredential(guessedThumbPrint, _sslProtocols, _serverMode, _encryptionPolicy);
// We can probably do some optimization here. If the selectedCert is returned by the delegate
// we can always go ahead and use the certificate to create our credential
// (instead of going anonymous as we do here).
if (sessionRestartAttempt && cachedCredentialHandle == null && selectedCert != null)
{
GlobalLog.Print("SecureChannel#" + Logging.HashString(this) + "::AcquireClientCredentials() Reset to anonymous session.");
// IIS does not renegotiate a restarted session if client cert is needed.
// So we don't want to reuse **anonymous** cached credential for a new SSL connection if the client has passed some certificate.
// The following block happens if client did specify a certificate but no cached creds were found in the cache.
// Since we don't restart a session the server side can still challenge for a client cert.
if ((object)clientCertificate != (object)selectedCert)
{
selectedCert.Dispose();
}
guessedThumbPrint = null;
selectedCert = null;
clientCertificate = null;
}
if (cachedCredentialHandle != null)
{
if (Logging.On)
{
Logging.PrintInfo(Logging.Web, SR.net_log_using_cached_credential);
}
_credentialsHandle = cachedCredentialHandle;
_selectedClientCertificate = clientCertificate;
cachedCred = true;
}
else
{
_credentialsHandle = SSPIWrapper.AcquireCredentialsHandle(GlobalSSPI.SSPISecureChannel, selectedCert, _sslProtocols, _encryptionPolicy, _serverMode);
thumbPrint = guessedThumbPrint; // Delay until here in case something above threw.
_selectedClientCertificate = clientCertificate;
}
}
finally
{
// An extra cert could have been created, dispose it now.
if (selectedCert != null && (object)clientCertificate != (object)selectedCert)
{
selectedCert.Dispose();
}
}
GlobalLog.Leave("SecureChannel#" + Logging.HashString(this) + "::AcquireClientCredentials, cachedCreds = " + cachedCred.ToString(), Logging.ObjectToString(_credentialsHandle));
return cachedCred;
}
//
// Acquire Server Side Certificate information and set it on the class.
//
private bool AcquireServerCredentials(ref byte[] thumbPrint)
{
GlobalLog.Enter("SecureChannel#" + Logging.HashString(this) + "::AcquireServerCredentials");
X509Certificate localCertificate = null;
bool cachedCred = false;
if (_certSelectionDelegate != null)
{
X509CertificateCollection tempCollection = new X509CertificateCollection();
tempCollection.Add(_serverCertificate);
localCertificate = _certSelectionDelegate(string.Empty, tempCollection, null, Array.Empty<string>());
GlobalLog.Print("SecureChannel#" + Logging.HashString(this) + "::AcquireServerCredentials() Use delegate selected Cert");
}
else
{
localCertificate = _serverCertificate;
}
if (localCertificate == null)
{
throw new NotSupportedException(SR.net_ssl_io_no_server_cert);
}
// SECURITY: Accessing X509 cert Credential is disabled for semitrust.
// We no longer need to demand for unmanaged code permissions.
// EnsurePrivateKey should do the right demand for us.
X509Certificate2 selectedCert = EnsurePrivateKey(localCertificate);
if (selectedCert == null)
{
throw new NotSupportedException(SR.net_ssl_io_no_server_cert);
}
GlobalLog.Assert(localCertificate.Equals(selectedCert), "AcquireServerCredentials()|'selectedCert' does not match 'localCertificate'.");
//
// Note selectedCert is a safe ref possibly cloned from the user passed Cert object
//
byte[] guessedThumbPrint = selectedCert.GetCertHash();
try
{
SafeFreeCredentials cachedCredentialHandle = SslSessionsCache.TryCachedCredential(guessedThumbPrint, _sslProtocols, _serverMode, _encryptionPolicy);
if (cachedCredentialHandle != null)
{
_credentialsHandle = cachedCredentialHandle;
_serverCertificate = localCertificate;
cachedCred = true;
}
else
{
_credentialsHandle = SSPIWrapper.AcquireCredentialsHandle(GlobalSSPI.SSPISecureChannel, selectedCert, _sslProtocols, _encryptionPolicy, _serverMode);
thumbPrint = guessedThumbPrint;
_serverCertificate = localCertificate;
}
}
finally
{
// An extra cert could have been created, dispose it now.
if ((object)localCertificate != (object)selectedCert)
{
selectedCert.Dispose();
}
}
GlobalLog.Leave("SecureChannel#" + Logging.HashString(this) + "::AcquireServerCredentials, cachedCreds = " + cachedCred.ToString(), Logging.ObjectToString(_credentialsHandle));
return cachedCred;
}
//
internal ProtocolToken NextMessage(byte[] incoming, int offset, int count)
{
GlobalLog.Enter("SecureChannel#" + Logging.HashString(this) + "::NextMessage");
byte[] nextmsg = null;
SecurityStatus errorCode = GenerateToken(incoming, offset, count, ref nextmsg);
if (!_serverMode && errorCode == SecurityStatus.CredentialsNeeded)
{
GlobalLog.Print("SecureChannel#" + Logging.HashString(this) + "::NextMessage() returned SecurityStatus.CredentialsNeeded");
SetRefreshCredentialNeeded();
errorCode = GenerateToken(incoming, offset, count, ref nextmsg);
}
ProtocolToken token = new ProtocolToken(nextmsg, errorCode);
GlobalLog.Leave("SecureChannel#" + Logging.HashString(this) + "::NextMessage", token.ToString());
return token;
}
/*++
GenerateToken - Called after each successive state
in the Client - Server handshake. This function
generates a set of bytes that will be sent next to
the server. The server responds, each response,
is pass then into this function, again, and the cycle
repeats until successful connection, or failure.
Input:
input - bytes from the wire
output - ref to byte [], what we will send to the
server in response
Return:
errorCode - an SSPI error code
--*/
private SecurityStatus GenerateToken(byte[] input, int offset, int count, ref byte[] output)
{
#if TRACE_VERBOSE
GlobalLog.Enter("SecureChannel#" + Logging.HashString(this) + "::GenerateToken, _refreshCredentialNeeded = " + _refreshCredentialNeeded);
#endif
if (offset < 0 || offset > (input == null ? 0 : input.Length))
{
GlobalLog.Assert(false, "SecureChannel#" + Logging.HashString(this) + "::GenerateToken", "Argument 'offset' out of range.");
throw new ArgumentOutOfRangeException("offset");
}
if (count < 0 || count > (input == null ? 0 : input.Length - offset))
{
GlobalLog.Assert(false, "SecureChannel#" + Logging.HashString(this) + "::GenerateToken", "Argument 'count' out of range.");
throw new ArgumentOutOfRangeException("count");
}
SecurityBuffer incomingSecurity = null;
SecurityBuffer[] incomingSecurityBuffers = null;
if (input != null)
{
incomingSecurity = new SecurityBuffer(input, offset, count, SecurityBufferType.Token);
incomingSecurityBuffers = new SecurityBuffer[]
{
incomingSecurity,
new SecurityBuffer(null, 0, 0, SecurityBufferType.Empty)
};
}
SecurityBuffer outgoingSecurity = new SecurityBuffer(null, SecurityBufferType.Token);
SecurityStatus errorCode = 0;
bool cachedCreds = false;
byte[] thumbPrint = null;
//
// Looping through ASC or ISC with potentially cached credential that could have been
// already disposed from a different thread before ISC or ASC dir increment a cred ref count.
//
try
{
do
{
thumbPrint = null;
if (_refreshCredentialNeeded)
{
cachedCreds = _serverMode
? AcquireServerCredentials(ref thumbPrint)
: AcquireClientCredentials(ref thumbPrint);
}
if (_serverMode)
{
errorCode = SSPIWrapper.AcceptSecurityContext(
GlobalSSPI.SSPISecureChannel,
ref _credentialsHandle,
ref _securityContext,
incomingSecurity,
outgoingSecurity,
_remoteCertRequired
);
}
else
{
if (incomingSecurity == null)
{
errorCode = SSPIWrapper.InitializeSecurityContext(
GlobalSSPI.SSPISecureChannel,
ref _credentialsHandle,
ref _securityContext,
_destination,
incomingSecurity,
outgoingSecurity
);
}
else
{
errorCode = SSPIWrapper.InitializeSecurityContext(
GlobalSSPI.SSPISecureChannel,
_credentialsHandle,
ref _securityContext,
_destination,
incomingSecurityBuffers,
outgoingSecurity
);
}
}
} while (cachedCreds && _credentialsHandle == null);
}
finally
{
if (_refreshCredentialNeeded)
{
_refreshCredentialNeeded = false;
//
// Assuming the ISC or ASC has referenced the credential,
// we want to call dispose so to decrement the effective ref count.
//
if (_credentialsHandle != null)
{
_credentialsHandle.Dispose();
}
//
// This call may bump up the credential reference count further.
// Note that thumbPrint is retrieved from a safe cert object that was possible cloned from the user passed cert.
//
if (!cachedCreds && _securityContext != null && !_securityContext.IsInvalid && _credentialsHandle != null && !_credentialsHandle.IsInvalid)
{
SslSessionsCache.CacheCredential(_credentialsHandle, thumbPrint, _sslProtocols, _serverMode, _encryptionPolicy);
}
}
}
output = outgoingSecurity.token;
#if TRACE_VERBOSE
GlobalLog.Leave("SecureChannel#" + Logging.HashString(this) + "::GenerateToken()", Interop.MapSecurityStatus((uint)errorCode));
#endif
return (SecurityStatus)errorCode;
}
/*++
ProcessHandshakeSuccess -
Called on successful completion of Handshake -
used to set header/trailer sizes for encryption use
Fills in the information about established protocol
--*/
internal void ProcessHandshakeSuccess()
{
GlobalLog.Enter("SecureChannel#" + Logging.HashString(this) + "::ProcessHandshakeSuccess");
StreamSizes streamSizes;
SSPIWrapper.QueryContextStreamSizes(GlobalSSPI.SSPISecureChannel, _securityContext, out streamSizes);
if (streamSizes != null)
{
try
{
_headerSize = streamSizes.header;
_trailerSize = streamSizes.trailer;
_maxDataSize = checked(streamSizes.maximumMessage - (_headerSize + _trailerSize));
}
catch (Exception e)
{
if (!ExceptionCheck.IsFatal(e))
{
GlobalLog.Assert(false, "SecureChannel#" + Logging.HashString(this) + "::ProcessHandshakeSuccess", "StreamSizes out of range.");
}
throw;
}
}
SSPIWrapper.QueryContextConnectionInfo(GlobalSSPI.SSPISecureChannel, _securityContext, out _connectionInfo);
GlobalLog.Leave("SecureChannel#" + Logging.HashString(this) + "::ProcessHandshakeSuccess");
}
/*++
Encrypt - Encrypts our bytes before we send them over the wire
PERF: make more efficient, this does an extra copy when the offset
is non-zero.
Input:
buffer - bytes for sending
offset -
size -
output - Encrypted bytes
--*/
internal SecurityStatus Encrypt(byte[] buffer, int offset, int size, ref byte[] output, out int resultSize)
{
GlobalLog.Enter("SecureChannel#" + Logging.HashString(this) + "::Encrypt");
GlobalLog.Print("SecureChannel#" + Logging.HashString(this) + "::Encrypt() - offset: " + offset.ToString() + " size: " + size.ToString() + " buffersize: " + buffer.Length.ToString());
GlobalLog.Print("SecureChannel#" + Logging.HashString(this) + "::Encrypt() buffer:");
GlobalLog.Dump(buffer, Math.Min(buffer.Length, 128));
byte[] writeBuffer;
try
{
if (offset < 0 || offset > (buffer == null ? 0 : buffer.Length))
{
throw new ArgumentOutOfRangeException("offset");
}
if (size < 0 || size > (buffer == null ? 0 : buffer.Length - offset))
{
throw new ArgumentOutOfRangeException("size");
}
resultSize = 0;
int bufferSizeNeeded = checked(size + _headerSize + _trailerSize);
if (output != null && bufferSizeNeeded <= output.Length)
{
writeBuffer = output;
}
else
{
writeBuffer = new byte[bufferSizeNeeded];
}
Buffer.BlockCopy(buffer, offset, writeBuffer, _headerSize, size);
}
catch (Exception e)
{
if (!ExceptionCheck.IsFatal(e))
{
GlobalLog.Assert(false, "SecureChannel#" + Logging.HashString(this) + "::Encrypt", "Arguments out of range.");
}
throw;
}
SecurityStatus secStatus = SSPIWrapper.EncryptMessage(GlobalSSPI.SSPISecureChannel, _securityContext, writeBuffer, size, _headerSize, _trailerSize, out resultSize);
if (secStatus != SecurityStatus.OK)
{
GlobalLog.Leave("SecureChannel#" + Logging.HashString(this) + "::Encrypt ERROR", secStatus.ToString("x"));
}
else
{
output = writeBuffer;
GlobalLog.Leave("SecureChannel#" + Logging.HashString(this) + "::Encrypt OK", "data size:" + resultSize.ToString());
}
return secStatus;
}
internal SecurityStatus Decrypt(byte[] payload, ref int offset, ref int count)
{
GlobalLog.Print("SecureChannel#" + Logging.HashString(this) + "::Decrypt() - offset: " + offset.ToString() + " size: " + count.ToString() + " buffersize: " + payload.Length.ToString());
if (offset < 0 || offset > (payload == null ? 0 : payload.Length))
{
GlobalLog.Assert(false, "SecureChannel#" + Logging.HashString(this) + "::Encrypt", "Argument 'offset' out of range.");
throw new ArgumentOutOfRangeException("offset");
}
if (count < 0 || count > (payload == null ? 0 : payload.Length - offset))
{
GlobalLog.Assert(false, "SecureChannel#" + Logging.HashString(this) + "::Encrypt", "Argument 'count' out of range.");
throw new ArgumentOutOfRangeException("count");
}
SecurityStatus secStatus = SSPIWrapper.DecryptMessage(GlobalSSPI.SSPISecureChannel, _securityContext, payload, ref offset, ref count);
return secStatus;
}
/*++
VerifyRemoteCertificate - Validates the content of a Remote Certificate
checkCRL if true, checks the certificate revocation list for validity.
checkCertName, if true checks the CN field of the certificate
--*/
//This method validates a remote certificate.
//SECURITY: The scenario is allowed in semitrust StorePermission is asserted for Chain.Build
// A user callback has unique signature so it is safe to call it under permission assert.
//
internal bool VerifyRemoteCertificate(RemoteCertValidationCallback remoteCertValidationCallback)
{
GlobalLog.Enter("SecureChannel#" + Logging.HashString(this) + "::VerifyRemoteCertificate");
SslPolicyErrors sslPolicyErrors = SslPolicyErrors.None;
// We don't catch exceptions in this method, so it's safe for "accepted" be initialized with true.
bool success = false;
X509Chain chain = null;
X509Certificate2 remoteCertificateEx = null;
try
{
X509Certificate2Collection remoteCertificateStore;
remoteCertificateEx = CertWrapper.GetRemoteCertificate(_securityContext, out remoteCertificateStore);
_isRemoteCertificateAvailable = remoteCertificateEx != null;
if (remoteCertificateEx == null)
{
GlobalLog.Leave("SecureChannel#" + Logging.HashString(this) + "::VerifyRemoteCertificate (no remote cert)", (!_remoteCertRequired).ToString());
sslPolicyErrors |= SslPolicyErrors.RemoteCertificateNotAvailable;
}
else
{
chain = new X509Chain();
chain.ChainPolicy.RevocationMode = _checkCertRevocation ? X509RevocationMode.Online : X509RevocationMode.NoCheck;
chain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot;
if (remoteCertificateStore != null)
{
chain.ChainPolicy.ExtraStore.AddRange(remoteCertificateStore);
}
// Don't call chain.Build here in the common code, because the Windows version
// is potentially going to check for GetLastWin32Error, and that call needs to be
// guaranteed to be right after the call to chain.Build.
sslPolicyErrors |= CertWrapper.VerifyCertificateProperties(
chain,
remoteCertificateEx,
_checkCertName,
_serverMode,
_hostName);
}
if (remoteCertValidationCallback != null)
{
success = remoteCertValidationCallback(_hostName, remoteCertificateEx, chain, sslPolicyErrors);
}
else
{
if (sslPolicyErrors == SslPolicyErrors.RemoteCertificateNotAvailable && !_remoteCertRequired)
{
success = true;
}
else
{
success = (sslPolicyErrors == SslPolicyErrors.None);
}
}
if (Logging.On)
{
if (sslPolicyErrors != SslPolicyErrors.None)
{
Logging.PrintInfo(Logging.Web, this, SR.net_log_remote_cert_has_errors);
if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateNotAvailable) != 0)
{
Logging.PrintInfo(Logging.Web, this, "\t" + SR.net_log_remote_cert_not_available);
}
if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateNameMismatch) != 0)
{
Logging.PrintInfo(Logging.Web, this, "\t" + SR.net_log_remote_cert_name_mismatch);
}
if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateChainErrors) != 0)
{
foreach (X509ChainStatus chainStatus in chain.ChainStatus)
{
Logging.PrintInfo(Logging.Web, this, "\t" + chainStatus.StatusInformation);
}
}
}
if (success)
{
if (remoteCertValidationCallback != null)
{
Logging.PrintInfo(Logging.Web, this, SR.net_log_remote_cert_user_declared_valid);
}
else
{
Logging.PrintInfo(Logging.Web, this, SR.net_log_remote_cert_has_no_errors);
}
}
else
{
if (remoteCertValidationCallback != null)
{
Logging.PrintInfo(Logging.Web, this, SR.net_log_remote_cert_user_declared_invalid);
}
}
}
GlobalLog.Print("Cert Validation, remote cert = " + (remoteCertificateEx == null ? "<null>" : remoteCertificateEx.ToString(true)));
}
finally
{
// At least on Win2k server the chain is found to have dependencies on the original cert context.
// So it should be closed first.
if (chain != null)
{
chain.Dispose();
}
if (remoteCertificateEx != null)
{
remoteCertificateEx.Dispose();
}
}
GlobalLog.Leave("SecureChannel#" + Logging.HashString(this) + "::VerifyRemoteCertificate", success.ToString());
return success;
}
}
//
// ProtocolToken - used to process and handle the return codes
// from the SSPI wrapper
//
internal class ProtocolToken
{
internal SecurityStatus Status;
internal byte[] Payload;
internal int Size;
internal bool Failed
{
get
{
return ((Status != SecurityStatus.OK) && (Status != SecurityStatus.ContinueNeeded));
}
}
internal bool Done
{
get
{
return (Status == SecurityStatus.OK);
}
}
internal bool Renegotiate
{
get
{
return (Status == SecurityStatus.Renegotiate);
}
}
internal bool CloseConnection
{
get
{
return (Status == SecurityStatus.ContextExpired);
}
}
internal ProtocolToken(byte[] data, SecurityStatus errorCode)
{
Status = errorCode;
Payload = data;
Size = data != null ? data.Length : 0;
}
internal Exception GetException()
{
// If it's not done, then there's got to be an error, even if it's
// a Handshake message up, and we only have a Warning message.
return this.Done ? null : SSPIWrapper.GetException(GlobalSSPI.SSPISecureChannel, Status);
}
#if TRACE_VERBOSE
public override string ToString()
{
return "Status=" + Status.ToString() + ", data size=" + Size;
}
#endif
}
}
| |
/*
This file is derived off ELMAH:
http://code.google.com/p/elmah/
http://www.apache.org/licenses/LICENSE-2.0
*/
namespace SimpleErrorHandler
{
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Mail;
using NameValueCollection = System.Collections.Specialized.NameValueCollection;
using Comparer = System.Collections.Comparer;
using StringWriter = System.IO.StringWriter;
using System.Text.RegularExpressions;
/// <summary>
/// Renders an HTML page displaying details about an error from the error log.
/// </summary>
internal sealed class ErrorDetailPage : ErrorPageBase
{
private ErrorLogEntry _errorEntry;
protected override void OnLoad(EventArgs e)
{
string errorId = this.Request.QueryString["id"] ?? "";
if (errorId.Length == 0) return;
_errorEntry = this.ErrorLog.GetError(errorId);
if (_errorEntry == null) return;
this.Title = string.Format("Error: {0} [{1}]", _errorEntry.Error.Type, _errorEntry.Id);
base.OnLoad(e);
}
protected override void RenderHead(HtmlTextWriter w)
{
base.RenderHead(w);
}
protected override void RenderContents(HtmlTextWriter w)
{
if (_errorEntry != null)
{
RenderError(w);
}
else
{
RenderNoError(w);
}
}
private void RenderNoError(HtmlTextWriter w)
{
w.RenderBeginTag(HtmlTextWriterTag.P);
w.Write("Error not found in log.");
w.RenderEndTag(); // </p>
w.WriteLine();
}
private void RenderError(HtmlTextWriter w)
{
Error error = _errorEntry.Error;
if (error.WebHostHtmlMessage.Length != 0)
{
w.Write(@"<div id=""error-view"">");
string htmlUrl = this.BasePageName + "/html?id=" + _errorEntry.Id;
w.Write(String.Format(@"<a href=""{0}"" title="""">view original error message (as seen by user)</a>", htmlUrl));
w.Write("</div>");
}
w.AddAttribute(HtmlTextWriterAttribute.Id, "PageTitle");
w.RenderBeginTag(HtmlTextWriterTag.P);
Server.HtmlEncode(error.Message, w);
w.RenderEndTag(); // </p>
w.WriteLine();
w.AddAttribute(HtmlTextWriterAttribute.Id, "ErrorTitle");
w.RenderBeginTag(HtmlTextWriterTag.P);
w.AddAttribute(HtmlTextWriterAttribute.Id, "ErrorType");
w.RenderBeginTag(HtmlTextWriterTag.Span);
Server.HtmlEncode(error.Type, w);
w.RenderEndTag(); // </span>
w.AddAttribute(HtmlTextWriterAttribute.Id, "ErrorTypeMessageSeparator");
w.RenderBeginTag(HtmlTextWriterTag.Span);
w.Write(": ");
w.RenderEndTag(); // </span>
//w.AddAttribute(HtmlTextWriterAttribute.Id, "ErrorMessage");
//w.RenderBeginTag(HtmlTextWriterTag.Span);
//Server.HtmlEncode(error.Message, w);
//w.RenderEndTag(); // </span>
w.RenderEndTag(); // </p>
w.WriteLine();
// Do we have details, like the stack trace? If so, then write
// them out in a pre-formatted (pre) element.
if (error.Detail.Length != 0)
{
w.AddAttribute(HtmlTextWriterAttribute.Id, "ErrorDetail");
w.RenderBeginTag(HtmlTextWriterTag.Pre);
w.Flush();
Server.HtmlEncode(error.Detail, w.InnerWriter);
w.RenderEndTag(); // </pre>
w.WriteLine();
}
// Write out the error log time, in local server time
w.AddAttribute(HtmlTextWriterAttribute.Id, "ErrorLogTime");
w.RenderBeginTag(HtmlTextWriterTag.P);
w.Write(string.Format(@"occurred <b>{2}</b> on {0} at {1}",
error.Time.ToLongDateString(),
error.Time.ToLongTimeString(), error.Time.ToRelativeTime()), w);
w.RenderEndTag(); // </p>
w.WriteLine();
// If this error has context, then write it out.
RenderCollection(w, error.ServerVariables, "ServerVariables", "Server Variables");
RenderCollection(w, error.Form, "Form", "Form");
RenderCollection(w, error.Cookies, "Cookies", "Cookies");
RenderCollection(w, error.QueryString, "QueryString", "QueryString");
base.RenderContents(w);
}
private string PrepareCell(string s)
{
if (Regex.IsMatch(s, @"%[A-Z0-9][A-Z0-9]"))
{
s = Server.UrlDecode(s);
}
if (Regex.IsMatch(s, "^(https?|ftp|file)://"))
{
return Regex.Replace(s, @"((?:https?|ftp|file)://.*)", @"<a href=""$1"">$1</a>");
}
if (Regex.IsMatch(s, "/[^ /,]+/"))
{
// block special case of "/LM/W3SVC/1"
if (!s.Contains("/LM"))
{
return Regex.Replace(s, @"(.*)", @"<a href=""$1"">$1</a>");
}
}
return Server.HtmlEncode(s);
}
private string _hidden_keys = "|ALL_HTTP|ALL_RAW|HTTP_COOKIE|HTTP_CONTENT_LENGTH|HTTP_CONTENT_TYPE|QUERY_STRING|";
private string _unimportant_keys = "|HTTP_ACCEPT_ENCODING|HTTP_ACCEPT_LANGUAGE|HTTP_CONNECTION|HTTP_HOST|HTTP_KEEP_ALIVE|PATH_TRANSLATED|SERVER_NAME|SERVER_PORT|SERVER_PORT_SECURE|SERVER_PROTOCOL|HTTP_ACCEPT|HTTP_ACCEPT_CHARSET|APPL_PHYSICAL_PATH|GATEWAY_INTERFACE|HTTPS|INSTANCE_ID|INSTANCE_META_PATH|SERVER_SOFTWARE|APPL_MD_PATH|PATH_INFO|SCRIPT_NAME|REMOTE_PORT|";
private void RenderCollection(HtmlTextWriter w, NameValueCollection c, string id, string title)
{
if (c == null || c.Count == 0) return;
w.AddAttribute(HtmlTextWriterAttribute.Id, id);
w.RenderBeginTag(HtmlTextWriterTag.Div);
w.AddAttribute(HtmlTextWriterAttribute.Class, "table-caption");
w.RenderBeginTag(HtmlTextWriterTag.P);
this.Server.HtmlEncode(title, w);
w.RenderEndTag(); // </p>
w.WriteLine();
w.AddAttribute(HtmlTextWriterAttribute.Class, "scroll-view");
w.RenderBeginTag(HtmlTextWriterTag.Div);
Table table = new Table();
table.CellSpacing = 0;
string[] keys = c.AllKeys;
Array.Sort(keys, Comparer.DefaultInvariant);
int i = 0;
foreach (var key in keys)
{
string value = c[key];
if (!String.IsNullOrEmpty(value) && !IsHidden(key))
{
bool unimportant = IsUnimportant(key);
string matchingKeys = "";
if (!unimportant)
{
matchingKeys = GetMatchingKeys(c, value);
if (matchingKeys != null)
{
_hidden_keys += matchingKeys.Replace(", ", "|") + "|";
}
}
TableRow bodyRow = new TableRow();
if (unimportant)
bodyRow.CssClass = "unimportant-row";
else
{
i++;
bodyRow.CssClass = i % 2 == 0 ? "even-row" : "odd-row";
}
TableCell cell;
// key
cell = new TableCell();
if (!String.IsNullOrEmpty(matchingKeys))
cell.Text = Server.HtmlEncode(matchingKeys);
else
cell.Text = Server.HtmlEncode(key);
cell.CssClass = "key-col";
bodyRow.Cells.Add(cell);
// value
cell = new TableCell();
cell.Text = PrepareCell(value);
cell.CssClass = "value-col";
bodyRow.Cells.Add(cell);
table.Rows.Add(bodyRow);
}
}
table.RenderControl(w);
w.RenderEndTag(); // </div>
w.WriteLine();
w.RenderEndTag(); // </div>
w.WriteLine();
}
/// <summary>
/// returns true of the target is contained in the list;
/// presumes list is pipe delimited like |apples|oranges|pears|
/// </summary>
private bool Matches(string list, string target)
{
return list.Contains("|" + target + "|");
}
private bool IsUnimportant(string key)
{
return Matches(_unimportant_keys, key);
}
private bool IsHidden(string key)
{
return Matches(_hidden_keys, key);
}
private string GetMatchingKeys(NameValueCollection nvc, string s)
{
string matchingKeys = "";
int matches = 0;
foreach (string key in nvc.Keys)
{
if (nvc[key] == s && !IsUnimportant(key) && !IsHidden(key))
{
matches++;
matchingKeys += key + ", ";
}
}
if (matches == 1)
return null;
else
return matchingKeys.Substring(0, matchingKeys.Length - 2);
}
}
}
| |
// 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.Collections.Immutable;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Navigation;
using Microsoft.CodeAnalysis.Options;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.GoToDefinition
{
internal static class GoToDefinitionHelpers
{
public static bool TryGoToDefinition(
ISymbol symbol,
Project project,
IEnumerable<Lazy<INavigableDefinitionProvider>> externalDefinitionProviders,
IEnumerable<Lazy<INavigableItemsPresenter>> presenters,
CancellationToken cancellationToken,
bool thirdPartyNavigationAllowed = true,
bool throwOnHiddenDefinition = false)
{
var alias = symbol as IAliasSymbol;
if (alias != null)
{
var ns = alias.Target as INamespaceSymbol;
if (ns != null && ns.IsGlobalNamespace)
{
return false;
}
}
// VB global import aliases have a synthesized SyntaxTree.
// We can't go to the definition of the alias, so use the target type.
var solution = project.Solution;
if (symbol is IAliasSymbol &&
NavigableItemFactory.GetPreferredSourceLocations(solution, symbol).All(l => project.Solution.GetDocument(l.SourceTree) == null))
{
symbol = ((IAliasSymbol)symbol).Target;
}
var definition = SymbolFinder.FindSourceDefinitionAsync(symbol, solution, cancellationToken).WaitAndGetResult(cancellationToken);
cancellationToken.ThrowIfCancellationRequested();
symbol = definition ?? symbol;
if (thirdPartyNavigationAllowed && TryThirdPartyNavigation(symbol, solution))
{
return true;
}
// If it is a partial method declaration with no body, choose to go to the implementation
// that has a method body.
if (symbol is IMethodSymbol)
{
symbol = ((IMethodSymbol)symbol).PartialImplementationPart ?? symbol;
}
var options = project.Solution.Options;
var preferredSourceLocations = NavigableItemFactory.GetPreferredSourceLocations(solution, symbol).ToArray();
var displayParts = NavigableItemFactory.GetSymbolDisplayTaggedParts(project, symbol);
var title = displayParts.JoinText();
if (!preferredSourceLocations.Any())
{
// Attempt to find source locations from external definition providers.
if (thirdPartyNavigationAllowed && externalDefinitionProviders.Any())
{
var externalSourceDefinitions = FindExternalDefinitionsAsync(symbol, project, externalDefinitionProviders, cancellationToken).WaitAndGetResult(cancellationToken).ToImmutableArray();
if (externalSourceDefinitions.Length > 0)
{
return TryGoToDefinition(externalSourceDefinitions, title, options, presenters, throwOnHiddenDefinition);
}
}
// If there are no visible source locations, then tell the host about the symbol and
// allow it to navigate to it. This will either navigate to any non-visible source
// locations, or it can appropriately deal with metadata symbols for hosts that can go
// to a metadata-as-source view.
var symbolNavigationService = solution.Workspace.Services.GetService<ISymbolNavigationService>();
return symbolNavigationService.TryNavigateToSymbol(
symbol, project,
options: options.WithChangedOption(NavigationOptions.PreferProvisionalTab, true),
cancellationToken: cancellationToken);
}
var navigableItems = preferredSourceLocations.Select(location =>
NavigableItemFactory.GetItemFromSymbolLocation(
solution, symbol, location,
displayTaggedParts: null)).ToImmutableArray();
return TryGoToDefinition(navigableItems, title, options, presenters, throwOnHiddenDefinition);
}
private static bool TryGoToDefinition(
ImmutableArray<INavigableItem> navigableItems,
string title,
OptionSet options,
IEnumerable<Lazy<INavigableItemsPresenter>> presenters,
bool throwOnHiddenDefinition)
{
Contract.ThrowIfNull(options);
// If we have a single location, then just navigate to it.
if (navigableItems.Length == 1 && navigableItems[0].Document != null)
{
var firstItem = navigableItems[0];
var workspace = firstItem.Document.Project.Solution.Workspace;
var navigationService = workspace.Services.GetService<IDocumentNavigationService>();
if (navigationService.CanNavigateToSpan(workspace, firstItem.Document.Id, firstItem.SourceSpan))
{
return navigationService.TryNavigateToSpan(
workspace,
documentId: firstItem.Document.Id,
textSpan: firstItem.SourceSpan,
options: options.WithChangedOption(NavigationOptions.PreferProvisionalTab, true));
}
else
{
if (throwOnHiddenDefinition)
{
const int E_FAIL = -2147467259;
throw new COMException(EditorFeaturesResources.The_definition_of_the_object_is_hidden, E_FAIL);
}
else
{
return false;
}
}
}
else
{
// We have multiple viable source locations, so ask the host what to do. Most hosts
// will simply display the results to the user and allow them to choose where to
// go.
if (presenters.Any())
{
presenters.First().Value.DisplayResult(title, navigableItems);
return true;
}
return false;
}
}
public static async Task<IEnumerable<INavigableItem>> FindExternalDefinitionsAsync(Document document, int position, IEnumerable<Lazy<INavigableDefinitionProvider>> externalDefinitionProviders, CancellationToken cancellationToken)
{
foreach (var definitionProvider in externalDefinitionProviders)
{
var definitions = await definitionProvider.Value.FindDefinitionsAsync(document, position, cancellationToken).ConfigureAwait(false);
if (definitions != null && definitions.Any())
{
var preferredDefinitions = NavigableItemFactory.GetPreferredNavigableItems(document.Project.Solution, definitions);
if (preferredDefinitions.Any())
{
return preferredDefinitions;
}
}
}
return SpecializedCollections.EmptyEnumerable<INavigableItem>();
}
public static async Task<IEnumerable<INavigableItem>> FindExternalDefinitionsAsync(ISymbol symbol, Project project, IEnumerable<Lazy<INavigableDefinitionProvider>> externalDefinitionProviders, CancellationToken cancellationToken)
{
foreach (var definitionProvider in externalDefinitionProviders)
{
var definitions = await definitionProvider.Value.FindDefinitionsAsync(project, symbol, cancellationToken).ConfigureAwait(false);
if (definitions != null && definitions.Any())
{
var preferredDefinitions = NavigableItemFactory.GetPreferredNavigableItems(project.Solution, definitions);
if (preferredDefinitions.Any())
{
return preferredDefinitions;
}
}
}
return SpecializedCollections.EmptyEnumerable<INavigableItem>();
}
public static bool TryExternalGoToDefinition(Document document, int position, IEnumerable<Lazy<INavigableDefinitionProvider>> externalDefinitionProviders, IEnumerable<Lazy<INavigableItemsPresenter>> presenters, CancellationToken cancellationToken)
{
var externalDefinitions = FindExternalDefinitionsAsync(document, position, externalDefinitionProviders, cancellationToken).WaitAndGetResult(cancellationToken);
if (externalDefinitions != null && externalDefinitions.Any())
{
var itemsArray = externalDefinitions.ToImmutableArrayOrEmpty();
var title = itemsArray[0].DisplayTaggedParts.JoinText();
return TryGoToDefinition(externalDefinitions.ToImmutableArrayOrEmpty(), title, document.Project.Solution.Workspace.Options, presenters, throwOnHiddenDefinition: true);
}
return false;
}
private static bool TryThirdPartyNavigation(ISymbol symbol, Solution solution)
{
var symbolNavigationService = solution.Workspace.Services.GetService<ISymbolNavigationService>();
// Notify of navigation so third parties can intercept the navigation
return symbolNavigationService.TrySymbolNavigationNotify(symbol, solution);
}
}
}
| |
using System.Diagnostics;
namespace Community.CsharpSqlite
{
using sqlite3_stmt = Sqlite3.Vdbe;
public partial class Sqlite3
{
/*
** 2007 May 1
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
**
** This file contains code used to implement incremental BLOB I/O.
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2010-03-09 19:31:43 4ae453ea7be69018d8c16eb8dabe05617397dc4d
**
** $Header$
*************************************************************************
*/
//#include "sqliteInt.h"
//#include "vdbeInt.h"
#if !SQLITE_OMIT_INCRBLOB
/*
** Valid sqlite3_blob* handles point to Incrblob structures.
*/
typedef struct Incrblob Incrblob;
struct Incrblob {
int flags; /* Copy of "flags" passed to sqlite3_blob_open() */
int nByte; /* Size of open blob, in bytes */
int iOffset; /* Byte offset of blob in cursor data */
BtCursor *pCsr; /* Cursor pointing at blob row */
sqlite3_stmt *pStmt; /* Statement holding cursor open */
sqlite3 *db; /* The associated database */
};
/*
** Open a blob handle.
*/
int sqlite3_blob_open(
sqlite3* db, /* The database connection */
const char *zDb, /* The attached database containing the blob */
const char *zTable, /* The table containing the blob */
const char *zColumn, /* The column containing the blob */
sqlite_int64 iRow, /* The row containing the glob */
int flags, /* True -> read/write access, false -> read-only */
sqlite3_blob **ppBlob /* Handle for accessing the blob returned here */
){
int nAttempt = 0;
int iCol; /* Index of zColumn in row-record */
/* This VDBE program seeks a btree cursor to the identified
** db/table/row entry. The reason for using a vdbe program instead
** of writing code to use the b-tree layer directly is that the
** vdbe program will take advantage of the various transaction,
** locking and error handling infrastructure built into the vdbe.
**
** After seeking the cursor, the vdbe executes an OP_ResultRow.
** Code external to the Vdbe then "borrows" the b-tree cursor and
** uses it to implement the blob_read(), blob_write() and
** blob_bytes() functions.
**
** The sqlite3_blob_close() function finalizes the vdbe program,
** which closes the b-tree cursor and (possibly) commits the
** transaction.
*/
static const VdbeOpList openBlob[] = {
{OP_Transaction, 0, 0, 0}, /* 0: Start a transaction */
{OP_VerifyCookie, 0, 0, 0}, /* 1: Check the schema cookie */
{OP_TableLock, 0, 0, 0}, /* 2: Acquire a read or write lock */
/* One of the following two instructions is replaced by an OP_Noop. */
{OP_OpenRead, 0, 0, 0}, /* 3: Open cursor 0 for reading */
{OP_OpenWrite, 0, 0, 0}, /* 4: Open cursor 0 for read/write */
{OP_Variable, 1, 1, 1}, /* 5: Push the rowid to the stack */
{OP_NotExists, 0, 9, 1}, /* 6: Seek the cursor */
{OP_Column, 0, 0, 1}, /* 7 */
{OP_ResultRow, 1, 0, 0}, /* 8 */
{OP_Close, 0, 0, 0}, /* 9 */
{OP_Halt, 0, 0, 0}, /* 10 */
};
Vdbe *v = 0;
int rc = SQLITE_OK;
char *zErr = 0;
Table *pTab;
Parse *pParse;
*ppBlob = 0;
sqlite3_mutex_enter(db->mutex);
pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
if( pParse==0 ){
rc = SQLITE_NOMEM;
goto blob_open_out;
}
do {
memset(pParse, 0, sizeof(Parse));
pParse->db = db;
sqlite3BtreeEnterAll(db);
pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
if( pTab && IsVirtual(pTab) ){
pTab = 0;
sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
}
#if !SQLITE_OMIT_VIEW
if( pTab && pTab->pSelect ){
pTab = 0;
sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
}
#endif
if( !pTab ){
if( pParse->zErrMsg ){
sqlite3DbFree(db, zErr);
zErr = pParse->zErrMsg;
pParse->zErrMsg = 0;
}
rc = SQLITE_ERROR;
sqlite3BtreeLeaveAll(db);
goto blob_open_out;
}
/* Now search pTab for the exact column. */
for(iCol=0; iCol < pTab->nCol; iCol++) {
if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
break;
}
}
if( iCol==pTab->nCol ){
sqlite3DbFree(db, zErr);
zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
rc = SQLITE_ERROR;
sqlite3BtreeLeaveAll(db);
goto blob_open_out;
}
/* If the value is being opened for writing, check that the
** column is not indexed, and that it is not part of a foreign key.
** It is against the rules to open a column to which either of these
** descriptions applies for writing. */
if( flags ){
const char *zFault = 0;
Index *pIdx;
#if !SQLITE_OMIT_FOREIGN_KEY
if( db->flags&SQLITE_ForeignKeys ){
/* Check that the column is not part of an FK child key definition. It
** is not necessary to check if it is part of a parent key, as parent
** key columns must be indexed. The check below will pick up this
** case. */
FKey *pFKey;
for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
int j;
for(j=0; j<pFKey->nCol; j++){
if( pFKey->aCol[j].iFrom==iCol ){
zFault = "foreign key";
}
}
}
}
#endif
for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
int j;
for(j=0; j<pIdx->nColumn; j++){
if( pIdx->aiColumn[j]==iCol ){
zFault = "indexed";
}
}
}
if( zFault ){
sqlite3DbFree(db, zErr);
zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
rc = SQLITE_ERROR;
sqlite3BtreeLeaveAll(db);
goto blob_open_out;
}
}
v = sqlite3VdbeCreate(db);
if( v ){
int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
flags = !!flags; /* flags = (flags ? 1 : 0); */
/* Configure the OP_Transaction */
sqlite3VdbeChangeP1(v, 0, iDb);
sqlite3VdbeChangeP2(v, 0, flags);
/* Configure the OP_VerifyCookie */
sqlite3VdbeChangeP1(v, 1, iDb);
sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
/* Make sure a mutex is held on the table to be accessed */
sqlite3VdbeUsesBtree(v, iDb);
/* Configure the OP_TableLock instruction */
sqlite3VdbeChangeP1(v, 2, iDb);
sqlite3VdbeChangeP2(v, 2, pTab->tnum);
sqlite3VdbeChangeP3(v, 2, flags);
sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
/* Remove either the OP_OpenWrite or OpenRead. Set the P2
** parameter of the other to pTab->tnum. */
sqlite3VdbeChangeToNoop(v, 4 - flags, 1);
sqlite3VdbeChangeP2(v, 3 + flags, pTab->tnum);
sqlite3VdbeChangeP3(v, 3 + flags, iDb);
/* Configure the number of columns. Configure the cursor to
** think that the table has one more column than it really
** does. An OP_Column to retrieve this imaginary column will
** always return an SQL NULL. This is useful because it means
** we can invoke OP_Column to fill in the vdbe cursors type
** and offset cache without causing any IO.
*/
sqlite3VdbeChangeP4(v, 3+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
sqlite3VdbeChangeP2(v, 7, pTab->nCol);
if( !db->mallocFailed ){
sqlite3VdbeMakeReady(v, 1, 1, 1, 0, 0, 0);
}
}
sqlite3BtreeLeaveAll(db);
goto blob_open_out;
}
sqlite3_bind_int64((sqlite3_stmt *)v, 1, iRow);
rc = sqlite3_step((sqlite3_stmt *)v);
if( rc!=SQLITE_ROW ){
nAttempt++;
rc = sqlite3_finalize((sqlite3_stmt *)v);
sqlite3DbFree(db, zErr);
zErr = sqlite3MPrintf(db, sqlite3_errmsg(db));
v = 0;
}
} while( nAttempt<5 && rc==SQLITE_SCHEMA );
if( rc==SQLITE_ROW ){
/* The row-record has been opened successfully. Check that the
** column in question contains text or a blob. If it contains
** text, it is up to the caller to get the encoding right.
*/
Incrblob *pBlob;
u32 type = v->apCsr[0]->aType[iCol];
if( type<12 ){
sqlite3DbFree(db, zErr);
zErr = sqlite3MPrintf(db, "cannot open value of type %s",
type==0?"null": type==7?"real": "integer"
);
rc = SQLITE_ERROR;
goto blob_open_out;
}
pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
if( db->mallocFailed ){
sqlite3DbFree(db, ref pBlob);
goto blob_open_out;
}
pBlob->flags = flags;
pBlob->pCsr = v->apCsr[0]->pCursor;
sqlite3BtreeEnterCursor(pBlob->pCsr);
sqlite3BtreeCacheOverflow(pBlob->pCsr);
sqlite3BtreeLeaveCursor(pBlob->pCsr);
pBlob->pStmt = (sqlite3_stmt *)v;
pBlob->iOffset = v->apCsr[0]->aOffset[iCol];
pBlob->nByte = sqlite3VdbeSerialTypeLen(type);
pBlob->db = db;
*ppBlob = (sqlite3_blob *)pBlob;
rc = SQLITE_OK;
}else if( rc==SQLITE_OK ){
sqlite3DbFree(db, zErr);
zErr = sqlite3MPrintf(db, "no such rowid: %lld", iRow);
rc = SQLITE_ERROR;
}
blob_open_out:
if( v && (rc!=SQLITE_OK || db->mallocFailed) ){
sqlite3VdbeFinalize(v);
}
sqlite3Error(db, rc, zErr);
sqlite3DbFree(db, zErr);
sqlite3StackFree(db, pParse);
rc = sqlite3ApiExit(db, rc);
sqlite3_mutex_leave(db->mutex);
return rc;
}
/*
** Close a blob handle that was previously created using
** sqlite3_blob_open().
*/
int sqlite3_blob_close(sqlite3_blob *pBlob){
Incrblob *p = (Incrblob *)pBlob;
int rc;
sqlite3 *db;
if( p ){
db = p->db;
sqlite3_mutex_enter(db->mutex);
rc = sqlite3_finalize(p->pStmt);
sqlite3DbFree(db, ref p);
sqlite3_mutex_leave(db->mutex);
}else{
rc = SQLITE_OK;
}
return rc;
}
/*
** Perform a read or write operation on a blob
*/
static int blobReadWrite(
sqlite3_blob *pBlob,
void *z,
int n,
int iOffset,
int (*xCall)(BtCursor*, u32, u32, void*)
){
int rc;
Incrblob *p = (Incrblob *)pBlob;
Vdbe *v;
sqlite3 *db;
if( p==0 ) return SQLITE_MISUSE_BKPT();
db = p->db;
sqlite3_mutex_enter(db->mutex);
v = (Vdbe*)p->pStmt;
if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
/* Request is out of range. Return a transient error. */
rc = SQLITE_ERROR;
sqlite3Error(db, SQLITE_ERROR, 0);
} else if( v==0 ){
/* If there is no statement handle, then the blob-handle has
** already been invalidated. Return SQLITE_ABORT in this case.
*/
rc = SQLITE_ABORT;
}else{
/* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
** returned, clean-up the statement handle.
*/
assert( db == v->db );
sqlite3BtreeEnterCursor(p->pCsr);
rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
sqlite3BtreeLeaveCursor(p->pCsr);
if( rc==SQLITE_ABORT ){
sqlite3VdbeFinalize(v);
p->pStmt = 0;
}else{
db->errCode = rc;
v->rc = rc;
}
}
rc = sqlite3ApiExit(db, rc);
sqlite3_mutex_leave(db->mutex);
return rc;
}
/*
** Read data from a blob handle.
*/
int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
}
/*
** Write data to a blob handle.
*/
int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
}
/*
** Query a blob handle for the size of the data.
**
** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
** so no mutex is required for access.
*/
int sqlite3_blob_bytes(sqlite3_blob *pBlob){
Incrblob *p = (Incrblob *)pBlob;
return p ? p->nByte : 0;
}
#endif // * #if !SQLITE_OMIT_INCRBLOB */
}
}
| |
/**
The MIT License (MIT)
Copyright (c) 2014 Paul Hayes
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
**/
using UnityEngine;
using System;
using System.Collections.Generic;
using System.Reflection;
namespace AnimatorStateMachineLibrary
{
public class AnimatorStateMachineUtil : MonoBehaviour
{
private static Dictionary<Animator, List<AnimatorStateMachineUtil>> fsmUtilsByAnimator = new Dictionary<Animator, List<AnimatorStateMachineUtil>>();
public static AnimatorStateMachineUtil GetFSMUtilFromAnimator(Animator _animator) {
List<AnimatorStateMachineUtil> utils;
fsmUtilsByAnimator.TryGetValue(_animator, out utils);
return (utils != null && utils.Count > 0) ? utils[0] : null;
}
public static IList<AnimatorStateMachineUtil> GetFSMUtilsFromAnimator(Animator _animator) {
List<AnimatorStateMachineUtil> utils;
fsmUtilsByAnimator.TryGetValue(_animator, out utils);
return utils;
}
public bool autoUpdate = false;
[SerializeField] private Animator animator;
public Animator Animator {
get {
if (_animator == null) {
if (animator == null) {
_animator = GetComponent<Animator>();
}
else {
_animator = animator;
}
}
return _animator;
}
}
public bool verbose;
private Animator _animator;
private Dictionary<int, List<Action>> stateHashToUpdateMethod = new Dictionary<int, List<Action>>();
private Dictionary<int, List<Action>> stateHashToEnterMethod = new Dictionary<int, List<Action>>();
private Dictionary<int, List<Action>> stateHashToExitMethod = new Dictionary<int, List<Action>>();
private int[] _lastStateLayers;
void Awake() {
_lastStateLayers = new int[Animator.layerCount];
List<AnimatorStateMachineUtil> utils;
if (!fsmUtilsByAnimator.TryGetValue(Animator, out utils)) {
utils = new List<AnimatorStateMachineUtil>();
fsmUtilsByAnimator.Add(Animator, utils);
}
utils.Add(this);
DiscoverStateMethods();
}
void OnDestroy() {
List<AnimatorStateMachineUtil> utils;
if (fsmUtilsByAnimator.TryGetValue(Animator, out utils)) {
utils.Remove(this);
}
}
void Update() {
if (autoUpdate) {
StateMachineUpdate();
}
}
void OnValidate() {
DiscoverStateMethods();
}
public void CallEnterMethods(int _stateHash) {
List<Action> actions;
if (stateHashToEnterMethod.TryGetValue(_stateHash, out actions)) {
foreach (Action action in actions) {
action.Invoke();
}
}
}
public void CallUpdateMethods(int _stateHash) {
List<Action> actions;
if (stateHashToUpdateMethod.TryGetValue(_stateHash, out actions)) {
foreach (Action action in actions) {
action.Invoke();
}
}
}
public void CallExitMethod(int _stateHash) {
List<Action> actions;
if (stateHashToExitMethod.TryGetValue(_stateHash, out actions)) {
foreach (Action action in actions) {
action.Invoke();
}
}
}
public void StateMachineUpdate() {
for (int layer = 0; layer < _lastStateLayers.Length; layer++) {
int _lastState = _lastStateLayers[layer];
int stateId = Animator.GetCurrentAnimatorStateInfo(layer).fullPathHash;
if (_lastState != stateId) {
if (verbose) {
Debug.LogWarningFormat("State changed for layer {0}", layer);
}
CallExitMethod(_lastState);
CallEnterMethods(stateId);
}
CallUpdateMethods(stateId);
_lastStateLayers[layer] = stateId;
}
}
void DiscoverStateMethods() {
MonoBehaviour[] components = gameObject.GetComponents<MonoBehaviour>();
stateHashToUpdateMethod.Clear();
stateHashToEnterMethod.Clear();
stateHashToExitMethod.Clear();
foreach (MonoBehaviour component in components) {
if (component != null) {
Type type = component.GetType();
MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.InvokeMethod);
foreach (MethodInfo method in methods) {
object[] attributes;
attributes = method.GetCustomAttributes(typeof(StateUpdateMethodAttribute), true);
foreach (StateUpdateMethodAttribute attribute in attributes) {
ParameterInfo[] parameters = method.GetParameters();
if (parameters.Length == 0) {
AddStateMethod(stateHashToUpdateMethod, attribute.state, method, component);
}
}
attributes = method.GetCustomAttributes(typeof(StateEnterMethodAttribute), true);
foreach (StateEnterMethodAttribute attribute in attributes) {
ParameterInfo[] parameters = method.GetParameters();
if (parameters.Length == 0) {
AddStateMethod(stateHashToEnterMethod, attribute.state, method, component);
}
}
attributes = method.GetCustomAttributes(typeof(StateExitMethodAttribute), true);
foreach (StateExitMethodAttribute attribute in attributes) {
ParameterInfo[] parameters = method.GetParameters();
if (parameters.Length == 0) {
AddStateMethod(stateHashToExitMethod, attribute.state, method, component);
}
}
}
}
}
}
private void AddStateMethod(Dictionary<int, List<Action>> _dictionnary, string _state, MethodInfo _method, MonoBehaviour _component) {
int stateHash = Animator.StringToHash(_state);
List<Action> actions = null;
if (!_dictionnary.TryGetValue(stateHash, out actions)) {
actions = new List<Action>();
_dictionnary[stateHash] = actions;
}
actions.Add(() => {
_method.Invoke(_component, null);
});
}
}
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class StateUpdateMethodAttribute : Attribute
{
public string state;
public StateUpdateMethodAttribute(string state) {
this.state = state;
}
}
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class StateEnterMethodAttribute : Attribute
{
public string state;
public StateEnterMethodAttribute(string state) {
this.state = state;
}
}
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class StateExitMethodAttribute : Attribute
{
public string state;
public StateExitMethodAttribute(string state) {
this.state = state;
}
}
}
| |
/*******************************************************************************
* Copyright 2017 ROBOTIS CO., LTD.
*
* 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.
*******************************************************************************/
/* Author: Ryu Woon Jung (Leon) */
//
// ********* Multi Port Example *********
//
//
// Available Dynamixel model on this example : All models using Protocol 1.0
// This example is designed for using two Dynamixel MX-28, and two USB2DYNAMIXEL.
// To use another Dynamixel model, such as X series, see their details in E-Manual(emanual.robotis.com) and edit below variables yourself.
// Be sure that Dynamixel MX properties are already set as %% ID : 1 / Baudnum : 34 (Baudrate : 57600)
//
using System;
using System.Runtime.InteropServices;
using dynamixel_sdk;
namespace read_write
{
class ReadWrite
{
// Control table address
public const int ADDR_MX_TORQUE_ENABLE = 24; // Control table address is different in Dynamixel model
public const int ADDR_MX_GOAL_POSITION = 30;
public const int ADDR_MX_PRESENT_POSITION = 36;
// Protocol version
public const int PROTOCOL_VERSION = 1; // See which protocol version is used in the Dynamixel
// Default setting
public const int DXL1_ID = 1; // Dynamixel ID: 1
public const int DXL2_ID = 2; // Dynamixel ID: 2
public const int BAUDRATE = 57600;
public const string DEVICENAME1 = "COM1"; // Check which port is being used on your controller
public const string DEVICENAME2 = "COM2"; // ex) Windows: "COM1" Linux: "/dev/ttyUSB0" Mac: "/dev/tty.usbserial-*"
public const int TORQUE_ENABLE = 1; // Value for enabling the torque
public const int TORQUE_DISABLE = 0; // Value for disabling the torque
public const int DXL_MINIMUM_POSITION_VALUE = 100; // Dynamixel will rotate between this value
public const int DXL_MAXIMUM_POSITION_VALUE = 4000; // and this value (note that the Dynamixel would not move when the position value is out of movable range. Check e-manual about the range of the Dynamixel you use.)
public const int DXL_MOVING_STATUS_THRESHOLD = 10; // Dynamixel moving status threshold
public const byte ESC_ASCII_VALUE = 0x1b;
public const int COMM_SUCCESS = 0; // Communication Success result value
public const int COMM_TX_FAIL = -1001; // Communication Tx Failed
static void Main(string[] args)
{
// Initialize PortHandler Structs
// Set the port path
// Get methods and members of PortHandlerLinux or PortHandlerWindows
int port_num1 = dynamixel.portHandler(DEVICENAME1);
int port_num2 = dynamixel.portHandler(DEVICENAME2);
// Initialize PacketHandler Structs
dynamixel.packetHandler();
int index = 0;
int dxl_comm_result = COMM_TX_FAIL; // Communication result
UInt16[] dxl_goal_position = new UInt16[2]{ DXL_MINIMUM_POSITION_VALUE, DXL_MAXIMUM_POSITION_VALUE }; // Goal position
byte dxl_error = 0; // Dynamixel error
UInt16 dxl1_present_position = 0, dxl2_present_position = 0; // Present position
// Open port1
if (dynamixel.openPort(port_num1))
{
Console.WriteLine("Succeeded to open the port!");
}
else
{
Console.WriteLine("Failed to open the port!");
Console.WriteLine("Press any key to terminate...");
Console.ReadKey();
return;
}
// Open port2
if (dynamixel.openPort(port_num2))
{
Console.WriteLine("Succeeded to open the port!");
}
else
{
Console.WriteLine("Failed to open the port!");
Console.WriteLine("Press any key to terminate...");
Console.ReadKey();
return;
}
// Set port1 baudrate
if (dynamixel.setBaudRate(port_num1, BAUDRATE))
{
Console.WriteLine("Succeeded to change the baudrate!");
}
else
{
Console.WriteLine("Failed to change the baudrate!");
Console.WriteLine("Press any key to terminate...");
Console.ReadKey();
return;
}
// Set port2 baudrate
if (dynamixel.setBaudRate(port_num2, BAUDRATE))
{
Console.WriteLine("Succeeded to change the baudrate!");
}
else
{
Console.WriteLine("Failed to change the baudrate!");
Console.WriteLine("Press any key to terminate...");
Console.ReadKey();
return;
}
// Enable Dynamixel#1 Torque
dynamixel.write1ByteTxRx(port_num1, PROTOCOL_VERSION, DXL1_ID, ADDR_MX_TORQUE_ENABLE, TORQUE_ENABLE);
if ((dxl_comm_result = dynamixel.getLastTxRxResult(port_num1, PROTOCOL_VERSION)) != COMM_SUCCESS)
{
Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getTxRxResult(PROTOCOL_VERSION, dxl_comm_result)));
}
else if ((dxl_error = dynamixel.getLastRxPacketError(port_num1, PROTOCOL_VERSION)) != 0)
{
Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getRxPacketError(PROTOCOL_VERSION, dxl_error)));
}
else
{
Console.WriteLine("Dynamixel#{0} has been successfully connected ", DXL1_ID);
}
// Enable Dynamixel#2 Torque
dynamixel.write1ByteTxRx(port_num2, PROTOCOL_VERSION, DXL2_ID, ADDR_MX_TORQUE_ENABLE, TORQUE_ENABLE);
if ((dxl_comm_result = dynamixel.getLastTxRxResult(port_num2, PROTOCOL_VERSION)) != COMM_SUCCESS)
{
Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getTxRxResult(PROTOCOL_VERSION, dxl_comm_result)));
}
else if ((dxl_error = dynamixel.getLastRxPacketError(port_num2, PROTOCOL_VERSION)) != 0)
{
Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getRxPacketError(PROTOCOL_VERSION, dxl_error)));
}
else
{
Console.WriteLine("Dynamixel#{0} has been successfully connected ", DXL2_ID);
}
while (true)
{
Console.WriteLine("Press any key to continue! (or press ESC to quit!)");
if (Console.ReadKey().KeyChar == ESC_ASCII_VALUE)
break;
// Write Dynamixel#1 goal position
dynamixel.write2ByteTxRx(port_num1, PROTOCOL_VERSION, DXL1_ID, ADDR_MX_GOAL_POSITION, dxl_goal_position[index]);
if ((dxl_comm_result = dynamixel.getLastTxRxResult(port_num1, PROTOCOL_VERSION)) != COMM_SUCCESS)
{
Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getTxRxResult(PROTOCOL_VERSION, dxl_comm_result)));
}
else if ((dxl_error = dynamixel.getLastRxPacketError(port_num1, PROTOCOL_VERSION)) != 0)
{
Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getRxPacketError(PROTOCOL_VERSION, dxl_error)));
}
// Write Dynamixel#2 goal position
dynamixel.write2ByteTxRx(port_num2, PROTOCOL_VERSION, DXL2_ID, ADDR_MX_GOAL_POSITION, dxl_goal_position[index]);
if ((dxl_comm_result = dynamixel.getLastTxRxResult(port_num2, PROTOCOL_VERSION)) != COMM_SUCCESS)
{
Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getTxRxResult(PROTOCOL_VERSION, dxl_comm_result)));
}
else if ((dxl_error = dynamixel.getLastRxPacketError(port_num2, PROTOCOL_VERSION)) != 0)
{
Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getRxPacketError(PROTOCOL_VERSION, dxl_error)));
}
do
{
// Read Dynamixel#1 present position
dxl1_present_position = dynamixel.read2ByteTxRx(port_num1, PROTOCOL_VERSION, DXL1_ID, ADDR_MX_PRESENT_POSITION);
if ((dxl_comm_result = dynamixel.getLastTxRxResult(port_num1, PROTOCOL_VERSION)) != COMM_SUCCESS)
{
Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getTxRxResult(PROTOCOL_VERSION, dxl_comm_result)));
}
else if ((dxl_error = dynamixel.getLastRxPacketError(port_num1, PROTOCOL_VERSION)) != 0)
{
Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getRxPacketError(PROTOCOL_VERSION, dxl_error)));
}
// Read Dynamixel#2 present position
dxl2_present_position = dynamixel.read2ByteTxRx(port_num2, PROTOCOL_VERSION, DXL2_ID, ADDR_MX_PRESENT_POSITION);
if ((dxl_comm_result = dynamixel.getLastTxRxResult(port_num2, PROTOCOL_VERSION)) != COMM_SUCCESS)
{
Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getTxRxResult(PROTOCOL_VERSION, dxl_comm_result)));
}
else if ((dxl_error = dynamixel.getLastRxPacketError(port_num2, PROTOCOL_VERSION)) != 0)
{
Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getRxPacketError(PROTOCOL_VERSION, dxl_error)));
}
Console.WriteLine("[ID: {0}] GoalPos: {1} PresPos: {2} [ID: {3}] GoalPos: {4} PresPos: {5}", DXL1_ID, dxl_goal_position[index], dxl1_present_position, DXL2_ID, dxl_goal_position[index], dxl2_present_position);
} while ((Math.Abs(dxl_goal_position[index] - dxl1_present_position) > DXL_MOVING_STATUS_THRESHOLD) || (Math.Abs(dxl_goal_position[index] - dxl2_present_position) > DXL_MOVING_STATUS_THRESHOLD));
// Change goal position
if (index == 0)
{
index = 1;
}
else
{
index = 0;
}
}
// Disable Dynamixel#1 Torque
dynamixel.write1ByteTxRx(port_num1, PROTOCOL_VERSION, DXL1_ID, ADDR_MX_TORQUE_ENABLE, TORQUE_DISABLE);
if ((dxl_comm_result = dynamixel.getLastTxRxResult(port_num1, PROTOCOL_VERSION)) != COMM_SUCCESS)
{
Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getTxRxResult(PROTOCOL_VERSION, dxl_comm_result)));
}
else if ((dxl_error = dynamixel.getLastRxPacketError(port_num1, PROTOCOL_VERSION)) != 0)
{
Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getRxPacketError(PROTOCOL_VERSION, dxl_error)));
}
// Disable Dynamixel#2 Torque
dynamixel.write1ByteTxRx(port_num2, PROTOCOL_VERSION, DXL2_ID, ADDR_MX_TORQUE_ENABLE, TORQUE_DISABLE);
if ((dxl_comm_result = dynamixel.getLastTxRxResult(port_num2, PROTOCOL_VERSION)) != COMM_SUCCESS)
{
Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getTxRxResult(PROTOCOL_VERSION, dxl_comm_result)));
}
else if ((dxl_error = dynamixel.getLastRxPacketError(port_num2, PROTOCOL_VERSION)) != 0)
{
Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getRxPacketError(PROTOCOL_VERSION, dxl_error)));
}
// Close port1
dynamixel.closePort(port_num1);
// Close port2
dynamixel.closePort(port_num2);
return;
}
}
}
| |
/*
* TestUri.cs - Test class for "System.Uri"
*
* Copyright (C) 2002 Free Software Foundation, Inc.
*
* Contributed by Stephen Compall <[email protected]>
*
* 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
*/
using CSUnit;
using System;
/*
my sage (cough) advice to anyone writing unit tests...have a little
fun! Leave some little jokes to make future generations of hackers
chortle as they wait for their 2 second long build process to
complete.
*/
public class TestUri : TestCase
{
Uri rmsUri, pathEnding, noPathEnding;
const String rmsString
="ftp://[email protected]:2538/pub/gnu/?freesoftware=good";
const String guileDir= "http://www.gnu.org/software/../software/guile/";
const String guileFile= "http://www.gnu.org/software/../software/guile";
// Constructor.
public TestUri(String name) : base(name)
{
// Nothing to do here.
}
// Set up for the tests.
protected override void Setup()
{
this.rmsUri = new Uri(rmsString);
this.pathEnding = new Uri(guileDir);
this.noPathEnding = new Uri(guileFile);
}
// Clean up after the tests.
protected override void Cleanup()
{
// Nothing to do here.
}
public void TestUriConstructor()
{
String lasturi = null;
try // good constructors
{
new Uri(lasturi = rmsString);
new Uri(lasturi = guileDir);
new Uri(lasturi = guileFile);
new Uri(lasturi = "mailto:[email protected]");
new Uri(lasturi = "jabber:[email protected]/MyPresence");
}
catch (Exception)
{
Fail(lasturi.ToString()+" threw an exception it shouldn't have!");
}
}
public void TestUriCanonicalize()
{
AssertEquals("Should keep the ending slash when there is one",
"/software/guile/", pathEnding.AbsolutePath);
AssertEquals("Shouldn't have an ending slash when there isn't one",
"/software/guile",
noPathEnding.AbsolutePath);
}
public void TestUriCheckHostName()
{
AssertEquals("www.gnu.org is a DNS name",
UriHostNameType.Dns,
Uri.CheckHostName("www.gnu.org"));
AssertEquals("www.southern.-storm.com.au is not a DNS name",
UriHostNameType.Unknown,
Uri.CheckHostName("www.southern.-storm.com.au"));
AssertEquals("www.southern-storm.com.au is a DNS name",
UriHostNameType.Dns,
Uri.CheckHostName("www.southern-storm.com.au"));
AssertEquals("127.0.0.1 is an IPv4 address",
UriHostNameType.IPv4,
Uri.CheckHostName("127.0.0.1"));
AssertEquals(".63.64.201.1 is not an IPv4 address",
UriHostNameType.Unknown,
Uri.CheckHostName(".63.64.201.1"));
AssertEquals("207..211.18.4 is not an IPv4 address",
UriHostNameType.Unknown,
Uri.CheckHostName("207..211.18.4"));
// checking IPng
AssertEquals(":F0F0::0 should have bad IPng zerocompress at beginning",
UriHostNameType.Unknown,
Uri.CheckHostName(":F0F0::0"));
AssertEquals("::F0F0:0 allows fake zerocompress at beginning",
UriHostNameType.IPv6,
Uri.CheckHostName("::F0F0:0"));
AssertEquals("0:1:2:3:4:5:6:127.0.0.1 has too many elements",
UriHostNameType.Unknown,
Uri.CheckHostName("0:1:2:3:4:5:6:127.0.0.1"));
AssertEquals("0:1:2:3:4:5:127.0.0.1 has the right number of elements",
UriHostNameType.IPv6,
Uri.CheckHostName("0:1:2:3:4:5:127.0.0.1"));
}
public void TestUriCheckSchemeName()
{
Assert("Anr.7 is a scheme name",
Uri.CheckSchemeName("Anr.7"));
Assert("6thsense is not a scheme name",
!Uri.CheckSchemeName("6thsense"));
Assert("gnu+freedom-limits is a scheme name",
Uri.CheckSchemeName("gnu+freedom-limits"));
// that's GNU plus Freedom minus Limits
}
// TestUriCheckSecurity() is not necessary
// TODO
public void TestUriEquals()
{
}
// TODO
public void TestUriEscape()
{
}
// TODO
public void TestUriEscapeString()
{
}
// TODO
public void TestUriFromHex()
{
}
// TODO
public void TestUriGetHashCode()
{
}
// TODO
public void TestUriGetLeftPart()
{
}
// TODO
public void TestUriHexEscape()
{
}
// TODO
public void TestUriHexUnescape()
{
}
// TODO
public void TestUriIsBadFileSystemCharacter()
{
}
// TODO
public void TestUriIsExcludedCharacter()
{
}
public void TestUriIsHexDigit()
{
// gee, this is a hard one
Assert("C is a hex digit", Uri.IsHexDigit('C'));
Assert("9 is a hex digit", Uri.IsHexDigit('9'));
// incidentally, 0xC9 in binary is...11001001
Assert("f is a hex digit", Uri.IsHexDigit('f'));
Assert("G is not a hex digit", !Uri.IsHexDigit('G'));
Assert("\x00C9 is not a hex digit",
!Uri.IsHexDigit('\x00C9')); // I am one funny guy
Assert("\x20AC is not a hex digit (then again, neither is $)",
!Uri.IsHexDigit('\x20AC'));
// ok, classes like this don't really need all this testing ;)
}
public void TestUriIsHexEncoding()
{
Assert("\"%c9\", position 0, is hex encoding", Uri.IsHexEncoding("%c9", 0));
Assert("\"%c9\", position -1, is not hex encoding", !Uri.IsHexEncoding("%c9", -1));
Assert("\"0x%c9\", position 3, is not hex encoding", !Uri.IsHexEncoding("0x%c9", 3));
Assert("\"0x%c9\", position 2, is hex encoding", Uri.IsHexEncoding("0x%c9", 2));
Assert("\"%at\", position 0, is not hex encoding", !Uri.IsHexEncoding("%at", 0));
Assert("\"%af\", position 100, is not hex encoding", !Uri.IsHexEncoding("%af", 100));
}
// TODO
public void TestUriIsReservedCharacter()
{
}
public void TestUriMakeRelative()
{
Uri gnuphil = new Uri("http://www.gnu.org/philosophy/why-free.html");
Uri gnuoreilly = new Uri("http://www.gnu.org/gnu/thegnuproject.html");
Uri mozillaftp = new Uri("ftp://ftp.mozilla.org/pub/mozilla/latest/mozilla-i686-pc-linux-gnu-sea.tar.gz");
Uri mozillahttp = new Uri("http://ftp.mozilla.org/pub/mozilla/latest/mozilla-i686-pc-linux-gnu-sea.tar.gz");
Uri mandrake = new Uri("ftp://distro.ibiblio.org/pub/Linux/distributions/mandrake/Mandrake/iso/");
Uri debian = new Uri("ftp://distro.ibiblio.org/pub/Linux/distributions/debian/main/");
Uri debianrelease = new Uri("ftp://distro.ibiblio.org/pub/Linux/distributions/debian/main/source/Release");
AssertEquals(
"Code figures out simple relative Uri correctly (with files)",
gnuphil.MakeRelative(gnuoreilly),
"../gnu/thegnuproject.html");
AssertEquals("notices different schemes when comparing Uris",
mozillaftp.MakeRelative(mozillahttp),
mozillahttp.AbsoluteUri);
AssertEquals("figures out more complex, directory-based relative Uri",
mandrake.MakeRelative(debian),
"../../../debian/main/");
AssertEquals("tells difference between files and directorys, by looking for ending slash",
debianrelease.MakeRelative(debian), "../");
AssertEquals("correctly goes further into subdirectories",
debian.MakeRelative(debianrelease), "source/Release");
}
// Parse N/A
public void TestUriToString()
{
Uri uri=new Uri("http://dotgnu.org:80");
AssertEquals("Removing default ports from uris",
"http://dotgnu.org/",
uri.ToString());
uri = new Uri("mailto:developers:[email protected]");
AssertEquals("Passwords in the uris",
"mailto:developers:[email protected]",
uri.ToString());
}
// TODO
public void TestUriUnescape()
{
}
// TODO
public void TestUriAbsolutePath()
{
}
// TODO
public void TestUriAbsoluteUri()
{
}
public void TestUriAuthority()
{
AssertEquals("rmsUri: Authority built correctly", rmsUri.Authority, "[email protected]:2538");
}
// TODO
public void TestUriFragment()
{
}
public void TestUriHost()
{
AssertEquals("rmsUri: Host parsed", rmsUri.Host, "ftp.gnu.org");
}
public void TestUriHostNameType()
{
AssertEquals("rmsUri: Correct HostNameType detected", rmsUri.HostNameType, UriHostNameType.Dns);
}
public void TestUriIsDefaultPort()
{
Assert("rmsUri: 2538 is not default for ftp", !rmsUri.IsDefaultPort);
}
// TODO
public void TestUriIsFile()
{
}
// TODO
public void TestUriIsLoopback()
{
}
// TODO
public void TestUriLocalPath()
{
}
// TODO
public void TestUriPathAndQuery()
{
}
public void TestUriPort()
{
AssertEquals("rmsUri: Port parsed", rmsUri.Port, 2538);
}
public void TestUriQuery()
{
AssertEquals("rmsUri: Query parsed", rmsUri.Query, "?freesoftware=good");
}
public void TestUriScheme()
{
AssertEquals("rmsUri: Scheme parsed", rmsUri.Scheme, "ftp");
}
// TODO
public void TestUriUserEscaped()
{
}
public void TestUriUserInfo()
{
AssertEquals("rmsUri: User info parsed", rmsUri.UserInfo, "rms");
}
}
| |
// 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 Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class TypeNameFormatterTests : CSharpResultProviderTestBase
{
[Fact]
public void Primitives()
{
Assert.Equal("object", typeof(object).GetTypeName());
Assert.Equal("bool", typeof(bool).GetTypeName());
Assert.Equal("char", typeof(char).GetTypeName());
Assert.Equal("sbyte", typeof(sbyte).GetTypeName());
Assert.Equal("byte", typeof(byte).GetTypeName());
Assert.Equal("short", typeof(short).GetTypeName());
Assert.Equal("ushort", typeof(ushort).GetTypeName());
Assert.Equal("int", typeof(int).GetTypeName());
Assert.Equal("uint", typeof(uint).GetTypeName());
Assert.Equal("long", typeof(long).GetTypeName());
Assert.Equal("ulong", typeof(ulong).GetTypeName());
Assert.Equal("float", typeof(float).GetTypeName());
Assert.Equal("double", typeof(double).GetTypeName());
Assert.Equal("decimal", typeof(decimal).GetTypeName());
Assert.Equal("string", typeof(string).GetTypeName());
}
[Fact, WorkItem(1016796)]
public void NestedTypes()
{
var source = @"
public class A
{
public class B { }
}
namespace N
{
public class A
{
public class B { }
}
public class G1<T>
{
public class G2<T>
{
public class G3<U> { }
class G4<U, V> { }
}
}
}
";
var assembly = GetAssembly(source);
Assert.Equal("A", assembly.GetType("A").GetTypeName());
Assert.Equal("A.B", assembly.GetType("A+B").GetTypeName());
Assert.Equal("N.A", assembly.GetType("N.A").GetTypeName());
Assert.Equal("N.A.B", assembly.GetType("N.A+B").GetTypeName());
Assert.Equal("N.G1<int>.G2<float>.G3<double>", assembly.GetType("N.G1`1+G2`1+G3`1").MakeGenericType(typeof(int), typeof(float), typeof(double)).GetTypeName());
Assert.Equal("N.G1<int>.G2<float>.G4<double, ushort>", assembly.GetType("N.G1`1+G2`1+G4`2").MakeGenericType(typeof(int), typeof(float), typeof(double), typeof(ushort)).GetTypeName());
}
[Fact]
public void GenericTypes()
{
var source = @"
public class A
{
public class B { }
}
namespace N
{
public class C<T, U>
{
public class D<V, W>
{
}
}
}
";
var assembly = GetAssembly(source);
var typeA = assembly.GetType("A");
var typeB = typeA.GetNestedType("B");
var typeC = assembly.GetType("N.C`2");
var typeD = typeC.GetNestedType("D`2");
var typeInt = typeof(int);
var typeString = typeof(string);
var typeCIntString = typeC.MakeGenericType(typeInt, typeString);
Assert.Equal("N.C<T, U>", typeC.GetTypeName());
Assert.Equal("N.C<int, string>", typeCIntString.GetTypeName());
Assert.Equal("N.C<A, A.B>", typeC.MakeGenericType(typeA, typeB).GetTypeName());
Assert.Equal("N.C<int, string>.D<A, A.B>", typeD.MakeGenericType(typeInt, typeString, typeA, typeB).GetTypeName());
Assert.Equal("N.C<A, N.C<int, string>>.D<N.C<int, string>, A.B>", typeD.MakeGenericType(typeA, typeCIntString, typeCIntString, typeB).GetTypeName());
}
[Fact]
public void NonGenericInGeneric()
{
var source = @"
public class A<T>
{
public class B { }
}
";
var assembly = GetAssembly(source);
var typeA = assembly.GetType("A`1");
var typeB = typeA.GetNestedType("B");
Assert.Equal("A<int>.B", typeB.MakeGenericType(typeof(int)).GetTypeName());
}
[Fact]
public void PrimitiveNullableTypes()
{
Assert.Equal("int?", typeof(int?).GetTypeName());
Assert.Equal("bool?", typeof(bool?).GetTypeName());
}
[Fact]
public void NullableTypes()
{
var source = @"
namespace N
{
public struct A<T>
{
public struct B<U>
{
}
}
public struct C
{
}
}
";
var typeNullable = typeof(System.Nullable<>);
var assembly = GetAssembly(source);
var typeA = assembly.GetType("N.A`1");
var typeB = typeA.GetNestedType("B`1");
var typeC = assembly.GetType("N.C");
Assert.Equal("N.C?", typeNullable.MakeGenericType(typeC).GetTypeName());
Assert.Equal("N.A<N.C>?", typeNullable.MakeGenericType(typeA.MakeGenericType(typeC)).GetTypeName());
Assert.Equal("N.A<N.C>.B<N.C>?", typeNullable.MakeGenericType(typeB.MakeGenericType(typeC, typeC)).GetTypeName());
}
[Fact]
public void PrimitiveArrayTypes()
{
Assert.Equal("int[]", typeof(int[]).GetTypeName());
Assert.Equal("int[,]", typeof(int[,]).GetTypeName());
Assert.Equal("int[][,]", typeof(int[][,]).GetTypeName());
Assert.Equal("int[,][]", typeof(int[,][]).GetTypeName());
}
[Fact]
public void ArrayTypes()
{
var source = @"
namespace N
{
public class A<T>
{
public class B<U>
{
}
}
public class C
{
}
}
";
var assembly = GetAssembly(source);
var typeA = assembly.GetType("N.A`1");
var typeB = typeA.GetNestedType("B`1");
var typeC = assembly.GetType("N.C");
Assert.NotEqual(typeC.MakeArrayType(), typeC.MakeArrayType(1));
Assert.Equal("N.C[]", typeC.MakeArrayType().GetTypeName());
Assert.Equal("N.C[]", typeC.MakeArrayType(1).GetTypeName()); // NOTE: Multi-dimensional array that happens to exactly one dimension.
Assert.Equal("N.A<N.C>[,]", typeA.MakeGenericType(typeC).MakeArrayType(2).GetTypeName());
Assert.Equal("N.A<N.C[]>.B<N.C>[,,]", typeB.MakeGenericType(typeC.MakeArrayType(), typeC).MakeArrayType(3).GetTypeName());
}
[Fact]
public void CustomBoundsArrayTypes()
{
Array instance = Array.CreateInstance(typeof(int), new[] { 1, 2, 3, }, new[] { 4, 5, 6, });
Assert.Equal("int[,,]", instance.GetType().GetTypeName());
Assert.Equal("int[][,,]", instance.GetType().MakeArrayType().GetTypeName());
}
[Fact]
public void PrimitivePointerTypes()
{
Assert.Equal("int*", typeof(int).MakePointerType().GetTypeName());
Assert.Equal("int**", typeof(int).MakePointerType().MakePointerType().GetTypeName());
Assert.Equal("int*[]", typeof(int).MakePointerType().MakeArrayType().GetTypeName());
}
[Fact]
public void PointerTypes()
{
var source = @"
namespace N
{
public struct A<T>
{
public struct B<U>
{
}
}
public struct C
{
}
}
";
var assembly = GetAssembly(source);
var typeA = assembly.GetType("N.A`1");
var typeB = typeA.GetNestedType("B`1");
var typeC = assembly.GetType("N.C");
Assert.Equal("N.C*", typeC.MakePointerType().GetTypeName());
Assert.Equal("N.A<N.C>*", typeA.MakeGenericType(typeC).MakePointerType().GetTypeName());
Assert.Equal("N.A<N.C>.B<N.C>*", typeB.MakeGenericType(typeC, typeC).MakePointerType().GetTypeName());
}
[Fact]
public void Void()
{
Assert.Equal("void", typeof(void).GetTypeName());
Assert.Equal("void*", typeof(void).MakePointerType().GetTypeName());
}
[Fact]
public void KeywordIdentifiers()
{
var source = @"
public class @object
{
public class @true { }
}
namespace @return
{
public class @yield<@async>
{
public class @await { }
}
namespace @false
{
public class @null { }
}
}
";
var assembly = GetAssembly(source);
var objectType = assembly.GetType("object");
var trueType = objectType.GetNestedType("true");
var nullType = assembly.GetType("return.false.null");
var yieldType = assembly.GetType("return.yield`1");
var constructedYieldType = yieldType.MakeGenericType(nullType);
var awaitType = yieldType.GetNestedType("await");
var constructedAwaitType = awaitType.MakeGenericType(nullType);
Assert.Equal("object", objectType.GetTypeName(escapeKeywordIdentifiers: false));
Assert.Equal("object.true", trueType.GetTypeName(escapeKeywordIdentifiers: false));
Assert.Equal("return.false.null", nullType.GetTypeName(escapeKeywordIdentifiers: false));
Assert.Equal("return.yield<async>", yieldType.GetTypeName(escapeKeywordIdentifiers: false));
Assert.Equal("return.yield<return.false.null>", constructedYieldType.GetTypeName(escapeKeywordIdentifiers: false));
Assert.Equal("return.yield<return.false.null>.await", constructedAwaitType.GetTypeName(escapeKeywordIdentifiers: false));
Assert.Equal("@object", objectType.GetTypeName(escapeKeywordIdentifiers: true));
Assert.Equal("@object.@true", trueType.GetTypeName(escapeKeywordIdentifiers: true));
Assert.Equal("@return.@false.@null", nullType.GetTypeName(escapeKeywordIdentifiers: true));
Assert.Equal("@return.@yield<@async>", yieldType.GetTypeName(escapeKeywordIdentifiers: true));
Assert.Equal("@return.@yield<@return.@false.@null>", constructedYieldType.GetTypeName(escapeKeywordIdentifiers: true));
Assert.Equal("@return.@yield<@return.@false.@null>.@await", constructedAwaitType.GetTypeName(escapeKeywordIdentifiers: true));
}
}
}
| |
namespace Orleans.CodeGenerator
{
using System;
using System.CodeDom.Compiler;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Orleans.Async;
using Orleans.CodeGeneration;
using Orleans.Runtime;
using GrainInterfaceUtils = Orleans.CodeGeneration.GrainInterfaceUtils;
using SF = Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
/// <summary>
/// Implements a code generator using the Roslyn C# compiler.
/// </summary>
public class RoslynCodeGenerator : IRuntimeCodeGenerator, ISourceCodeGenerator, ICodeGeneratorCache
{
/// <summary>
/// The compiled assemblies.
/// </summary>
private static readonly ConcurrentDictionary<string, CachedAssembly> CompiledAssemblies =
new ConcurrentDictionary<string, CachedAssembly>();
/// <summary>
/// The logger.
/// </summary>
private static readonly Logger Logger = LogManager.GetLogger("CodeGenerator");
/// <summary>
/// The serializer generation manager.
/// </summary>
private static readonly SerializerGenerationManager SerializerGenerationManager = new SerializerGenerationManager();
/// <summary>
/// The generic interface types whose type arguments needs serializators generation
/// </summary>
private static readonly HashSet<Type> KnownGenericIntefaceTypes = new HashSet<Type>
{
typeof(Streams.IAsyncObserver<>),
typeof(Streams.IAsyncStream<>),
typeof(Streams.IAsyncObservable<>)
};
/// <summary>
/// The generic base types whose type arguments needs serializators generation
/// </summary>
private static readonly HashSet<Type> KnownGenericBaseTypes = new HashSet<Type>
{
typeof(Grain<>),
typeof(Streams.StreamSubscriptionHandleImpl<>),
typeof(Streams.StreamSubscriptionHandle<>)
};
/// <summary>
/// Adds a pre-generated assembly.
/// </summary>
/// <param name="targetAssemblyName">
/// The name of the assembly the provided <paramref name="generatedAssembly"/> targets.
/// </param>
/// <param name="generatedAssembly">
/// The generated assembly.
/// </param>
public void AddGeneratedAssembly(string targetAssemblyName, GeneratedAssembly generatedAssembly)
{
CompiledAssemblies.TryAdd(targetAssemblyName, new CachedAssembly(generatedAssembly));
}
/// <summary>
/// Generates code for all loaded assemblies and loads the output.
/// </summary>
public void GenerateAndLoadForAllAssemblies()
{
this.GenerateAndLoadForAssemblies(AppDomain.CurrentDomain.GetAssemblies());
}
/// <summary>
/// Generates and loads code for the specified inputs.
/// </summary>
/// <param name="inputs">The assemblies to generate code for.</param>
public void GenerateAndLoadForAssemblies(params Assembly[] inputs)
{
if (inputs == null)
{
throw new ArgumentNullException(nameof(inputs));
}
var timer = Stopwatch.StartNew();
var emitDebugSymbols = false;
foreach (var input in inputs)
{
if (!emitDebugSymbols)
{
emitDebugSymbols |= RuntimeVersion.IsAssemblyDebugBuild(input);
}
RegisterGeneratedCodeTargets(input);
TryLoadGeneratedAssemblyFromCache(input);
}
var grainAssemblies = inputs.Where(ShouldGenerateCodeForAssembly).ToList();
if (grainAssemblies.Count == 0)
{
// Already up to date.
return;
}
try
{
// Generate code for newly loaded assemblies.
var generatedSyntax = GenerateForAssemblies(grainAssemblies, true);
CachedAssembly generatedAssembly;
if (generatedSyntax.Syntax != null)
{
generatedAssembly = CompileAndLoad(generatedSyntax, emitDebugSymbols);
}
else
{
generatedAssembly = new CachedAssembly { Loaded = true };
}
foreach (var assembly in generatedSyntax.SourceAssemblies)
{
CompiledAssemblies.AddOrUpdate(
assembly.GetName().FullName,
generatedAssembly,
(_, __) => generatedAssembly);
}
if (Logger.IsVerbose2)
{
Logger.Verbose2(
ErrorCode.CodeGenCompilationSucceeded,
"Generated code for {0} assemblies in {1}ms",
generatedSyntax.SourceAssemblies.Count,
timer.ElapsedMilliseconds);
}
}
catch (Exception exception)
{
var assemblyNames = string.Join("\n", grainAssemblies.Select(_ => _.GetName().FullName));
var message =
$"Exception generating code for input assemblies:\n{assemblyNames}\nException: {LogFormatter.PrintException(exception)}";
Logger.Warn(ErrorCode.CodeGenCompilationFailed, message, exception);
throw;
}
}
/// <summary>
/// Ensures that code generation has been run for the provided assembly.
/// </summary>
/// <param name="input">
/// The assembly to generate code for.
/// </param>
public void GenerateAndLoadForAssembly(Assembly input)
{
try
{
RegisterGeneratedCodeTargets(input);
if (!ShouldGenerateCodeForAssembly(input))
{
TryLoadGeneratedAssemblyFromCache(input);
return;
}
var timer = Stopwatch.StartNew();
var generated = GenerateForAssemblies(new List<Assembly> { input }, true);
CachedAssembly generatedAssembly;
if (generated.Syntax != null)
{
var emitDebugSymbols = RuntimeVersion.IsAssemblyDebugBuild(input);
generatedAssembly = CompileAndLoad(generated, emitDebugSymbols);
}
else
{
generatedAssembly = new CachedAssembly { Loaded = true };
}
foreach (var assembly in generated.SourceAssemblies)
{
CompiledAssemblies.AddOrUpdate(
assembly.GetName().FullName,
generatedAssembly,
(_, __) => generatedAssembly);
}
if (Logger.IsVerbose2)
{
Logger.Verbose2(
ErrorCode.CodeGenCompilationSucceeded,
"Generated code for 1 assembly in {0}ms",
timer.ElapsedMilliseconds);
}
}
catch (Exception exception)
{
var message =
$"Exception generating code for input assembly {input.GetName().FullName}\nException: {LogFormatter.PrintException(exception)}";
Logger.Warn(ErrorCode.CodeGenCompilationFailed, message, exception);
throw;
}
}
/// <summary>
/// Generates source code for the provided assembly.
/// </summary>
/// <param name="input">
/// The assembly to generate source for.
/// </param>
/// <returns>
/// The generated source.
/// </returns>
public string GenerateSourceForAssembly(Assembly input)
{
RegisterGeneratedCodeTargets(input);
if (!ShouldGenerateCodeForAssembly(input))
{
return string.Empty;
}
var generated = GenerateForAssemblies(new List<Assembly> { input }, false);
if (generated.Syntax == null)
{
return string.Empty;
}
return CodeGeneratorCommon.GenerateSourceCode(CodeGeneratorCommon.AddGeneratedCodeAttribute(generated));
}
/// <summary>
/// Returns the collection of generated assemblies as pairs of target assembly name to raw assembly bytes.
/// </summary>
/// <returns>The collection of generated assemblies.</returns>
public IDictionary<string, GeneratedAssembly> GetGeneratedAssemblies()
{
return CompiledAssemblies.ToDictionary(_ => _.Key, _ => (GeneratedAssembly)_.Value);
}
/// <summary>
/// Attempts to load a generated assembly from the cache.
/// </summary>
/// <param name="targetAssembly">
/// The target assembly which the cached counterpart is generated for.
/// </param>
private static void TryLoadGeneratedAssemblyFromCache(Assembly targetAssembly)
{
CachedAssembly cached;
if (!CompiledAssemblies.TryGetValue(targetAssembly.GetName().FullName, out cached)
|| cached.RawBytes == null || cached.Loaded)
{
return;
}
// Load the assembly and mark it as being loaded.
Assembly.Load(cached.RawBytes, cached.DebugSymbolRawBytes);
cached.Loaded = true;
}
/// <summary>
/// Compiles the provided syntax tree, and loads and returns the result.
/// </summary>
/// <param name="generatedSyntax">The syntax tree.</param>
/// <param name="emitDebugSymbols">
/// Whether or not to emit debug symbols for the generated assembly.
/// </param>
/// <returns>The compilation output.</returns>
private static CachedAssembly CompileAndLoad(GeneratedSyntax generatedSyntax, bool emitDebugSymbols)
{
var generated = CodeGeneratorCommon.CompileAssembly(generatedSyntax, "OrleansCodeGen", emitDebugSymbols: emitDebugSymbols);
Assembly.Load(generated.RawBytes, generated.DebugSymbolRawBytes);
return new CachedAssembly(generated)
{
Loaded = true
};
}
/// <summary>
/// Generates a syntax tree for the provided assemblies.
/// </summary>
/// <param name="assemblies">The assemblies to generate code for.</param>
/// <param name="runtime">Whether or not runtime code generation is being performed.</param>
/// <returns>The generated syntax tree.</returns>
private static GeneratedSyntax GenerateForAssemblies(List<Assembly> assemblies, bool runtime)
{
if (Logger.IsVerbose)
{
Logger.Verbose(
"Generating code for assemblies: {0}",
string.Join(", ", assemblies.Select(_ => _.FullName)));
}
Assembly targetAssembly;
HashSet<Type> ignoredTypes;
if (runtime)
{
// Ignore types which have already been accounted for.
ignoredTypes = GetTypesWithGeneratedSupportClasses();
targetAssembly = null;
}
else
{
ignoredTypes = new HashSet<Type>();
targetAssembly = assemblies.FirstOrDefault();
}
var members = new List<MemberDeclarationSyntax>();
// Include assemblies which are marked as included.
var knownAssemblyAttributes = new Dictionary<Assembly, KnownAssemblyAttribute>();
var knownAssemblies = new HashSet<Assembly>();
foreach (var attribute in assemblies.SelectMany(asm => asm.GetCustomAttributes<KnownAssemblyAttribute>()))
{
knownAssemblyAttributes[attribute.Assembly] = attribute;
knownAssemblies.Add(attribute.Assembly);
}
if (knownAssemblies.Count > 0)
{
knownAssemblies.UnionWith(assemblies);
assemblies = knownAssemblies.ToList();
}
// Get types from assemblies which reference Orleans and are not generated assemblies.
var includedTypes = new HashSet<Type>();
for (var i = 0; i < assemblies.Count; i++)
{
var assembly = assemblies[i];
foreach (var attribute in assembly.GetCustomAttributes<ConsiderForCodeGenerationAttribute>())
{
ConsiderType(attribute.Type, runtime, targetAssembly, includedTypes, considerForSerialization: true);
if (attribute.ThrowOnFailure && !SerializerGenerationManager.IsTypeRecorded(attribute.Type))
{
throw new CodeGenerationException(
$"Found {attribute.GetType().Name} for type {attribute.Type.GetParseableName()}, but code"
+ " could not be generated. Ensure that the type is accessible.");
}
}
KnownAssemblyAttribute knownAssemblyAttribute;
var considerAllTypesForSerialization = knownAssemblyAttributes.TryGetValue(assembly, out knownAssemblyAttribute)
&& knownAssemblyAttribute.TreatTypesAsSerializable;
foreach (var type in TypeUtils.GetDefinedTypes(assembly, Logger))
{
var considerForSerialization = considerAllTypesForSerialization || type.GetTypeInfo().IsSerializable;
ConsiderType(type, runtime, targetAssembly, includedTypes, considerForSerialization);
}
}
includedTypes.RemoveWhere(_ => ignoredTypes.Contains(_));
// Group the types by namespace and generate the required code in each namespace.
foreach (var group in includedTypes.GroupBy(_ => CodeGeneratorCommon.GetGeneratedNamespace(_)))
{
var namespaceMembers = new List<MemberDeclarationSyntax>();
foreach (var type in group)
{
// The module containing the serializer.
var module = runtime ? null : type.GetTypeInfo().Module;
// Every type which is encountered must be considered for serialization.
Action<Type> onEncounteredType = encounteredType =>
{
// If a type was encountered which can be accessed, process it for serialization.
SerializerGenerationManager.RecordTypeToGenerate(encounteredType, module, targetAssembly);
};
if (Logger.IsVerbose2)
{
Logger.Verbose2("Generating code for: {0}", type.GetParseableName());
}
if (GrainInterfaceUtils.IsGrainInterface(type))
{
if (Logger.IsVerbose2)
{
Logger.Verbose2(
"Generating GrainReference and MethodInvoker for {0}",
type.GetParseableName());
}
GrainInterfaceUtils.ValidateInterfaceRules(type);
namespaceMembers.Add(GrainReferenceGenerator.GenerateClass(type, onEncounteredType));
namespaceMembers.Add(GrainMethodInvokerGenerator.GenerateClass(type));
}
// Generate serializers.
var first = true;
Type toGen;
while (SerializerGenerationManager.GetNextTypeToProcess(out toGen))
{
if (!runtime)
{
if (first)
{
ConsoleText.WriteStatus("ClientGenerator - Generating serializer classes for types:");
first = false;
}
ConsoleText.WriteStatus(
"\ttype " + toGen.FullName + " in namespace " + toGen.Namespace
+ " defined in Assembly " + toGen.Assembly.GetName());
}
if (Logger.IsVerbose2)
{
Logger.Verbose2(
"Generating & Registering Serializer for Type {0}",
toGen.GetParseableName());
}
namespaceMembers.AddRange(SerializerGenerator.GenerateClass(toGen, onEncounteredType));
}
}
if (namespaceMembers.Count == 0)
{
if (Logger.IsVerbose)
{
Logger.Verbose2("Skipping namespace: {0}", group.Key);
}
continue;
}
members.Add(
SF.NamespaceDeclaration(SF.ParseName(group.Key))
.AddUsings(
TypeUtils.GetNamespaces(typeof(TaskUtility), typeof(GrainExtensions), typeof(IntrospectionExtensions))
.Select(_ => SF.UsingDirective(SF.ParseName(_)))
.ToArray())
.AddMembers(namespaceMembers.ToArray()));
}
return new GeneratedSyntax
{
SourceAssemblies = assemblies,
Syntax = members.Count > 0 ? SF.CompilationUnit().AddMembers(members.ToArray()) : null
};
}
private static void ConsiderType(
Type type,
bool runtime,
Assembly targetAssembly,
ISet<Type> includedTypes,
bool considerForSerialization = false)
{
// The module containing the serializer.
var module = runtime || type.Assembly != targetAssembly ? null : type.Module;
var typeInfo = type.GetTypeInfo();
// If a type was encountered which can be accessed and is marked as [Serializable], process it for serialization.
if (considerForSerialization)
{
RecordType(type, module, targetAssembly, includedTypes);
}
ConsiderGenericBaseTypeArguments(typeInfo, module, targetAssembly, includedTypes);
ConsiderGenericInterfacesArguments(typeInfo, module, targetAssembly, includedTypes);
// Collect the types which require code generation.
if (GrainInterfaceUtils.IsGrainInterface(type))
{
if (Logger.IsVerbose2) Logger.Verbose2("Will generate code for: {0}", type.GetParseableName());
includedTypes.Add(type);
}
}
private static void RecordType(Type type, Module module, Assembly targetAssembly, ISet<Type> includedTypes)
{
if (SerializerGenerationManager.RecordTypeToGenerate(type, module, targetAssembly))
{
includedTypes.Add(type);
}
}
private static void ConsiderGenericBaseTypeArguments(
TypeInfo typeInfo,
Module module,
Assembly targetAssembly,
ISet<Type> includedTypes)
{
if (typeInfo.BaseType == null) return;
if (!typeInfo.BaseType.IsConstructedGenericType) return;
if (!KnownGenericBaseTypes.Contains(typeInfo.BaseType.GetGenericTypeDefinition())) return;
foreach (var type in typeInfo.BaseType.GetGenericArguments())
{
RecordType(type, module, targetAssembly, includedTypes);
}
}
private static void ConsiderGenericInterfacesArguments(
TypeInfo typeInfo,
Module module,
Assembly targetAssembly,
ISet<Type> includedTypes)
{
var interfaces = typeInfo.GetInterfaces().Where(x =>
x.IsConstructedGenericType
&& KnownGenericIntefaceTypes.Contains(x.GetGenericTypeDefinition()));
foreach (var type in interfaces.SelectMany(v => v.GetGenericArguments()))
{
RecordType(type, module, targetAssembly, includedTypes);
}
}
/// <summary>
/// Get types which have corresponding generated classes.
/// </summary>
/// <returns>Types which have corresponding generated classes marked.</returns>
private static HashSet<Type> GetTypesWithGeneratedSupportClasses()
{
// Get assemblies which contain generated code.
var all =
AppDomain.CurrentDomain.GetAssemblies()
.Where(assemblies => assemblies.GetCustomAttribute<GeneratedCodeAttribute>() != null)
.SelectMany(assembly => TypeUtils.GetDefinedTypes(assembly, Logger));
// Get all generated types in each assembly.
var attributes = all.SelectMany(_ => _.GetCustomAttributes<GeneratedAttribute>());
var results = new HashSet<Type>();
foreach (var attribute in attributes)
{
if (attribute.TargetType != null)
{
results.Add(attribute.TargetType);
}
}
return results;
}
/// <summary>
/// Returns a value indicating whether or not code should be generated for the provided assembly.
/// </summary>
/// <param name="assembly">The assembly.</param>
/// <returns>A value indicating whether or not code should be generated for the provided assembly.</returns>
private static bool ShouldGenerateCodeForAssembly(Assembly assembly)
{
return !assembly.IsDynamic && !CompiledAssemblies.ContainsKey(assembly.GetName().FullName)
&& TypeUtils.IsOrleansOrReferencesOrleans(assembly)
&& assembly.GetCustomAttribute<GeneratedCodeAttribute>() == null
&& assembly.GetCustomAttribute<SkipCodeGenerationAttribute>() == null;
}
/// <summary>
/// Registers the input assembly with this class.
/// </summary>
/// <param name="input">The assembly to register.</param>
private static void RegisterGeneratedCodeTargets(Assembly input)
{
var targets = input.GetCustomAttributes<OrleansCodeGenerationTargetAttribute>();
foreach (var target in targets)
{
CompiledAssemblies.TryAdd(target.AssemblyName, new CachedAssembly { Loaded = true });
}
}
[Serializable]
private class CachedAssembly : GeneratedAssembly
{
public CachedAssembly()
{
}
public CachedAssembly(GeneratedAssembly generated) : base(generated)
{
}
/// <summary>
/// Gets or sets a value indicating whether or not the assembly has been loaded.
/// </summary>
public bool Loaded { get; set; }
}
}
}
| |
// 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.Buffers;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Xunit;
namespace Microsoft.AspNetCore.WebUtilities
{
public class FileBufferingWriteStreamTests : IDisposable
{
private readonly string TempDirectory = Path.Combine(Path.GetTempPath(), "FileBufferingWriteTests", Path.GetRandomFileName());
public FileBufferingWriteStreamTests()
{
Directory.CreateDirectory(TempDirectory);
}
[Fact]
public void Write_BuffersContentToMemory()
{
// Arrange
using var bufferingStream = new FileBufferingWriteStream(tempFileDirectoryAccessor: () => TempDirectory);
var input = Encoding.UTF8.GetBytes("Hello world");
// Act
bufferingStream.Write(input, 0, input.Length);
// Assert
Assert.Equal(input.Length, bufferingStream.Length);
// We should have written content to memory
var pagedByteBuffer = bufferingStream.PagedByteBuffer;
Assert.Equal(input, ReadBufferedContent(pagedByteBuffer));
// No files should not have been created.
Assert.Null(bufferingStream.FileStream);
}
[Fact]
public void Write_BeforeMemoryThresholdIsReached_WritesToMemory()
{
// Arrange
var input = new byte[] { 1, 2, };
using var bufferingStream = new FileBufferingWriteStream(memoryThreshold: 2, tempFileDirectoryAccessor: () => TempDirectory);
// Act
bufferingStream.Write(input, 0, 2);
// Assert
var pageBuffer = bufferingStream.PagedByteBuffer;
var fileStream = bufferingStream.FileStream;
Assert.Equal(input.Length, bufferingStream.Length);
// File should have been created.
Assert.Null(fileStream);
// No content should be in the memory stream
Assert.Equal(2, pageBuffer.Length);
Assert.Equal(input, ReadBufferedContent(pageBuffer));
}
[Fact]
public void Write_BuffersContentToDisk_WhenMemoryThresholdIsReached()
{
// Arrange
var input = new byte[] { 1, 2, 3, };
using var bufferingStream = new FileBufferingWriteStream(memoryThreshold: 2, tempFileDirectoryAccessor: () => TempDirectory);
bufferingStream.Write(input, 0, 2);
// Act
bufferingStream.Write(input, 2, 1);
// Assert
var pageBuffer = bufferingStream.PagedByteBuffer;
var fileStream = bufferingStream.FileStream;
// File should have been created.
Assert.NotNull(fileStream);
var fileBytes = ReadFileContent(fileStream!);
Assert.Equal(input, fileBytes);
// No content should be in the memory stream
Assert.Equal(0, pageBuffer.Length);
}
[Fact]
public void Write_BuffersContentToDisk_WhenWriteWillOverflowMemoryThreshold()
{
// Arrange
var input = new byte[] { 1, 2, 3, };
using var bufferingStream = new FileBufferingWriteStream(memoryThreshold: 2, tempFileDirectoryAccessor: () => TempDirectory);
// Act
bufferingStream.Write(input, 0, input.Length);
// Assert
var pageBuffer = bufferingStream.PagedByteBuffer;
var fileStream = bufferingStream.FileStream;
// File should have been created.
Assert.NotNull(fileStream);
var fileBytes = ReadFileContent(fileStream!);
Assert.Equal(input, fileBytes);
// No content should be in the memory stream
Assert.Equal(0, pageBuffer.Length);
}
[Fact]
public void Write_AfterMemoryThresholdIsReached_BuffersToMemory()
{
// Arrange
var input = new byte[] { 1, 2, 3, 4, 5, 6, 7 };
using var bufferingStream = new FileBufferingWriteStream(memoryThreshold: 4, tempFileDirectoryAccessor: () => TempDirectory);
// Act
bufferingStream.Write(input, 0, 5);
bufferingStream.Write(input, 5, 2);
// Assert
var pageBuffer = bufferingStream.PagedByteBuffer;
var fileStream = bufferingStream.FileStream;
// File should have been created.
Assert.NotNull(fileStream);
var fileBytes = ReadFileContent(fileStream!);
Assert.Equal(new byte[] { 1, 2, 3, 4, 5, }, fileBytes);
Assert.Equal(new byte[] { 6, 7 }, ReadBufferedContent(pageBuffer));
}
[Fact]
public async Task WriteAsync_BuffersContentToMemory()
{
// Arrange
using var bufferingStream = new FileBufferingWriteStream(tempFileDirectoryAccessor: () => TempDirectory);
var input = Encoding.UTF8.GetBytes("Hello world");
// Act
await bufferingStream.WriteAsync(input, 0, input.Length);
// Assert
// We should have written content to memory
var pagedByteBuffer = bufferingStream.PagedByteBuffer;
Assert.Equal(input, ReadBufferedContent(pagedByteBuffer));
// No files should not have been created.
Assert.Null(bufferingStream.FileStream);
}
[Fact]
public async Task WriteAsync_BeforeMemoryThresholdIsReached_WritesToMemory()
{
// Arrange
var input = new byte[] { 1, 2, };
using var bufferingStream = new FileBufferingWriteStream(memoryThreshold: 2, tempFileDirectoryAccessor: () => TempDirectory);
// Act
await bufferingStream.WriteAsync(input, 0, 2);
// Assert
var pageBuffer = bufferingStream.PagedByteBuffer;
var fileStream = bufferingStream.FileStream;
// File should have been created.
Assert.Null(fileStream);
// No content should be in the memory stream
Assert.Equal(2, pageBuffer.Length);
Assert.Equal(input, ReadBufferedContent(pageBuffer));
}
[Fact]
public async Task WriteAsync_BuffersContentToDisk_WhenMemoryThresholdIsReached()
{
// Arrange
var input = new byte[] { 1, 2, 3, };
using var bufferingStream = new FileBufferingWriteStream(memoryThreshold: 2, tempFileDirectoryAccessor: () => TempDirectory);
bufferingStream.Write(input, 0, 2);
// Act
await bufferingStream.WriteAsync(input, 2, 1);
// Assert
var pageBuffer = bufferingStream.PagedByteBuffer;
var fileStream = bufferingStream.FileStream;
// File should have been created.
Assert.NotNull(fileStream);
var fileBytes = ReadFileContent(fileStream!);
Assert.Equal(input, fileBytes);
// No content should be in the memory stream
Assert.Equal(0, pageBuffer.Length);
}
[Fact]
public async Task WriteAsync_BuffersContentToDisk_WhenWriteWillOverflowMemoryThreshold()
{
// Arrange
var input = new byte[] { 1, 2, 3, };
using var bufferingStream = new FileBufferingWriteStream(memoryThreshold: 2, tempFileDirectoryAccessor: () => TempDirectory);
// Act
await bufferingStream.WriteAsync(input, 0, input.Length);
// Assert
var pageBuffer = bufferingStream.PagedByteBuffer;
var fileStream = bufferingStream.FileStream;
// File should have been created.
Assert.NotNull(fileStream);
var fileBytes = ReadFileContent(fileStream!);
Assert.Equal(input, fileBytes);
// No content should be in the memory stream
Assert.Equal(0, pageBuffer.Length);
}
[Fact]
public async Task WriteAsync_AfterMemoryThresholdIsReached_BuffersToMemory()
{
// Arrange
var input = new byte[] { 1, 2, 3, 4, 5, 6, 7 };
using var bufferingStream = new FileBufferingWriteStream(memoryThreshold: 4, tempFileDirectoryAccessor: () => TempDirectory);
// Act
await bufferingStream.WriteAsync(input, 0, 5);
await bufferingStream.WriteAsync(input, 5, 2);
// Assert
var pageBuffer = bufferingStream.PagedByteBuffer;
var fileStream = bufferingStream.FileStream;
// File should have been created.
Assert.NotNull(fileStream);
var fileBytes = ReadFileContent(fileStream!);
Assert.Equal(input.Length, bufferingStream.Length);
Assert.Equal(new byte[] { 1, 2, 3, 4, 5, }, fileBytes);
Assert.Equal(new byte[] { 6, 7 }, ReadBufferedContent(pageBuffer));
}
[Fact]
public void Write_Throws_IfSingleWriteExceedsBufferLimit()
{
// Arrange
var input = new byte[20];
var bufferingStream = new FileBufferingWriteStream(memoryThreshold: 2, bufferLimit: 10, tempFileDirectoryAccessor: () => TempDirectory);
// Act
var exception = Assert.Throws<IOException>(() => bufferingStream.Write(input, 0, input.Length));
Assert.Equal("Buffer limit exceeded.", exception.Message);
Assert.True(bufferingStream.Disposed);
}
[Fact]
public void Write_Throws_IfWriteCumulativeWritesExceedsBuffersLimit()
{
// Arrange
var input = new byte[6];
var bufferingStream = new FileBufferingWriteStream(memoryThreshold: 2, bufferLimit: 10, tempFileDirectoryAccessor: () => TempDirectory);
// Act
bufferingStream.Write(input, 0, input.Length);
var exception = Assert.Throws<IOException>(() => bufferingStream.Write(input, 0, input.Length));
Assert.Equal("Buffer limit exceeded.", exception.Message);
// Verify we return the buffer.
Assert.True(bufferingStream.Disposed);
}
[Fact]
public void Write_DoesNotThrow_IfBufferLimitIsReached()
{
// Arrange
var input = new byte[5];
using var bufferingStream = new FileBufferingWriteStream(memoryThreshold: 2, bufferLimit: 10, tempFileDirectoryAccessor: () => TempDirectory);
// Act
bufferingStream.Write(input, 0, input.Length);
bufferingStream.Write(input, 0, input.Length); // Should get to exactly the buffer limit, which is fine
// If we got here, the test succeeded.
}
[Fact]
public async Task WriteAsync_Throws_IfSingleWriteExceedsBufferLimit()
{
// Arrange
var input = new byte[20];
var bufferingStream = new FileBufferingWriteStream(memoryThreshold: 2, bufferLimit: 10, tempFileDirectoryAccessor: () => TempDirectory);
// Act
var exception = await Assert.ThrowsAsync<IOException>(() => bufferingStream.WriteAsync(input, 0, input.Length));
Assert.Equal("Buffer limit exceeded.", exception.Message);
Assert.True(bufferingStream.Disposed);
}
[Fact]
public async Task WriteAsync_Throws_IfWriteCumulativeWritesExceedsBuffersLimit()
{
// Arrange
var input = new byte[6];
var bufferingStream = new FileBufferingWriteStream(memoryThreshold: 2, bufferLimit: 10, tempFileDirectoryAccessor: () => TempDirectory);
// Act
await bufferingStream.WriteAsync(input, 0, input.Length);
var exception = await Assert.ThrowsAsync<IOException>(() => bufferingStream.WriteAsync(input, 0, input.Length));
Assert.Equal("Buffer limit exceeded.", exception.Message);
// Verify we return the buffer.
Assert.True(bufferingStream.Disposed);
}
[Fact]
public async Task WriteAsync_DoesNotThrow_IfBufferLimitIsReached()
{
// Arrange
var input = new byte[5];
using var bufferingStream = new FileBufferingWriteStream(memoryThreshold: 2, bufferLimit: 10, tempFileDirectoryAccessor: () => TempDirectory);
// Act
await bufferingStream.WriteAsync(input, 0, input.Length);
await bufferingStream.WriteAsync(input, 0, input.Length); // Should get to exactly the buffer limit, which is fine
// If we got here, the test succeeded.
}
[Fact]
public async Task DrainBufferAsync_CopiesContentFromMemoryStream()
{
// Arrange
var input = new byte[] { 1, 2, 3, 4, 5 };
using var bufferingStream = new FileBufferingWriteStream(tempFileDirectoryAccessor: () => TempDirectory);
bufferingStream.Write(input, 0, input.Length);
var memoryStream = new MemoryStream();
// Act
await bufferingStream.DrainBufferAsync(memoryStream, default);
// Assert
Assert.Equal(input, memoryStream.ToArray());
Assert.Equal(0, bufferingStream.Length);
}
[Fact]
public async Task DrainBufferAsync_WithContentInDisk_CopiesContentFromMemoryStream()
{
// Arrange
var input = Enumerable.Repeat((byte)0xca, 30).ToArray();
using var bufferingStream = new FileBufferingWriteStream(memoryThreshold: 21, tempFileDirectoryAccessor: () => TempDirectory);
bufferingStream.Write(input, 0, input.Length);
var memoryStream = new MemoryStream();
// Act
await bufferingStream.DrainBufferAsync(memoryStream, default);
// Assert
Assert.Equal(input, memoryStream.ToArray());
Assert.Equal(0, bufferingStream.Length);
}
public void Dispose()
{
try
{
Directory.Delete(TempDirectory, recursive: true);
}
catch
{
}
}
private static byte[] ReadFileContent(FileStream fileStream)
{
var fs = new FileStream(fileStream.Name, FileMode.Open, FileAccess.Read, FileShare.Delete | FileShare.ReadWrite);
using var memoryStream = new MemoryStream();
fs.CopyTo(memoryStream);
return memoryStream.ToArray();
}
private static byte[] ReadBufferedContent(PagedByteBuffer buffer)
{
using var memoryStream = new MemoryStream();
buffer.MoveTo(memoryStream);
return memoryStream.ToArray();
}
}
}
| |
#region License
// Copyright 2014 MorseCode Software
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
namespace MorseCode.RxMvvm.Observable.Property.Internal
{
using System;
using System.Diagnostics.Contracts;
using System.Reactive.Concurrency;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Runtime.Serialization;
using System.Security.Permissions;
using MorseCode.RxMvvm.Common;
using MorseCode.RxMvvm.Common.DiscriminatedUnion;
[Serializable]
internal class AsyncCalculatedProperty<TFirst, TSecond, T> : CalculatedPropertyBase<T>, ISerializable
{
#region Fields
private readonly IObservable<TFirst> firstProperty;
private readonly IObservable<TSecond> secondProperty;
private readonly TimeSpan throttleTime;
private readonly Func<TFirst, TSecond, T> calculateValue;
private readonly bool isLongRunningCalculation;
private IDisposable scheduledTask;
#endregion
#region Constructors and Destructors
internal AsyncCalculatedProperty(
IObservable<TFirst> firstProperty,
IObservable<TSecond> secondProperty,
TimeSpan throttleTime,
Func<TFirst, TSecond, T> calculateValue,
bool isLongRunningCalculation)
{
Contract.Requires<ArgumentNullException>(firstProperty != null, "firstProperty");
Contract.Requires<ArgumentNullException>(secondProperty != null, "secondProperty");
Contract.Requires<ArgumentNullException>(calculateValue != null, "calculateValue");
Contract.Ensures(this.firstProperty != null);
Contract.Ensures(this.secondProperty != null);
Contract.Ensures(this.calculateValue != null);
RxMvvmConfiguration.EnsureSerializableDelegateIfUsingSerialization(calculateValue);
this.firstProperty = firstProperty;
this.secondProperty = secondProperty;
this.throttleTime = throttleTime;
this.calculateValue = calculateValue;
this.isLongRunningCalculation = isLongRunningCalculation;
Func<TFirst, TSecond, IDiscriminatedUnion<object, T, Exception>> calculate = (first, second) =>
{
IDiscriminatedUnion<object, T, Exception> discriminatedUnion;
try
{
discriminatedUnion =
DiscriminatedUnion.First<object, T, Exception>(calculateValue(first, second));
}
catch (Exception e)
{
discriminatedUnion = DiscriminatedUnion.Second<object, T, Exception>(e);
}
return discriminatedUnion;
};
this.SetHelper(
new CalculatedPropertyHelper(
(resultSubject, isCalculatingSubject) =>
{
CompositeDisposable d = new CompositeDisposable();
IScheduler scheduler = isLongRunningCalculation
? RxMvvmConfiguration.GetLongRunningCalculationScheduler()
: RxMvvmConfiguration.GetCalculationScheduler();
IObservable<Tuple<TFirst, TSecond>> o = firstProperty.CombineLatest(
secondProperty, Tuple.Create);
o = throttleTime > TimeSpan.Zero
? o.Throttle(throttleTime, scheduler)
: o.ObserveOn(scheduler);
d.Add(
o.Subscribe(
v =>
{
using (this.scheduledTask)
{
}
isCalculatingSubject.OnNext(true);
this.scheduledTask = scheduler.ScheduleAsync(
async (s, t) =>
{
try
{
await s.Yield(t).ConfigureAwait(true);
IDiscriminatedUnion<object, T, Exception> result =
calculate(v.Item1, v.Item2);
await s.Yield(t).ConfigureAwait(true);
resultSubject.OnNext(result);
}
catch (OperationCanceledException)
{
}
catch (Exception e)
{
resultSubject.OnNext(
DiscriminatedUnion.Second<object, T, Exception>(e));
}
isCalculatingSubject.OnNext(false);
});
}));
return d;
}));
}
/// <summary>
/// Initializes a new instance of the <see cref="AsyncCalculatedProperty{TFirst,TSecond,T}"/> class.
/// </summary>
/// <param name="info">
/// The serialization info.
/// </param>
/// <param name="context">
/// The serialization context.
/// </param>
[ContractVerification(false)]
// ReSharper disable UnusedParameter.Local
protected AsyncCalculatedProperty(SerializationInfo info, StreamingContext context)
// ReSharper restore UnusedParameter.Local
: this(
(IObservable<TFirst>)info.GetValue("p1", typeof(IObservable<TFirst>)),
(IObservable<TSecond>)info.GetValue("p2", typeof(IObservable<TSecond>)),
(TimeSpan)(info.GetValue("t", typeof(TimeSpan)) ?? default(TimeSpan)),
(Func<TFirst, TSecond, T>)info.GetValue("f", typeof(Func<TFirst, TSecond, T>)),
(bool)info.GetValue("l", typeof(bool)))
{
}
#endregion
#region Public Methods and Operators
/// <summary>
/// Gets the object data to serialize.
/// </summary>
/// <param name="info">
/// The serialization info.
/// </param>
/// <param name="context">
/// The serialization context.
/// </param>
[SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("p1", this.firstProperty);
info.AddValue("p2", this.secondProperty);
info.AddValue("t", this.throttleTime);
info.AddValue("f", this.calculateValue);
info.AddValue("l", this.isLongRunningCalculation);
}
#endregion
#region Methods
/// <summary>
/// Disposes of the property.
/// </summary>
protected override void Dispose()
{
base.Dispose();
using (this.scheduledTask)
{
}
}
[ContractInvariantMethod]
private void CodeContractsInvariants()
{
Contract.Invariant(this.firstProperty != null);
Contract.Invariant(this.secondProperty != null);
Contract.Invariant(this.calculateValue != null);
}
#endregion
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Globalization;
#if !HAVE_LINQ
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
using Newtonsoft.Json.Serialization;
namespace Newtonsoft.Json.Utilities
{
internal static class StringUtils
{
public const string CarriageReturnLineFeed = "\r\n";
public const string Empty = "";
public const char CarriageReturn = '\r';
public const char LineFeed = '\n';
public const char Tab = '\t';
public static string FormatWith(this string format, IFormatProvider provider, object arg0)
{
return format.FormatWith(provider, new[] { arg0 });
}
public static string FormatWith(this string format, IFormatProvider provider, object arg0, object arg1)
{
return format.FormatWith(provider, new[] { arg0, arg1 });
}
public static string FormatWith(this string format, IFormatProvider provider, object arg0, object arg1, object arg2)
{
return format.FormatWith(provider, new[] { arg0, arg1, arg2 });
}
public static string FormatWith(this string format, IFormatProvider provider, object arg0, object arg1, object arg2, object arg3)
{
return format.FormatWith(provider, new[] { arg0, arg1, arg2, arg3 });
}
private static string FormatWith(this string format, IFormatProvider provider, params object[] args)
{
// leave this a private to force code to use an explicit overload
// avoids stack memory being reserved for the object array
ValidationUtils.ArgumentNotNull(format, nameof(format));
return string.Format(provider, format, args);
}
/// <summary>
/// Determines whether the string is all white space. Empty string will return <c>false</c>.
/// </summary>
/// <param name="s">The string to test whether it is all white space.</param>
/// <returns>
/// <c>true</c> if the string is all white space; otherwise, <c>false</c>.
/// </returns>
public static bool IsWhiteSpace(string s)
{
if (s == null)
{
throw new ArgumentNullException(nameof(s));
}
if (s.Length == 0)
{
return false;
}
for (int i = 0; i < s.Length; i++)
{
if (!char.IsWhiteSpace(s[i]))
{
return false;
}
}
return true;
}
public static StringWriter CreateStringWriter(int capacity)
{
StringBuilder sb = new StringBuilder(capacity);
StringWriter sw = new StringWriter(sb, CultureInfo.InvariantCulture);
return sw;
}
public static void ToCharAsUnicode(char c, char[] buffer)
{
buffer[0] = '\\';
buffer[1] = 'u';
buffer[2] = MathUtils.IntToHex((c >> 12) & '\x000f');
buffer[3] = MathUtils.IntToHex((c >> 8) & '\x000f');
buffer[4] = MathUtils.IntToHex((c >> 4) & '\x000f');
buffer[5] = MathUtils.IntToHex(c & '\x000f');
}
public static TSource ForgivingCaseSensitiveFind<TSource>(this IEnumerable<TSource> source, Func<TSource, string> valueSelector, string testValue)
{
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
if (valueSelector == null)
{
throw new ArgumentNullException(nameof(valueSelector));
}
IEnumerable<TSource> caseInsensitiveResults = source.Where(s => string.Equals(valueSelector(s), testValue, StringComparison.OrdinalIgnoreCase));
if (caseInsensitiveResults.Count() <= 1)
{
return caseInsensitiveResults.SingleOrDefault();
}
else
{
// multiple results returned. now filter using case sensitivity
IEnumerable<TSource> caseSensitiveResults = source.Where(s => string.Equals(valueSelector(s), testValue, StringComparison.Ordinal));
return caseSensitiveResults.SingleOrDefault();
}
}
public static string ToCamelCase(string s)
{
if (string.IsNullOrEmpty(s) || !char.IsUpper(s[0]))
{
return s;
}
char[] chars = s.ToCharArray();
for (int i = 0; i < chars.Length; i++)
{
if (i == 1 && !char.IsUpper(chars[i]))
{
break;
}
bool hasNext = (i + 1 < chars.Length);
if (i > 0 && hasNext && !char.IsUpper(chars[i + 1]))
{
// if the next character is a space, which is not considered uppercase
// (otherwise we wouldn't be here...)
// we want to ensure that the following:
// 'FOO bar' is rewritten as 'foo bar', and not as 'foO bar'
// The code was written in such a way that the first word in uppercase
// ends when if finds an uppercase letter followed by a lowercase letter.
// now a ' ' (space, (char)32) is considered not upper
// but in that case we still want our current character to become lowercase
if (char.IsSeparator(chars[i + 1]))
{
chars[i] = ToLower(chars[i]);
}
break;
}
chars[i] = ToLower(chars[i]);
}
return new string(chars);
}
private static char ToLower(char c)
{
#if HAVE_CHAR_TO_STRING_WITH_CULTURE
c = char.ToLower(c, CultureInfo.InvariantCulture);
#else
c = char.ToLowerInvariant(c);
#endif
return c;
}
internal enum SnakeCaseState
{
Start,
Lower,
Upper,
NewWord
}
public static string ToSnakeCase(string s)
{
if (string.IsNullOrEmpty(s))
{
return s;
}
StringBuilder sb = new StringBuilder();
SnakeCaseState state = SnakeCaseState.Start;
for (int i = 0; i < s.Length; i++)
{
if (s[i] == ' ')
{
if (state != SnakeCaseState.Start)
{
state = SnakeCaseState.NewWord;
}
}
else if (char.IsUpper(s[i]))
{
switch (state)
{
case SnakeCaseState.Upper:
bool hasNext = (i + 1 < s.Length);
if (i > 0 && hasNext)
{
char nextChar = s[i + 1];
if (!char.IsUpper(nextChar) && nextChar != '_')
{
sb.Append('_');
}
}
break;
case SnakeCaseState.Lower:
case SnakeCaseState.NewWord:
sb.Append('_');
break;
}
char c;
#if HAVE_CHAR_TO_LOWER_WITH_CULTURE
c = char.ToLower(s[i], CultureInfo.InvariantCulture);
#else
c = char.ToLowerInvariant(s[i]);
#endif
sb.Append(c);
state = SnakeCaseState.Upper;
}
else if (s[i] == '_')
{
sb.Append('_');
state = SnakeCaseState.Start;
}
else
{
if (state == SnakeCaseState.NewWord)
{
sb.Append('_');
}
sb.Append(s[i]);
state = SnakeCaseState.Lower;
}
}
return sb.ToString();
}
public static bool IsHighSurrogate(char c)
{
#if HAVE_UNICODE_SURROGATE_DETECTION
return char.IsHighSurrogate(c);
#else
return (c >= 55296 && c <= 56319);
#endif
}
public static bool IsLowSurrogate(char c)
{
#if HAVE_UNICODE_SURROGATE_DETECTION
return char.IsLowSurrogate(c);
#else
return (c >= 56320 && c <= 57343);
#endif
}
public static bool StartsWith(this string source, char value)
{
return (source.Length > 0 && source[0] == value);
}
public static bool EndsWith(this string source, char value)
{
return (source.Length > 0 && source[source.Length - 1] == value);
}
public static string Trim(this string s, int start, int length)
{
// References: https://referencesource.microsoft.com/#mscorlib/system/string.cs,2691
// https://referencesource.microsoft.com/#mscorlib/system/string.cs,1226
if (s == null)
{
throw new ArgumentNullException();
}
if (start < 0)
{
throw new ArgumentOutOfRangeException(nameof(start));
}
if (length < 0)
{
throw new ArgumentOutOfRangeException(nameof(length));
}
int end = start + length - 1;
if (end >= s.Length)
{
throw new ArgumentOutOfRangeException(nameof(length));
}
for (; start < end; start++)
{
if (!char.IsWhiteSpace(s[start]))
{
break;
}
}
for (; end >= start; end--)
{
if (!char.IsWhiteSpace(s[end]))
{
break;
}
}
return s.Substring(start, end - start + 1);
}
}
}
| |
// 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.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Scripting
{
/// <summary>
/// Implements shadow-copying metadata file cache.
/// </summary>
internal sealed class MetadataShadowCopyProvider : MetadataFileReferenceProvider, IDisposable
{
/// <summary>
/// Specialize <see cref="PortableExecutableReference"/> with path being the original path of the copy.
/// Logically this reference represents that file, the fact that we load the image from a copy is an implementation detail.
/// </summary>
private sealed class ShadowCopyReference : PortableExecutableReference
{
private readonly MetadataShadowCopyProvider _provider;
public ShadowCopyReference(MetadataShadowCopyProvider provider, string originalPath, MetadataReferenceProperties properties)
: base(properties, originalPath)
{
Debug.Assert(originalPath != null);
Debug.Assert(provider != null);
_provider = provider;
}
protected override DocumentationProvider CreateDocumentationProvider()
{
// TODO (tomat): use file next to the dll (or shadow copy)
return DocumentationProvider.Default;
}
protected override Metadata GetMetadataImpl()
{
return _provider.GetMetadata(FilePath, Properties.Kind);
}
protected override PortableExecutableReference WithPropertiesImpl(MetadataReferenceProperties properties)
{
return new ShadowCopyReference(_provider, this.FilePath, properties);
}
}
// normalized absolute path
private readonly string _baseDirectory;
// Normalized absolute path to a directory where assemblies are copied. Must contain nothing but shadow-copied assemblies.
// Internal for testing.
internal string ShadowCopyDirectory;
// normalized absolute paths
private readonly IEnumerable<string> _noShadowCopyDirectories;
private static readonly ImmutableArray<string> s_systemNoShadowCopyDirectories = ImmutableArray.Create(
FileUtilities.NormalizeDirectoryPath(Environment.GetFolderPath(Environment.SpecialFolder.Windows)),
FileUtilities.NormalizeDirectoryPath(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)),
FileUtilities.NormalizeDirectoryPath(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)),
FileUtilities.NormalizeDirectoryPath(RuntimeEnvironment.GetRuntimeDirectory()));
private struct CacheEntry<TPublic>
{
public readonly TPublic Public;
public readonly Metadata Private;
public CacheEntry(TPublic @public, Metadata @private)
{
Debug.Assert(@public != null);
Debug.Assert(@private != null);
Public = @public;
Private = @private;
}
}
// Cache for files that are shadow-copied:
// (original path, last write timestamp) -> (public shadow copy, private metadata instance that owns the PE image)
private readonly Dictionary<FileKey, CacheEntry<MetadataShadowCopy>> _shadowCopies = new Dictionary<FileKey, CacheEntry<MetadataShadowCopy>>();
// Cache for files that are not shadow-copied:
// (path, last write timestamp) -> (public metadata, private metadata instance that owns the PE image)
private readonly Dictionary<FileKey, CacheEntry<Metadata>> _noShadowCopyCache = new Dictionary<FileKey, CacheEntry<Metadata>>();
// files that should not be copied:
private HashSet<string> _lazySuppressedFiles;
private object Guard { get { return _shadowCopies; } }
/// <summary>
/// Creates an instance of <see cref="MetadataShadowCopyProvider"/>.
/// </summary>
/// <param name="directory">The directory to use to store file copies.</param>
/// <param name="noShadowCopyDirectories">Directories to exclude from shadow-copying.</param>
/// <exception cref="ArgumentNullException"><paramref name="directory"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="directory"/> is not an absolute path.</exception>
public MetadataShadowCopyProvider(string directory = null, IEnumerable<string> noShadowCopyDirectories = null)
{
if (directory != null)
{
RequireAbsolutePath(directory, "directory");
try
{
_baseDirectory = FileUtilities.NormalizeDirectoryPath(directory);
}
catch (Exception e)
{
throw new ArgumentException(e.Message, "directory");
}
}
else
{
_baseDirectory = Path.Combine(Path.GetTempPath(), "Roslyn", "MetadataShadowCopyProvider");
}
var normalizedDirs = s_systemNoShadowCopyDirectories;
if (noShadowCopyDirectories != null)
{
try
{
normalizedDirs = normalizedDirs.AddRange(noShadowCopyDirectories.Select(FileUtilities.NormalizeDirectoryPath));
}
catch (Exception e)
{
throw new ArgumentException(e.Message, "noShadowCopyDirectories");
}
}
_noShadowCopyDirectories = normalizedDirs;
// We want to be sure to delete the shadow-copied files when the process goes away. Frankly
// there's nothing we can do if the process is forcefully quit or goes down in a completely
// uncontrolled manner (like a stack overflow). When the process goes down in a controlled
// manned, we should generally expect this event to be called.
AppDomain.CurrentDomain.ProcessExit += HandleProcessExit;
}
private static void RequireAbsolutePath(string path, string argumentName)
{
if (path == null)
{
throw new ArgumentNullException(argumentName);
}
if (!PathUtilities.IsAbsolute(path))
{
throw new ArgumentException(Microsoft.CodeAnalysis.Scripting.ScriptingResources.AbsolutePathExpected, argumentName);
}
}
private void HandleProcessExit(object sender, EventArgs e)
{
Dispose();
AppDomain.CurrentDomain.ProcessExit -= HandleProcessExit;
}
/// <summary>
/// Determine whether given path is under the shadow-copy directory managed by this shadow-copy provider.
/// </summary>
/// <param name="fullPath">Absolute path.</param>
/// <exception cref="ArgumentNullException"><paramref name="fullPath"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="fullPath"/> is not an absolute path.</exception>
public bool IsShadowCopy(string fullPath)
{
RequireAbsolutePath(fullPath, "fullPath");
string directory = ShadowCopyDirectory;
if (directory == null)
{
return false;
}
string normalizedPath;
try
{
normalizedPath = FileUtilities.NormalizeDirectoryPath(fullPath);
}
catch
{
return false;
}
return normalizedPath.StartsWith(directory, StringComparison.OrdinalIgnoreCase);
}
~MetadataShadowCopyProvider()
{
DisposeShadowCopies();
DeleteShadowCopyDirectory();
}
/// <summary>
/// Clears shadow-copy cache, disposes all allocated metadata, and attempts to delete copied files.
/// </summary>
public void Dispose()
{
GC.SuppressFinalize(this);
lock (Guard)
{
DisposeShadowCopies();
_shadowCopies.Clear();
}
DeleteShadowCopyDirectory();
}
private void DisposeShadowCopies()
{
foreach (var entry in _shadowCopies.Values)
{
// metadata file handles have been disposed already, but the xml doc file handle hasn't:
entry.Public.DisposeFileHandles();
// dispose metadata images:
entry.Private.Dispose();
}
}
private void DeleteShadowCopyDirectory()
{
var directory = ShadowCopyDirectory;
if (Directory.Exists(directory))
{
try
{
// First, strip the read-only bit off of any files.
var directoryInfo = new DirectoryInfo(directory);
foreach (var fileInfo in directoryInfo.EnumerateFiles(searchPattern: "*", searchOption: SearchOption.AllDirectories))
{
StripReadOnlyAttributeFromFile(fileInfo);
}
// Second, delete everything.
Directory.Delete(directory, recursive: true);
}
catch
{
}
}
}
private static void StripReadOnlyAttributeFromFile(FileInfo fileInfo)
{
try
{
if (fileInfo.IsReadOnly)
{
fileInfo.IsReadOnly = false;
}
}
catch
{
// There are many reasons this could fail. Just ignore it and move on.
}
}
/// <summary>
/// Gets or creates metadata for specified file path.
/// </summary>
/// <param name="fullPath">Full path to an assembly manifest module file or a standalone module file.</param>
/// <param name="kind">Metadata kind (assembly or module).</param>
/// <returns>Metadata for the specified file.</returns>
/// <exception cref="IOException">Error reading file <paramref name="fullPath"/>. See <see cref="Exception.InnerException"/> for details.</exception>
public Metadata GetMetadata(string fullPath, MetadataImageKind kind)
{
if (NeedsShadowCopy(fullPath))
{
return GetMetadataShadowCopyNoCheck(fullPath, kind).Metadata;
}
FileKey key = FileKey.Create(fullPath);
lock (Guard)
{
CacheEntry<Metadata> existing;
if (_noShadowCopyCache.TryGetValue(key, out existing))
{
return existing.Public;
}
}
Metadata newMetadata;
if (kind == MetadataImageKind.Assembly)
{
newMetadata = AssemblyMetadata.CreateFromFile(fullPath);
}
else
{
newMetadata = ModuleMetadata.CreateFromFile(fullPath);
}
// the files are locked (memory mapped) now
key = FileKey.Create(fullPath);
lock (Guard)
{
CacheEntry<Metadata> existing;
if (_noShadowCopyCache.TryGetValue(key, out existing))
{
newMetadata.Dispose();
return existing.Public;
}
Metadata publicMetadata = newMetadata.Copy();
_noShadowCopyCache.Add(key, new CacheEntry<Metadata>(publicMetadata, newMetadata));
return publicMetadata;
}
}
/// <summary>
/// Gets or creates a copy of specified assembly or standalone module.
/// </summary>
/// <param name="fullPath">Full path to an assembly manifest module file or a standalone module file.</param>
/// <param name="kind">Metadata kind (assembly or module).</param>
/// <returns>
/// Copy of the specified file, or null if the file doesn't need a copy (<see cref="NeedsShadowCopy"/>).
/// Returns the same object if called multiple times with the same path.
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="fullPath"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="fullPath"/> is not an absolute path.</exception>
/// <exception cref="IOException">Error reading file <paramref name="fullPath"/>. See <see cref="Exception.InnerException"/> for details.</exception>
public MetadataShadowCopy GetMetadataShadowCopy(string fullPath, MetadataImageKind kind)
{
return NeedsShadowCopy(fullPath) ? GetMetadataShadowCopyNoCheck(fullPath, kind) : null;
}
private MetadataShadowCopy GetMetadataShadowCopyNoCheck(string fullPath, MetadataImageKind kind)
{
if (kind < MetadataImageKind.Assembly || kind > MetadataImageKind.Module)
{
throw new ArgumentOutOfRangeException(nameof(kind));
}
FileKey key = FileKey.Create(fullPath);
lock (Guard)
{
CacheEntry<MetadataShadowCopy> existing;
if (CopyExistsOrIsSuppressed(key, out existing))
{
return existing.Public;
}
}
CacheEntry<MetadataShadowCopy> newCopy = CreateMetadataShadowCopy(fullPath, kind);
// last-write timestamp is copied from the original file at the time the snapshot was made:
bool fault = true;
try
{
key = new FileKey(fullPath, FileUtilities.GetFileTimeStamp(newCopy.Public.PrimaryModule.FullPath));
fault = false;
}
finally
{
if (fault)
{
newCopy.Private.Dispose();
}
}
lock (Guard)
{
CacheEntry<MetadataShadowCopy> existing;
if (CopyExistsOrIsSuppressed(key, out existing))
{
newCopy.Private.Dispose();
return existing.Public;
}
_shadowCopies.Add(key, newCopy);
}
return newCopy.Public;
}
private bool CopyExistsOrIsSuppressed(FileKey key, out CacheEntry<MetadataShadowCopy> existing)
{
if (_lazySuppressedFiles != null && _lazySuppressedFiles.Contains(key.FullPath))
{
existing = default(CacheEntry<MetadataShadowCopy>);
return true;
}
return _shadowCopies.TryGetValue(key, out existing);
}
/// <exception cref="ArgumentNullException"><paramref name="fullPath"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="fullPath"/> is not an absolute path.</exception>
public override PortableExecutableReference GetReference(string fullPath, MetadataReferenceProperties properties = default(MetadataReferenceProperties))
{
RequireAbsolutePath(fullPath, "fullPath");
return new ShadowCopyReference(this, fullPath, properties);
}
/// <summary>
/// Suppresses shadow-coping of specified path.
/// </summary>
/// <param name="originalPath">Full path.</param>
/// <exception cref="ArgumentNullException"><paramref name="originalPath"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="originalPath"/> is not an absolute path.</exception>
/// <remarks>
/// Doesn't affect files that have already been shadow-copied.
/// </remarks>
public void SuppressShadowCopy(string originalPath)
{
RequireAbsolutePath(originalPath, "originalPath");
lock (Guard)
{
if (_lazySuppressedFiles == null)
{
_lazySuppressedFiles = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
}
_lazySuppressedFiles.Add(originalPath);
}
}
/// <summary>
/// Determines whether given file is a candidate for shadow-copy.
/// </summary>
/// <param name="fullPath">An absolute path.</param>
/// <returns>True if the shadow-copy policy applies to the specified path.</returns>
/// <exception cref="NullReferenceException"><paramref name="fullPath"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="fullPath"/> is not absolute.</exception>
public bool NeedsShadowCopy(string fullPath)
{
RequireAbsolutePath(fullPath, "fullPath");
string directory = Path.GetDirectoryName(fullPath);
// do not shadow-copy shadow-copies:
string referencesDir = ShadowCopyDirectory;
if (referencesDir != null && directory.StartsWith(referencesDir, StringComparison.OrdinalIgnoreCase))
{
return false;
}
return !_noShadowCopyDirectories.Any(dir => directory.StartsWith(dir, StringComparison.OrdinalIgnoreCase));
}
private CacheEntry<MetadataShadowCopy> CreateMetadataShadowCopy(string originalPath, MetadataImageKind kind)
{
int attempts = 10;
while (true)
{
try
{
if (ShadowCopyDirectory == null)
{
ShadowCopyDirectory = CreateUniqueDirectory(_baseDirectory);
}
// Create directory for the assembly.
// If the assembly has any modules they have to be copied to the same directory
// and have the same names as specified in metadata.
string assemblyDir = CreateUniqueDirectory(ShadowCopyDirectory);
string shadowCopyPath = Path.Combine(assemblyDir, Path.GetFileName(originalPath));
ShadowCopy documentationFileCopy = null;
string xmlOriginalPath;
if (TryFindXmlDocumentationFile(originalPath, out xmlOriginalPath))
{
// TODO (tomat): how do doc comments work for multi-module assembly?
var xmlCopyPath = Path.ChangeExtension(shadowCopyPath, ".xml");
var xmlStream = CopyFile(xmlOriginalPath, xmlCopyPath, fileMayNotExist: true);
if (xmlStream != null)
{
documentationFileCopy = new ShadowCopy(xmlStream, xmlOriginalPath, xmlCopyPath);
}
}
var manifestModuleCopyStream = CopyFile(originalPath, shadowCopyPath);
var manifestModuleCopy = new ShadowCopy(manifestModuleCopyStream, originalPath, shadowCopyPath);
Metadata privateMetadata;
if (kind == MetadataImageKind.Assembly)
{
privateMetadata = CreateAssemblyMetadata(manifestModuleCopyStream, originalPath, shadowCopyPath);
}
else
{
privateMetadata = CreateModuleMetadata(manifestModuleCopyStream);
}
var publicMetadata = privateMetadata.Copy();
return new CacheEntry<MetadataShadowCopy>(new MetadataShadowCopy(manifestModuleCopy, documentationFileCopy, publicMetadata), privateMetadata);
}
catch (DirectoryNotFoundException)
{
// the shadow copy directory has been deleted - try to copy all files again
if (!Directory.Exists(ShadowCopyDirectory))
{
ShadowCopyDirectory = null;
if (attempts-- > 0)
{
continue;
}
}
throw;
}
}
}
private bool TryFindXmlDocumentationFile(string assemblyFilePath, out string xmlDocumentationFilePath)
{
xmlDocumentationFilePath = null;
// Look for the documentation xml in subdirectories based on the current
// culture
// TODO: This logic is somewhat duplicated between here and
// Roslyn.Utilities.FilePathUtilities.TryFindXmlDocumentationFile
string candidateFilePath = string.Empty;
string xmlFileName = Path.ChangeExtension(Path.GetFileName(assemblyFilePath), ".xml");
string originalDirectory = Path.GetDirectoryName(assemblyFilePath);
var culture = CultureInfo.CurrentCulture;
while (culture != CultureInfo.InvariantCulture)
{
candidateFilePath = Path.Combine(originalDirectory, culture.Name, xmlFileName);
if (File.Exists(candidateFilePath))
{
xmlDocumentationFilePath = candidateFilePath;
return true;
}
culture = culture.Parent;
}
// The documentation xml was not found in a subdirectory for the current culture, so
// check the directory containing the assembly itself
candidateFilePath = Path.ChangeExtension(assemblyFilePath, ".xml");
if (File.Exists(candidateFilePath))
{
xmlDocumentationFilePath = candidateFilePath;
return true;
}
return false;
}
private AssemblyMetadata CreateAssemblyMetadata(FileStream manifestModuleCopyStream, string originalPath, string shadowCopyPath)
{
// We don't need to use the global metadata cache here since the shadow copy
// won't change and is private to us - only users of the same shadow copy provider see it.
ImmutableArray<ModuleMetadata>.Builder moduleBuilder = null;
bool fault = true;
ModuleMetadata manifestModule = null;
try
{
manifestModule = CreateModuleMetadata(manifestModuleCopyStream);
string originalDirectory = null, shadowCopyDirectory = null;
foreach (string moduleName in manifestModule.GetModuleNames())
{
if (moduleBuilder == null)
{
moduleBuilder = ImmutableArray.CreateBuilder<ModuleMetadata>();
moduleBuilder.Add(manifestModule);
originalDirectory = Path.GetDirectoryName(originalPath);
shadowCopyDirectory = Path.GetDirectoryName(shadowCopyPath);
}
FileStream moduleCopyStream = CopyFile(
originalPath: Path.Combine(originalDirectory, moduleName),
shadowCopyPath: Path.Combine(shadowCopyDirectory, moduleName));
moduleBuilder.Add(CreateModuleMetadata(moduleCopyStream));
}
var modules = (moduleBuilder != null) ? moduleBuilder.ToImmutable() : ImmutableArray.Create(manifestModule);
fault = false;
return AssemblyMetadata.Create(modules);
}
finally
{
if (fault)
{
if (manifestModule != null)
{
manifestModule.Dispose();
}
if (moduleBuilder != null)
{
for (int i = 1; i < moduleBuilder.Count; i++)
{
moduleBuilder[i].Dispose();
}
}
}
}
}
private static ModuleMetadata CreateModuleMetadata(FileStream stream)
{
// The Stream is held by the ModuleMetadata to read metadata on demand.
// We hand off the responsibility for closing the stream to the metadata object.
return ModuleMetadata.CreateFromStream(stream, leaveOpen: false);
}
private string CreateUniqueDirectory(string basePath)
{
int attempts = 10;
while (true)
{
string dir = Path.Combine(basePath, Guid.NewGuid().ToString());
if (File.Exists(dir) || Directory.Exists(dir))
{
// try a different name (guid):
continue;
}
try
{
Directory.CreateDirectory(dir);
return dir;
}
catch (IOException)
{
// Some other process might have created a file of the same name after we checked for its existence.
if (File.Exists(dir))
{
continue;
}
// This file might also have been deleted by now. So try again for a while and then give up.
if (--attempts == 0)
{
throw;
}
}
}
}
private FileStream CopyFile(string originalPath, string shadowCopyPath, bool fileMayNotExist = false)
{
try
{
File.Copy(originalPath, shadowCopyPath, overwrite: true);
StripReadOnlyAttributeFromFile(new FileInfo(shadowCopyPath));
// tomat: Ideally we would mark the handle as "delete on close". Unfortunately any subsequent attempt to create a handle to the file is denied if we do so.
// The only way to read the file is via the handle we open here, however we need to use APIs that take a path to the shadow copy and open it for read
// (e.g. Assembly.Load, VS XML doc caching service, etc.).
#if DELETE_ON_CLOSE
// deletes the file if the shadow copy cache isn't explicitly cleared
var stream = new FileStream(shadowCopyPath, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete, bufferSize: 0x1000, options: FileOptions.DeleteOnClose);
// this prevents us to reopen the file, so we need to use the above stream later on
PathUtilities.PrepareDeleteOnCloseStreamForDisposal(stream);
#else
return new FileStream(shadowCopyPath, FileMode.Open, FileAccess.Read, FileShare.Read);
#endif
}
catch (FileNotFoundException)
{
if (!fileMayNotExist)
{
throw;
}
}
return null;
}
#region Test hooks
// for testing only
internal int CacheSize
{
get { return _shadowCopies.Count; }
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
** Purpose: Exposes features of the Garbage Collector through
** the class libraries. This is a class which cannot be
** instantiated.
**
**
===========================================================*/
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Collections.Generic;
#if !DEBUG
using Internal.Runtime.CompilerServices;
#endif
namespace System
{
public enum GCCollectionMode
{
Default = 0,
Forced = 1,
Optimized = 2
}
// !!!!!!!!!!!!!!!!!!!!!!!
// make sure you change the def in vm\gc.h
// if you change this!
internal enum InternalGCCollectionMode
{
NonBlocking = 0x00000001,
Blocking = 0x00000002,
Optimized = 0x00000004,
Compacting = 0x00000008,
}
// !!!!!!!!!!!!!!!!!!!!!!!
// make sure you change the def in vm\gc.h
// if you change this!
public enum GCNotificationStatus
{
Succeeded = 0,
Failed = 1,
Canceled = 2,
Timeout = 3,
NotApplicable = 4
}
public static class GC
{
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern void GetMemoryInfo(out ulong highMemLoadThresholdBytes,
out ulong totalAvailableMemoryBytes,
out ulong lastRecordedMemLoadBytes,
out uint lastRecordedMemLoadPct,
// The next two are size_t
out UIntPtr lastRecordedHeapSizeBytes,
out UIntPtr lastRecordedFragmentationBytes);
public static GCMemoryInfo GetGCMemoryInfo()
{
GetMemoryInfo(out ulong highMemLoadThresholdBytes,
out ulong totalAvailableMemoryBytes,
out ulong lastRecordedMemLoadBytes,
out uint _,
out UIntPtr lastRecordedHeapSizeBytes,
out UIntPtr lastRecordedFragmentationBytes);
return new GCMemoryInfo(highMemoryLoadThresholdBytes: (long)highMemLoadThresholdBytes,
memoryLoadBytes: (long)lastRecordedMemLoadBytes,
totalAvailableMemoryBytes: (long)totalAvailableMemoryBytes,
heapSizeBytes: (long)(ulong)lastRecordedHeapSizeBytes,
fragmentedBytes: (long)(ulong)lastRecordedFragmentationBytes);
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
internal static extern int _StartNoGCRegion(long totalSize, bool lohSizeKnown, long lohSize, bool disallowFullBlockingGC);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
internal static extern int _EndNoGCRegion();
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern Array AllocateNewArray(IntPtr typeHandle, int length, bool zeroingOptional);
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern int GetGenerationWR(IntPtr handle);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern long GetTotalMemory();
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void _Collect(int generation, int mode);
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern int GetMaxGeneration();
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern int _CollectionCount(int generation, int getSpecialGCCount);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern ulong GetSegmentSize();
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern int GetLastGCPercentTimeInGC();
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern ulong GetGenerationSize(int gen);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void _AddMemoryPressure(ulong bytesAllocated);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void _RemoveMemoryPressure(ulong bytesAllocated);
public static void AddMemoryPressure(long bytesAllocated)
{
if (bytesAllocated <= 0)
{
throw new ArgumentOutOfRangeException(nameof(bytesAllocated),
SR.ArgumentOutOfRange_NeedPosNum);
}
if ((4 == IntPtr.Size) && (bytesAllocated > int.MaxValue))
{
throw new ArgumentOutOfRangeException("pressure",
SR.ArgumentOutOfRange_MustBeNonNegInt32);
}
_AddMemoryPressure((ulong)bytesAllocated);
}
public static void RemoveMemoryPressure(long bytesAllocated)
{
if (bytesAllocated <= 0)
{
throw new ArgumentOutOfRangeException(nameof(bytesAllocated),
SR.ArgumentOutOfRange_NeedPosNum);
}
if ((4 == IntPtr.Size) && (bytesAllocated > int.MaxValue))
{
throw new ArgumentOutOfRangeException(nameof(bytesAllocated),
SR.ArgumentOutOfRange_MustBeNonNegInt32);
}
_RemoveMemoryPressure((ulong)bytesAllocated);
}
// Returns the generation that obj is currently in.
//
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern int GetGeneration(object obj);
// Forces a collection of all generations from 0 through Generation.
//
public static void Collect(int generation)
{
Collect(generation, GCCollectionMode.Default);
}
// Garbage Collect all generations.
//
public static void Collect()
{
// -1 says to GC all generations.
_Collect(-1, (int)InternalGCCollectionMode.Blocking);
}
public static void Collect(int generation, GCCollectionMode mode)
{
Collect(generation, mode, true);
}
public static void Collect(int generation, GCCollectionMode mode, bool blocking)
{
Collect(generation, mode, blocking, false);
}
public static void Collect(int generation, GCCollectionMode mode, bool blocking, bool compacting)
{
if (generation < 0)
{
throw new ArgumentOutOfRangeException(nameof(generation), SR.ArgumentOutOfRange_GenericPositive);
}
if ((mode < GCCollectionMode.Default) || (mode > GCCollectionMode.Optimized))
{
throw new ArgumentOutOfRangeException(nameof(mode), SR.ArgumentOutOfRange_Enum);
}
int iInternalModes = 0;
if (mode == GCCollectionMode.Optimized)
{
iInternalModes |= (int)InternalGCCollectionMode.Optimized;
}
if (compacting)
iInternalModes |= (int)InternalGCCollectionMode.Compacting;
if (blocking)
{
iInternalModes |= (int)InternalGCCollectionMode.Blocking;
}
else if (!compacting)
{
iInternalModes |= (int)InternalGCCollectionMode.NonBlocking;
}
_Collect(generation, iInternalModes);
}
public static int CollectionCount(int generation)
{
if (generation < 0)
{
throw new ArgumentOutOfRangeException(nameof(generation), SR.ArgumentOutOfRange_GenericPositive);
}
return _CollectionCount(generation, 0);
}
// This method DOES NOT DO ANYTHING in and of itself. It's used to
// prevent a finalizable object from losing any outstanding references
// a touch too early. The JIT is very aggressive about keeping an
// object's lifetime to as small a window as possible, to the point
// where a 'this' pointer isn't considered live in an instance method
// unless you read a value from the instance. So for finalizable
// objects that store a handle or pointer and provide a finalizer that
// cleans them up, this can cause subtle race conditions with the finalizer
// thread. This isn't just about handles - it can happen with just
// about any finalizable resource.
//
// Users should insert a call to this method right after the last line
// of their code where their code still needs the object to be kept alive.
// The object which reference is passed into this method will not
// be eligible for collection until the call to this method happens.
// Once the call to this method has happened the object may immediately
// become eligible for collection. Here is an example:
//
// "...all you really need is one object with a Finalize method, and a
// second object with a Close/Dispose/Done method. Such as the following
// contrived example:
//
// class Foo {
// Stream stream = ...;
// protected void Finalize() { stream.Close(); }
// void Problem() { stream.MethodThatSpansGCs(); }
// static void Main() { new Foo().Problem(); }
// }
//
//
// In this code, Foo will be finalized in the middle of
// stream.MethodThatSpansGCs, thus closing a stream still in use."
//
// If we insert a call to GC.KeepAlive(this) at the end of Problem(), then
// Foo doesn't get finalized and the stream stays open.
[MethodImpl(MethodImplOptions.NoInlining)] // disable optimizations
public static void KeepAlive(object? obj)
{
}
// Returns the generation in which wo currently resides.
//
public static int GetGeneration(WeakReference wo)
{
int result = GetGenerationWR(wo.m_handle);
KeepAlive(wo);
return result;
}
// Returns the maximum GC generation. Currently assumes only 1 heap.
//
public static int MaxGeneration => GetMaxGeneration();
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void _WaitForPendingFinalizers();
public static void WaitForPendingFinalizers()
{
// QCalls can not be exposed from mscorlib directly, need to wrap it.
_WaitForPendingFinalizers();
}
// Indicates that the system should not call the Finalize() method on
// an object that would normally require this call.
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void _SuppressFinalize(object o);
public static void SuppressFinalize(object obj)
{
if (obj == null)
throw new ArgumentNullException(nameof(obj));
_SuppressFinalize(obj);
}
// Indicates that the system should call the Finalize() method on an object
// for which SuppressFinalize has already been called. The other situation
// where calling ReRegisterForFinalize is useful is inside a finalizer that
// needs to resurrect itself or an object that it references.
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void _ReRegisterForFinalize(object o);
public static void ReRegisterForFinalize(object obj)
{
if (obj == null)
throw new ArgumentNullException(nameof(obj));
_ReRegisterForFinalize(obj);
}
// Returns the total number of bytes currently in use by live objects in
// the GC heap. This does not return the total size of the GC heap, but
// only the live objects in the GC heap.
//
public static long GetTotalMemory(bool forceFullCollection)
{
long size = GetTotalMemory();
if (!forceFullCollection)
return size;
// If we force a full collection, we will run the finalizers on all
// existing objects and do a collection until the value stabilizes.
// The value is "stable" when either the value is within 5% of the
// previous call to GetTotalMemory, or if we have been sitting
// here for more than x times (we don't want to loop forever here).
int reps = 20; // Number of iterations
long newSize = size;
float diff;
do
{
GC.WaitForPendingFinalizers();
GC.Collect();
size = newSize;
newSize = GetTotalMemory();
diff = ((float)(newSize - size)) / size;
} while (reps-- > 0 && !(-.05 < diff && diff < .05));
return newSize;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern IntPtr _RegisterFrozenSegment(IntPtr sectionAddress, IntPtr sectionSize);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void _UnregisterFrozenSegment(IntPtr segmentHandle);
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern long GetAllocatedBytesForCurrentThread();
/// <summary>
/// Get a count of the bytes allocated over the lifetime of the process.
/// <param name="precise">If true, gather a precise number, otherwise gather a fairly count. Gathering a precise value triggers at a significant performance penalty.</param>
/// </summary>
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern long GetTotalAllocatedBytes(bool precise = false);
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern bool _RegisterForFullGCNotification(int maxGenerationPercentage, int largeObjectHeapPercentage);
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern bool _CancelFullGCNotification();
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern int _WaitForFullGCApproach(int millisecondsTimeout);
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern int _WaitForFullGCComplete(int millisecondsTimeout);
public static void RegisterForFullGCNotification(int maxGenerationThreshold, int largeObjectHeapThreshold)
{
if ((maxGenerationThreshold <= 0) || (maxGenerationThreshold >= 100))
{
throw new ArgumentOutOfRangeException(nameof(maxGenerationThreshold),
SR.Format(
SR.ArgumentOutOfRange_Bounds_Lower_Upper,
1,
99));
}
if ((largeObjectHeapThreshold <= 0) || (largeObjectHeapThreshold >= 100))
{
throw new ArgumentOutOfRangeException(nameof(largeObjectHeapThreshold),
SR.Format(
SR.ArgumentOutOfRange_Bounds_Lower_Upper,
1,
99));
}
if (!_RegisterForFullGCNotification(maxGenerationThreshold, largeObjectHeapThreshold))
{
throw new InvalidOperationException(SR.InvalidOperation_NotWithConcurrentGC);
}
}
public static void CancelFullGCNotification()
{
if (!_CancelFullGCNotification())
{
throw new InvalidOperationException(SR.InvalidOperation_NotWithConcurrentGC);
}
}
public static GCNotificationStatus WaitForFullGCApproach()
{
return (GCNotificationStatus)_WaitForFullGCApproach(-1);
}
public static GCNotificationStatus WaitForFullGCApproach(int millisecondsTimeout)
{
if (millisecondsTimeout < -1)
throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
return (GCNotificationStatus)_WaitForFullGCApproach(millisecondsTimeout);
}
public static GCNotificationStatus WaitForFullGCComplete()
{
return (GCNotificationStatus)_WaitForFullGCComplete(-1);
}
public static GCNotificationStatus WaitForFullGCComplete(int millisecondsTimeout)
{
if (millisecondsTimeout < -1)
throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
return (GCNotificationStatus)_WaitForFullGCComplete(millisecondsTimeout);
}
private enum StartNoGCRegionStatus
{
Succeeded = 0,
NotEnoughMemory = 1,
AmountTooLarge = 2,
AlreadyInProgress = 3
}
private enum EndNoGCRegionStatus
{
Succeeded = 0,
NotInProgress = 1,
GCInduced = 2,
AllocationExceeded = 3
}
private static bool StartNoGCRegionWorker(long totalSize, bool hasLohSize, long lohSize, bool disallowFullBlockingGC)
{
if (totalSize <= 0)
{
throw new ArgumentOutOfRangeException(nameof(totalSize), "totalSize can't be zero or negative");
}
if (hasLohSize)
{
if (lohSize <= 0)
{
throw new ArgumentOutOfRangeException(nameof(lohSize), "lohSize can't be zero or negative");
}
if (lohSize > totalSize)
{
throw new ArgumentOutOfRangeException(nameof(lohSize), "lohSize can't be greater than totalSize");
}
}
StartNoGCRegionStatus status = (StartNoGCRegionStatus)_StartNoGCRegion(totalSize, hasLohSize, lohSize, disallowFullBlockingGC);
switch (status)
{
case StartNoGCRegionStatus.NotEnoughMemory:
return false;
case StartNoGCRegionStatus.AlreadyInProgress:
throw new InvalidOperationException("The NoGCRegion mode was already in progress");
case StartNoGCRegionStatus.AmountTooLarge:
throw new ArgumentOutOfRangeException(nameof(totalSize),
"totalSize is too large. For more information about setting the maximum size, see \"Latency Modes\" in http://go.microsoft.com/fwlink/?LinkId=522706");
}
Debug.Assert(status == StartNoGCRegionStatus.Succeeded);
return true;
}
public static bool TryStartNoGCRegion(long totalSize)
{
return StartNoGCRegionWorker(totalSize, false, 0, false);
}
public static bool TryStartNoGCRegion(long totalSize, long lohSize)
{
return StartNoGCRegionWorker(totalSize, true, lohSize, false);
}
public static bool TryStartNoGCRegion(long totalSize, bool disallowFullBlockingGC)
{
return StartNoGCRegionWorker(totalSize, false, 0, disallowFullBlockingGC);
}
public static bool TryStartNoGCRegion(long totalSize, long lohSize, bool disallowFullBlockingGC)
{
return StartNoGCRegionWorker(totalSize, true, lohSize, disallowFullBlockingGC);
}
public static void EndNoGCRegion()
{
EndNoGCRegionStatus status = (EndNoGCRegionStatus)_EndNoGCRegion();
if (status == EndNoGCRegionStatus.NotInProgress)
throw new InvalidOperationException("NoGCRegion mode must be set");
else if (status == EndNoGCRegionStatus.GCInduced)
throw new InvalidOperationException("Garbage collection was induced in NoGCRegion mode");
else if (status == EndNoGCRegionStatus.AllocationExceeded)
throw new InvalidOperationException("Allocated memory exceeds specified memory for NoGCRegion mode");
}
private readonly struct MemoryLoadChangeNotification
{
public float LowMemoryPercent { get; }
public float HighMemoryPercent { get; }
public Action Notification { get; }
public MemoryLoadChangeNotification(float lowMemoryPercent, float highMemoryPercent, Action notification)
{
LowMemoryPercent = lowMemoryPercent;
HighMemoryPercent = highMemoryPercent;
Notification = notification;
}
}
private static readonly List<MemoryLoadChangeNotification> s_notifications = new List<MemoryLoadChangeNotification>();
private static float s_previousMemoryLoad = float.MaxValue;
private static float GetMemoryLoad()
{
GetMemoryInfo(out ulong _,
out ulong _,
out ulong _,
out uint lastRecordedMemLoadPct,
out UIntPtr _,
out UIntPtr _);
return (float)lastRecordedMemLoadPct;
}
private static bool InvokeMemoryLoadChangeNotifications()
{
float currentMemoryLoad = GetMemoryLoad();
lock (s_notifications)
{
if (s_previousMemoryLoad == float.MaxValue)
{
s_previousMemoryLoad = currentMemoryLoad;
return true;
}
// We need to take a snapshot of s_notifications.Count, so that in the case that s_notifications[i].Notification() registers new notifications,
// we neither get rid of them nor iterate over them
int count = s_notifications.Count;
// If there is no existing notifications, we won't be iterating over any and we won't be adding any new one. Also, there wasn't any added since
// we last invoked this method so it's safe to assume we can reset s_previousMemoryLoad.
if (count == 0)
{
s_previousMemoryLoad = float.MaxValue;
return false;
}
int last = 0;
for (int i = 0; i < count; ++i)
{
// If s_notifications[i] changes from within s_previousMemoryLoad bound to outside s_previousMemoryLoad, we trigger the notification
if (s_notifications[i].LowMemoryPercent <= s_previousMemoryLoad && s_previousMemoryLoad <= s_notifications[i].HighMemoryPercent
&& !(s_notifications[i].LowMemoryPercent <= currentMemoryLoad && currentMemoryLoad <= s_notifications[i].HighMemoryPercent))
{
s_notifications[i].Notification();
// it will then be overwritten or removed
}
else
{
s_notifications[last++] = s_notifications[i];
}
}
if (last < count)
{
s_notifications.RemoveRange(last, count - last);
}
return true;
}
}
/// <summary>
/// Register a notification to occur *AFTER* a GC occurs in which the memory load changes from within the bound specified
/// to outside of the bound specified. This notification will occur once. If repeated notifications are required, the notification
/// must be reregistered. The notification will occur on a thread which should not be blocked. Complex processing in the notification should defer work to the threadpool.
/// </summary>
/// <param name="lowMemoryPercent">percent of HighMemoryLoadThreshold to use as lower bound. Must be a number >= 0 or an ArgumentOutOfRangeException will be thrown.</param>
/// <param name="highMemoryPercent">percent of HighMemoryLoadThreshold use to use as lower bound. Must be a number > lowMemory or an ArgumentOutOfRangeException will be thrown. </param>
/// <param name="notification">delegate to invoke when operation occurs</param>s
internal static void RegisterMemoryLoadChangeNotification(float lowMemoryPercent, float highMemoryPercent, Action notification)
{
if (highMemoryPercent < 0 || highMemoryPercent > 1.0 || highMemoryPercent <= lowMemoryPercent)
{
throw new ArgumentOutOfRangeException(nameof(highMemoryPercent));
}
if (lowMemoryPercent < 0)
{
throw new ArgumentOutOfRangeException(nameof(lowMemoryPercent));
}
if (notification == null)
{
throw new ArgumentNullException(nameof(notification));
}
lock (s_notifications)
{
s_notifications.Add(new MemoryLoadChangeNotification(lowMemoryPercent, highMemoryPercent, notification));
if (s_notifications.Count == 1)
{
Gen2GcCallback.Register(InvokeMemoryLoadChangeNotifications);
}
}
}
internal static void UnregisterMemoryLoadChangeNotification(Action notification)
{
if (notification == null)
{
throw new ArgumentNullException(nameof(notification));
}
lock (s_notifications)
{
for (int i = 0; i < s_notifications.Count; ++i)
{
if (s_notifications[i].Notification == notification)
{
s_notifications.RemoveAt(i);
break;
}
}
// We only register the callback from the runtime in InvokeMemoryLoadChangeNotifications, so to avoid race conditions between
// UnregisterMemoryLoadChangeNotification and InvokeMemoryLoadChangeNotifications in native.
}
}
// Skips zero-initialization of the array if possible. If T contains object references,
// the array is always zero-initialized.
internal static T[] AllocateUninitializedArray<T>(int length)
{
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
return new T[length];
}
if (length < 0)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.lengths, 0, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
#if DEBUG
// in DEBUG arrays of any length can be created uninitialized
#else
// otherwise small arrays are allocated using `new[]` as that is generally faster.
//
// The threshold was derived from various simulations.
// As it turned out the threshold depends on overal pattern of all allocations and is typically in 200-300 byte range.
// The gradient around the number is shallow (there is no perf cliff) and the exact value of the threshold does not matter a lot.
// So it is 256 bytes including array header.
if (Unsafe.SizeOf<T>() * length < 256 - 3 * IntPtr.Size)
{
return new T[length];
}
#endif
return (T[])AllocateNewArray(typeof(T[]).TypeHandle.Value, length, zeroingOptional: 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.Generic;
using System.Reflection;
using System.Text;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
namespace OpenSim.Region.Framework.Scenes
{
#region Delegates
public delegate uint GenerateClientFlagsHandler(SceneObjectPart part, ScenePresence sp, uint curEffectivePerms);
public delegate void SetBypassPermissionsHandler(bool value);
public delegate bool BypassPermissionsHandler();
public delegate bool PropagatePermissionsHandler();
public delegate bool RezObjectHandler(int objectCount, UUID owner, Vector3 objectPosition);
public delegate bool DeleteObjectHandlerByIDs(UUID objectID, UUID deleter);
public delegate bool DeleteObjectHandler(SceneObjectGroup sog, ScenePresence sp);
public delegate bool TransferObjectHandler(UUID objectID, UUID recipient);
public delegate bool TakeObjectHandler(SceneObjectGroup sog, ScenePresence sp);
public delegate bool SellGroupObjectHandler(UUID userID, UUID groupID);
public delegate bool TakeCopyObjectHandler(SceneObjectGroup sog, ScenePresence sp);
public delegate bool DuplicateObjectHandler(SceneObjectGroup sog, ScenePresence sp);
public delegate bool EditObjectByIDsHandler(UUID objectID, UUID editorID);
public delegate bool EditObjectHandler(SceneObjectGroup sog, ScenePresence sp);
public delegate bool EditObjectInventoryHandler(UUID objectID, UUID editorID);
public delegate bool MoveObjectHandler(SceneObjectGroup sog, ScenePresence sp);
public delegate bool ObjectEntryHandler(SceneObjectGroup sog, bool enteringRegion, Vector3 newPoint);
public delegate bool ReturnObjectsHandler(ILandObject land, ScenePresence sp, List<SceneObjectGroup> objects);
public delegate bool InstantMessageHandler(UUID user, UUID target);
public delegate bool InventoryTransferHandler(UUID user, UUID target);
public delegate bool ViewScriptHandler(UUID script, UUID objectID, UUID user);
public delegate bool ViewNotecardHandler(UUID script, UUID objectID, UUID user);
public delegate bool EditScriptHandler(UUID script, UUID objectID, UUID user);
public delegate bool EditNotecardHandler(UUID notecard, UUID objectID, UUID user);
public delegate bool RunScriptHandlerByIDs(UUID script, UUID objectID, UUID user);
public delegate bool RunScriptHandler(TaskInventoryItem item, SceneObjectPart part);
public delegate bool CompileScriptHandler(UUID ownerUUID, int scriptType);
public delegate bool StartScriptHandler(UUID script, UUID user);
public delegate bool StopScriptHandler(UUID script, UUID user);
public delegate bool ResetScriptHandler(UUID prim, UUID script, UUID user);
public delegate bool TerraformLandHandler(UUID user, Vector3 position);
public delegate bool RunConsoleCommandHandler(UUID user);
public delegate bool IssueEstateCommandHandler(UUID user, bool ownerCommand);
public delegate bool IsGodHandler(UUID user);
public delegate bool IsGridGodHandler(UUID user);
public delegate bool IsAdministratorHandler(UUID user);
public delegate bool IsEstateManagerHandler(UUID user);
public delegate bool EditParcelHandler(UUID user, ILandObject parcel);
public delegate bool EditParcelPropertiesHandler(UUID user, ILandObject parcel, GroupPowers p, bool allowManager);
public delegate bool SellParcelHandler(UUID user, ILandObject parcel);
public delegate bool AbandonParcelHandler(UUID user, ILandObject parcel);
public delegate bool ReclaimParcelHandler(UUID user, ILandObject parcel);
public delegate bool DeedParcelHandler(UUID user, ILandObject parcel);
public delegate bool DeedObjectHandler(ScenePresence sp, SceneObjectGroup sog, UUID targetGroupID);
public delegate bool BuyLandHandler(UUID user, ILandObject parcel);
public delegate bool LinkObjectHandler(UUID user, UUID objectID);
public delegate bool DelinkObjectHandler(UUID user, UUID objectID);
public delegate bool CreateObjectInventoryHandler(int invType, UUID objectID, UUID userID);
public delegate bool CopyObjectInventoryHandler(UUID itemID, UUID objectID, UUID userID);
public delegate bool DoObjectInvToObjectInv(TaskInventoryItem item, SceneObjectPart sourcePart, SceneObjectPart destPart);
public delegate bool DoDropInObjectInv(InventoryItemBase item, ScenePresence sp, SceneObjectPart destPart);
public delegate bool DeleteObjectInventoryHandler(UUID itemID, UUID objectID, UUID userID);
public delegate bool TransferObjectInventoryHandler(UUID itemID, UUID objectID, UUID userID);
public delegate bool CreateUserInventoryHandler(int invType, UUID userID);
public delegate bool EditUserInventoryHandler(UUID itemID, UUID userID);
public delegate bool CopyUserInventoryHandler(UUID itemID, UUID userID);
public delegate bool DeleteUserInventoryHandler(UUID itemID, UUID userID);
public delegate bool TransferUserInventoryHandler(UUID itemID, UUID userID, UUID recipientID);
public delegate bool TeleportHandler(UUID userID, Scene scene);
public delegate bool ControlPrimMediaHandler(UUID userID, UUID primID, int face);
public delegate bool InteractWithPrimMediaHandler(UUID userID, UUID primID, int face);
#endregion
public class ScenePermissions
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private Scene m_scene;
public ScenePermissions(Scene scene)
{
m_scene = scene;
}
#region Events
public event GenerateClientFlagsHandler OnGenerateClientFlags;
public event SetBypassPermissionsHandler OnSetBypassPermissions;
public event BypassPermissionsHandler OnBypassPermissions;
public event PropagatePermissionsHandler OnPropagatePermissions;
public event RezObjectHandler OnRezObject;
public event DeleteObjectHandlerByIDs OnDeleteObjectByIDs;
public event DeleteObjectHandler OnDeleteObject;
public event TransferObjectHandler OnTransferObject;
public event TakeObjectHandler OnTakeObject;
public event SellGroupObjectHandler OnSellGroupObject;
public event TakeCopyObjectHandler OnTakeCopyObject;
public event DuplicateObjectHandler OnDuplicateObject;
public event EditObjectByIDsHandler OnEditObjectByIDs;
public event EditObjectHandler OnEditObject;
public event EditObjectInventoryHandler OnEditObjectInventory;
public event MoveObjectHandler OnMoveObject;
public event ObjectEntryHandler OnObjectEntry;
public event ReturnObjectsHandler OnReturnObjects;
public event InstantMessageHandler OnInstantMessage;
public event InventoryTransferHandler OnInventoryTransfer;
public event ViewScriptHandler OnViewScript;
public event ViewNotecardHandler OnViewNotecard;
public event EditScriptHandler OnEditScript;
public event EditNotecardHandler OnEditNotecard;
public event RunScriptHandlerByIDs OnRunScriptByIDs;
public event RunScriptHandler OnRunScript;
public event CompileScriptHandler OnCompileScript;
public event StartScriptHandler OnStartScript;
public event StopScriptHandler OnStopScript;
public event ResetScriptHandler OnResetScript;
public event TerraformLandHandler OnTerraformLand;
public event RunConsoleCommandHandler OnRunConsoleCommand;
public event IssueEstateCommandHandler OnIssueEstateCommand;
public event IsGridGodHandler OnIsGridGod;
public event IsAdministratorHandler OnIsAdministrator;
public event IsEstateManagerHandler OnIsEstateManager;
// public event EditParcelHandler OnEditParcel;
public event EditParcelPropertiesHandler OnEditParcelProperties;
public event SellParcelHandler OnSellParcel;
public event AbandonParcelHandler OnAbandonParcel;
public event ReclaimParcelHandler OnReclaimParcel;
public event DeedParcelHandler OnDeedParcel;
public event DeedObjectHandler OnDeedObject;
public event BuyLandHandler OnBuyLand;
public event LinkObjectHandler OnLinkObject;
public event DelinkObjectHandler OnDelinkObject;
public event CreateObjectInventoryHandler OnCreateObjectInventory;
public event CopyObjectInventoryHandler OnCopyObjectInventory;
public event DoObjectInvToObjectInv OnDoObjectInvToObjectInv;
public event DoDropInObjectInv OnDropInObjectInv;
public event DeleteObjectInventoryHandler OnDeleteObjectInventory;
public event TransferObjectInventoryHandler OnTransferObjectInventory;
public event CreateUserInventoryHandler OnCreateUserInventory;
public event EditUserInventoryHandler OnEditUserInventory;
public event CopyUserInventoryHandler OnCopyUserInventory;
public event DeleteUserInventoryHandler OnDeleteUserInventory;
public event TransferUserInventoryHandler OnTransferUserInventory;
public event TeleportHandler OnTeleport;
public event ControlPrimMediaHandler OnControlPrimMedia;
public event InteractWithPrimMediaHandler OnInteractWithPrimMedia;
#endregion
#region Object Permission Checks
public uint GenerateClientFlags( SceneObjectPart part, ScenePresence sp)
{
// libomv will moan about PrimFlags.ObjectYouOfficer being
// obsolete...
#pragma warning disable 0612
const PrimFlags DEFAULT_FLAGS =
PrimFlags.ObjectModify |
PrimFlags.ObjectCopy |
PrimFlags.ObjectMove |
PrimFlags.ObjectTransfer |
PrimFlags.ObjectYouOwner |
PrimFlags.ObjectAnyOwner |
PrimFlags.ObjectOwnerModify;
#pragma warning restore 0612
if (part == null)
return 0;
uint perms = part.GetEffectiveObjectFlags() | (uint)DEFAULT_FLAGS;
GenerateClientFlagsHandler handlerGenerateClientFlags = OnGenerateClientFlags;
if (handlerGenerateClientFlags != null)
{
Delegate[] list = handlerGenerateClientFlags.GetInvocationList();
foreach (GenerateClientFlagsHandler check in list)
{
perms &= check(part, sp, perms);
}
}
return perms;
}
public void SetBypassPermissions(bool value)
{
SetBypassPermissionsHandler handler = OnSetBypassPermissions;
if (handler != null)
handler(value);
}
public bool BypassPermissions()
{
BypassPermissionsHandler handler = OnBypassPermissions;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (BypassPermissionsHandler h in list)
{
if (h() == false)
return false;
}
}
return true;
}
public bool PropagatePermissions()
{
PropagatePermissionsHandler handler = OnPropagatePermissions;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (PropagatePermissionsHandler h in list)
{
if (h() == false)
return false;
}
}
return true;
}
#region REZ OBJECT
public bool CanRezObject(int objectCount, UUID owner, Vector3 objectPosition)
{
RezObjectHandler handler = OnRezObject;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (RezObjectHandler h in list)
{
if (h(objectCount, owner,objectPosition) == false)
return false;
}
}
return true;
}
#endregion
#region DELETE OBJECT
public bool CanDeleteObject(UUID objectID, UUID deleter)
{
bool result = true;
DeleteObjectHandlerByIDs handler = OnDeleteObjectByIDs;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (DeleteObjectHandlerByIDs h in list)
{
if (h(objectID, deleter) == false)
{
result = false;
break;
}
}
}
return result;
}
public bool CanDeleteObject(SceneObjectGroup sog, IClientAPI client)
{
bool result = true;
DeleteObjectHandler handler = OnDeleteObject;
if (handler != null)
{
if(sog == null || client == null || client.SceneAgent == null)
return false;
ScenePresence sp = client.SceneAgent as ScenePresence;
Delegate[] list = handler.GetInvocationList();
foreach (DeleteObjectHandler h in list)
{
if (h(sog, sp) == false)
{
result = false;
break;
}
}
}
return result;
}
public bool CanTransferObject(UUID objectID, UUID recipient)
{
bool result = true;
TransferObjectHandler handler = OnTransferObject;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (TransferObjectHandler h in list)
{
if (h(objectID, recipient) == false)
{
result = false;
break;
}
}
}
return result;
}
#endregion
#region TAKE OBJECT
public bool CanTakeObject(SceneObjectGroup sog, ScenePresence sp)
{
bool result = true;
TakeObjectHandler handler = OnTakeObject;
if (handler != null)
{
if(sog == null || sp == null)
return false;
Delegate[] list = handler.GetInvocationList();
foreach (TakeObjectHandler h in list)
{
if (h(sog, sp) == false)
{
result = false;
break;
}
}
}
// m_log.DebugFormat(
// "[SCENE PERMISSIONS]: CanTakeObject() fired for object {0}, taker {1}, result {2}",
// objectID, AvatarTakingUUID, result);
return result;
}
#endregion
#region SELL GROUP OBJECT
public bool CanSellGroupObject(UUID userID, UUID groupID)
{
bool result = true;
SellGroupObjectHandler handler = OnSellGroupObject;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (SellGroupObjectHandler h in list)
{
if (h(userID, groupID) == false)
{
result = false;
break;
}
}
}
//m_log.DebugFormat(
// "[SCENE PERMISSIONS]: CanSellGroupObject() fired for user {0}, group {1}, result {2}",
// userID, groupID, result);
return result;
}
#endregion
#region TAKE COPY OBJECT
public bool CanTakeCopyObject(SceneObjectGroup sog, ScenePresence sp)
{
bool result = true;
TakeCopyObjectHandler handler = OnTakeCopyObject;
if (handler != null)
{
if(sog == null || sp == null)
return false;
Delegate[] list = handler.GetInvocationList();
foreach (TakeCopyObjectHandler h in list)
{
if (h(sog, sp) == false)
{
result = false;
break;
}
}
}
// m_log.DebugFormat(
// "[SCENE PERMISSIONS]: CanTakeCopyObject() fired for object {0}, user {1}, result {2}",
// objectID, userID, result);
return result;
}
#endregion
#region DUPLICATE OBJECT
public bool CanDuplicateObject(SceneObjectGroup sog, UUID agentID)
{
DuplicateObjectHandler handler = OnDuplicateObject;
if (handler != null)
{
if(sog == null || sog.IsDeleted)
return false;
ScenePresence sp = m_scene.GetScenePresence(agentID);
if(sp == null || sp.IsDeleted)
return false;
Delegate[] list = handler.GetInvocationList();
foreach (DuplicateObjectHandler h in list)
{
if (h(sog, sp) == false)
return false;
}
}
return true;
}
#endregion
#region persence EDIT or MOVE OBJECT
private const uint CANSELECTMASK = (uint)(
PrimFlags.ObjectMove |
PrimFlags.ObjectModify |
PrimFlags.ObjectOwnerModify
);
public bool CanChangeSelectedState(SceneObjectPart part, ScenePresence sp)
{
uint perms = GenerateClientFlags(part, sp);
return (perms & CANSELECTMASK) != 0;
}
#endregion
#region EDIT OBJECT
public bool CanEditObject(UUID objectID, UUID editorID)
{
EditObjectByIDsHandler handler = OnEditObjectByIDs;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (EditObjectByIDsHandler h in list)
{
if (h(objectID, editorID) == false)
return false;
}
}
return true;
}
public bool CanEditObject(SceneObjectGroup sog, IClientAPI client)
{
EditObjectHandler handler = OnEditObject;
if (handler != null)
{
if(sog == null || client == null || client.SceneAgent == null)
return false;
ScenePresence sp = client.SceneAgent as ScenePresence;
Delegate[] list = handler.GetInvocationList();
foreach (EditObjectHandler h in list)
{
if (h(sog, sp) == false)
return false;
}
}
return true;
}
public bool CanEditObjectInventory(UUID objectID, UUID editorID)
{
EditObjectInventoryHandler handler = OnEditObjectInventory;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (EditObjectInventoryHandler h in list)
{
if (h(objectID, editorID) == false)
return false;
}
}
return true;
}
#endregion
#region MOVE OBJECT
public bool CanMoveObject(SceneObjectGroup sog, IClientAPI client)
{
MoveObjectHandler handler = OnMoveObject;
if (handler != null)
{
if(sog == null || client == null || client.SceneAgent == null)
return false;
ScenePresence sp = client.SceneAgent as ScenePresence;
Delegate[] list = handler.GetInvocationList();
foreach (MoveObjectHandler h in list)
{
if (h(sog, sp) == false)
return false;
}
}
return true;
}
#endregion
#region OBJECT ENTRY
public bool CanObjectEntry(SceneObjectGroup sog, bool enteringRegion, Vector3 newPoint)
{
ObjectEntryHandler handler = OnObjectEntry;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (ObjectEntryHandler h in list)
{
if (h(sog, enteringRegion, newPoint) == false)
return false;
}
}
return true;
}
#endregion
#region RETURN OBJECT
public bool CanReturnObjects(ILandObject land, IClientAPI client, List<SceneObjectGroup> objects)
{
bool result = true;
ReturnObjectsHandler handler = OnReturnObjects;
if (handler != null)
{
if(objects == null)
return false;
ScenePresence sp = null;
if(client != null && client.SceneAgent != null)
sp = client.SceneAgent as ScenePresence;
Delegate[] list = handler.GetInvocationList();
foreach (ReturnObjectsHandler h in list)
{
if (h(land, sp, objects) == false)
{
result = false;
break;
}
}
}
// m_log.DebugFormat(
// "[SCENE PERMISSIONS]: CanReturnObjects() fired for user {0} for {1} objects on {2}, result {3}",
// user, objects.Count, land.LandData.Name, result);
return result;
}
#endregion
#region INSTANT MESSAGE
public bool CanInstantMessage(UUID user, UUID target)
{
InstantMessageHandler handler = OnInstantMessage;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (InstantMessageHandler h in list)
{
if (h(user, target) == false)
return false;
}
}
return true;
}
#endregion
#region INVENTORY TRANSFER
public bool CanInventoryTransfer(UUID user, UUID target)
{
InventoryTransferHandler handler = OnInventoryTransfer;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (InventoryTransferHandler h in list)
{
if (h(user, target) == false)
return false;
}
}
return true;
}
#endregion
#region VIEW SCRIPT
public bool CanViewScript(UUID script, UUID objectID, UUID user)
{
ViewScriptHandler handler = OnViewScript;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (ViewScriptHandler h in list)
{
if (h(script, objectID, user) == false)
return false;
}
}
return true;
}
public bool CanViewNotecard(UUID script, UUID objectID, UUID user)
{
ViewNotecardHandler handler = OnViewNotecard;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (ViewNotecardHandler h in list)
{
if (h(script, objectID, user) == false)
return false;
}
}
return true;
}
#endregion
#region EDIT SCRIPT
public bool CanEditScript(UUID script, UUID objectID, UUID user)
{
EditScriptHandler handler = OnEditScript;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (EditScriptHandler h in list)
{
if (h(script, objectID, user) == false)
return false;
}
}
return true;
}
public bool CanEditNotecard(UUID script, UUID objectID, UUID user)
{
EditNotecardHandler handler = OnEditNotecard;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (EditNotecardHandler h in list)
{
if (h(script, objectID, user) == false)
return false;
}
}
return true;
}
#endregion
#region RUN SCRIPT (When Script Placed in Object)
public bool CanRunScript(UUID script, UUID objectID, UUID user)
{
RunScriptHandlerByIDs handler = OnRunScriptByIDs;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (RunScriptHandlerByIDs h in list)
{
if (h(script, objectID, user) == false)
return false;
}
}
return true;
}
public bool CanRunScript(TaskInventoryItem item, SceneObjectPart part)
{
RunScriptHandler handler = OnRunScript;
if (handler != null)
{
if(item == null || part == null)
return false;
Delegate[] list = handler.GetInvocationList();
foreach (RunScriptHandler h in list)
{
if (h(item, part) == false)
return false;
}
}
return true;
}
#endregion
#region COMPILE SCRIPT (When Script needs to get (re)compiled)
public bool CanCompileScript(UUID ownerUUID, int scriptType)
{
CompileScriptHandler handler = OnCompileScript;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (CompileScriptHandler h in list)
{
if (h(ownerUUID, scriptType) == false)
return false;
}
}
return true;
}
#endregion
#region START SCRIPT (When Script run box is Checked after placed in object)
public bool CanStartScript(UUID script, UUID user)
{
StartScriptHandler handler = OnStartScript;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (StartScriptHandler h in list)
{
if (h(script, user) == false)
return false;
}
}
return true;
}
#endregion
#region STOP SCRIPT (When Script run box is unchecked after placed in object)
public bool CanStopScript(UUID script, UUID user)
{
StopScriptHandler handler = OnStopScript;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (StopScriptHandler h in list)
{
if (h(script, user) == false)
return false;
}
}
return true;
}
#endregion
#region RESET SCRIPT
public bool CanResetScript(UUID prim, UUID script, UUID user)
{
ResetScriptHandler handler = OnResetScript;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (ResetScriptHandler h in list)
{
if (h(prim, script, user) == false)
return false;
}
}
return true;
}
#endregion
#region TERRAFORM LAND
public bool CanTerraformLand(UUID user, Vector3 pos)
{
TerraformLandHandler handler = OnTerraformLand;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (TerraformLandHandler h in list)
{
if (h(user, pos) == false)
return false;
}
}
return true;
}
#endregion
#region RUN CONSOLE COMMAND
public bool CanRunConsoleCommand(UUID user)
{
RunConsoleCommandHandler handler = OnRunConsoleCommand;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (RunConsoleCommandHandler h in list)
{
if (h(user) == false)
return false;
}
}
return true;
}
#endregion
#region CAN ISSUE ESTATE COMMAND
public bool CanIssueEstateCommand(UUID user, bool ownerCommand)
{
IssueEstateCommandHandler handler = OnIssueEstateCommand;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (IssueEstateCommandHandler h in list)
{
if (h(user, ownerCommand) == false)
return false;
}
}
return true;
}
#endregion
#region CAN BE GODLIKE
public bool IsGod(UUID user)
{
IsAdministratorHandler handler = OnIsAdministrator;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (IsAdministratorHandler h in list)
{
if (h(user) == false)
return false;
}
}
return true;
}
public bool IsGridGod(UUID user)
{
IsGridGodHandler handler = OnIsGridGod;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (IsGridGodHandler h in list)
{
if (h(user) == false)
return false;
}
}
return true;
}
public bool IsAdministrator(UUID user)
{
IsAdministratorHandler handler = OnIsAdministrator;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (IsAdministratorHandler h in list)
{
if (h(user) == false)
return false;
}
}
return true;
}
#endregion
public bool IsEstateManager(UUID user)
{
IsEstateManagerHandler handler = OnIsEstateManager;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (IsEstateManagerHandler h in list)
{
if (h(user) == false)
return false;
}
}
return true;
}
#region EDIT PARCEL
public bool CanEditParcelProperties(UUID user, ILandObject parcel, GroupPowers p, bool allowManager)
{
EditParcelPropertiesHandler handler = OnEditParcelProperties;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (EditParcelPropertiesHandler h in list)
{
if (h(user, parcel, p, allowManager) == false)
return false;
}
}
return true;
}
#endregion
#region SELL PARCEL
public bool CanSellParcel(UUID user, ILandObject parcel)
{
SellParcelHandler handler = OnSellParcel;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (SellParcelHandler h in list)
{
if (h(user, parcel) == false)
return false;
}
}
return true;
}
#endregion
#region ABANDON PARCEL
public bool CanAbandonParcel(UUID user, ILandObject parcel)
{
AbandonParcelHandler handler = OnAbandonParcel;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (AbandonParcelHandler h in list)
{
if (h(user, parcel) == false)
return false;
}
}
return true;
}
#endregion
public bool CanReclaimParcel(UUID user, ILandObject parcel)
{
ReclaimParcelHandler handler = OnReclaimParcel;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (ReclaimParcelHandler h in list)
{
if (h(user, parcel) == false)
return false;
}
}
return true;
}
public bool CanDeedParcel(UUID user, ILandObject parcel)
{
DeedParcelHandler handler = OnDeedParcel;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (DeedParcelHandler h in list)
{
if (h(user, parcel) == false)
return false;
}
}
return true;
}
public bool CanDeedObject(IClientAPI client, SceneObjectGroup sog, UUID targetGroupID)
{
DeedObjectHandler handler = OnDeedObject;
if (handler != null)
{
if(sog == null || client == null || client.SceneAgent == null || targetGroupID == UUID.Zero)
return false;
ScenePresence sp = client.SceneAgent as ScenePresence;
Delegate[] list = handler.GetInvocationList();
foreach (DeedObjectHandler h in list)
{
if (h(sp, sog, targetGroupID) == false)
return false;
}
}
return true;
}
public bool CanBuyLand(UUID user, ILandObject parcel)
{
BuyLandHandler handler = OnBuyLand;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (BuyLandHandler h in list)
{
if (h(user, parcel) == false)
return false;
}
}
return true;
}
public bool CanLinkObject(UUID user, UUID objectID)
{
LinkObjectHandler handler = OnLinkObject;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (LinkObjectHandler h in list)
{
if (h(user, objectID) == false)
return false;
}
}
return true;
}
public bool CanDelinkObject(UUID user, UUID objectID)
{
DelinkObjectHandler handler = OnDelinkObject;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (DelinkObjectHandler h in list)
{
if (h(user, objectID) == false)
return false;
}
}
return true;
}
#endregion
/// Check whether the specified user is allowed to directly create the given inventory type in a prim's
/// inventory (e.g. the New Script button in the 1.21 Linden Lab client).
/// </summary>
/// <param name="invType"></param>
/// <param name="objectID"></param>
/// <param name="userID"></param>
/// <returns></returns>
public bool CanCreateObjectInventory(int invType, UUID objectID, UUID userID)
{
CreateObjectInventoryHandler handler = OnCreateObjectInventory;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (CreateObjectInventoryHandler h in list)
{
if (h(invType, objectID, userID) == false)
return false;
}
}
return true;
}
public bool CanCopyObjectInventory(UUID itemID, UUID objectID, UUID userID)
{
CopyObjectInventoryHandler handler = OnCopyObjectInventory;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (CopyObjectInventoryHandler h in list)
{
if (h(itemID, objectID, userID) == false)
return false;
}
}
return true;
}
public bool CanDoObjectInvToObjectInv(TaskInventoryItem item, SceneObjectPart sourcePart, SceneObjectPart destPart)
{
DoObjectInvToObjectInv handler = OnDoObjectInvToObjectInv;
if (handler != null)
{
if (sourcePart == null || destPart == null || item == null)
return false;
Delegate[] list = handler.GetInvocationList();
foreach (DoObjectInvToObjectInv h in list)
{
if (h(item, sourcePart, destPart) == false)
return false;
}
}
return true;
}
public bool CanDropInObjectInv(InventoryItemBase item, IClientAPI client, SceneObjectPart destPart)
{
DoDropInObjectInv handler = OnDropInObjectInv;
if (handler != null)
{
if (client == null || client.SceneAgent == null|| destPart == null || item == null)
return false;
ScenePresence sp = client.SceneAgent as ScenePresence;
if(sp == null || sp.IsDeleted)
return false;
Delegate[] list = handler.GetInvocationList();
foreach (DoDropInObjectInv h in list)
{
if (h(item, sp, destPart) == false)
return false;
}
}
return true;
}
public bool CanDeleteObjectInventory(UUID itemID, UUID objectID, UUID userID)
{
DeleteObjectInventoryHandler handler = OnDeleteObjectInventory;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (DeleteObjectInventoryHandler h in list)
{
if (h(itemID, objectID, userID) == false)
return false;
}
}
return true;
}
public bool CanTransferObjectInventory(UUID itemID, UUID objectID, UUID userID)
{
TransferObjectInventoryHandler handler = OnTransferObjectInventory;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (TransferObjectInventoryHandler h in list)
{
if (h(itemID, objectID, userID) == false)
return false;
}
}
return true;
}
/// <summary>
/// Check whether the specified user is allowed to create the given inventory type in their inventory.
/// </summary>
/// <param name="invType"></param>
/// <param name="userID"></param>
/// <returns></returns>
public bool CanCreateUserInventory(int invType, UUID userID)
{
CreateUserInventoryHandler handler = OnCreateUserInventory;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (CreateUserInventoryHandler h in list)
{
if (h(invType, userID) == false)
return false;
}
}
return true;
}
/// <summary>
/// Check whether the specified user is allowed to edit the given inventory item within their own inventory.
/// </summary>
/// <param name="itemID"></param>
/// <param name="userID"></param>
/// <returns></returns>
public bool CanEditUserInventory(UUID itemID, UUID userID)
{
EditUserInventoryHandler handler = OnEditUserInventory;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (EditUserInventoryHandler h in list)
{
if (h(itemID, userID) == false)
return false;
}
}
return true;
}
/// <summary>
/// Check whether the specified user is allowed to copy the given inventory item from their own inventory.
/// </summary>
/// <param name="itemID"></param>
/// <param name="userID"></param>
/// <returns></returns>
public bool CanCopyUserInventory(UUID itemID, UUID userID)
{
CopyUserInventoryHandler handler = OnCopyUserInventory;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (CopyUserInventoryHandler h in list)
{
if (h(itemID, userID) == false)
return false;
}
}
return true;
}
/// <summary>
/// Check whether the specified user is allowed to edit the given inventory item within their own inventory.
/// </summary>
/// <param name="itemID"></param>
/// <param name="userID"></param>
/// <returns></returns>
public bool CanDeleteUserInventory(UUID itemID, UUID userID)
{
DeleteUserInventoryHandler handler = OnDeleteUserInventory;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (DeleteUserInventoryHandler h in list)
{
if (h(itemID, userID) == false)
return false;
}
}
return true;
}
public bool CanTransferUserInventory(UUID itemID, UUID userID, UUID recipientID)
{
TransferUserInventoryHandler handler = OnTransferUserInventory;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (TransferUserInventoryHandler h in list)
{
if (h(itemID, userID, recipientID) == false)
return false;
}
}
return true;
}
public bool CanTeleport(UUID userID)
{
TeleportHandler handler = OnTeleport;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (TeleportHandler h in list)
{
if (h(userID, m_scene) == false)
return false;
}
}
return true;
}
public bool CanControlPrimMedia(UUID userID, UUID primID, int face)
{
ControlPrimMediaHandler handler = OnControlPrimMedia;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (ControlPrimMediaHandler h in list)
{
if (h(userID, primID, face) == false)
return false;
}
}
return true;
}
public bool CanInteractWithPrimMedia(UUID userID, UUID primID, int face)
{
InteractWithPrimMediaHandler handler = OnInteractWithPrimMedia;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (InteractWithPrimMediaHandler h in list)
{
if (h(userID, primID, face) == false)
return false;
}
}
return true;
}
}
}
| |
// Malcolm Crowe 1995,2000
// As far as possible the regular expression notation follows that of lex
using System;
using System.Collections;
using System.IO;
using System.Text;
using System.Globalization;
namespace Tools
{
// We cleverly arrange for the YyLexer class to serialize itself out of a simple integer array.
// So: to use the lexer generated for a script, include the generated tokens.cs file in the build,
// This defines classes tokens (subclass of Lexer) and yytokens (subclass of YyLexer).
// Call Lexer::Start() to start the input engine going, and then use the
// Lexer::Next() function to get successive TOKENs.
// Note that if you are using ParserGenerator, this is done for you.
/// <exclude/>
public class YyLexer // we will gather all formerly static definitions for lexing here and in LexerGenerate
{
// Deserializing
/// <exclude/>
public void GetDfa()
{
if (tokens.Count>0)
return;
Serialiser f = new Serialiser(arr);
f.VersionCheck();
m_encoding = (Encoding)f.Deserialise();
toupper = (bool)f.Deserialise();
cats = (Hashtable)f.Deserialise();
m_gencat = (UnicodeCategory)f.Deserialise();
usingEOF = (bool)f.Deserialise();
starts = (Hashtable)f.Deserialise();
Dfa.SetTokens(this,starts);
tokens = (Hashtable)f.Deserialise();
reswds = (Hashtable)f.Deserialise();
}
#if (GENTIME)
/// <exclude/>
public void EmitDfa(TextWriter outFile)
{
Console.WriteLine("Serializing the lexer");
Serialiser f = new Serialiser(outFile);
f.VersionCheck();
f.Serialise(m_encoding);
f.Serialise(toupper);
f.Serialise(cats);
f.Serialise(m_gencat);
f.Serialise(usingEOF);
f.Serialise(starts);
f.Serialise(tokens);
f.Serialise(reswds);
outFile.WriteLine("0};");
}
#endif
// support for Unicode character sets
/// <exclude/>
public Encoding m_encoding = Encoding.ASCII; // overwritten by Deserialize
/// <exclude/>
public string InputEncoding
{
set
{
m_encoding = Charset.GetEncoding(value,ref toupper,erh);
}
}
/// <exclude/>
public bool usingEOF = false;
/// <exclude/>
public bool toupper = false; // for ASCIICAPS
/// <exclude/>
public Hashtable cats = new Hashtable(); // UnicodeCategory -> Charset
/// <exclude/>
public UnicodeCategory m_gencat; // not a UsingCat unless all usbale cats in use
// support for lexer states
/// <exclude/>
public Hashtable starts = new Hashtable(); // string->Dfa
// support for serialization
/// <exclude/>
protected int[] arr; // defined in generated tokens class
// support for token classes
/// <exclude/>
public Hashtable types = new Hashtable(); // string->TCreator
/// <exclude/>
public Hashtable tokens = new Hashtable(); // string->TokClassDef
// support for reserved word sets
/// <exclude/>
public Hashtable reswds = new Hashtable(); // int->ResWds
/// <exclude/>
public ErrorHandler erh;
/// <exclude/>
public YyLexer(ErrorHandler eh)
{
erh = eh;
#if (GENTIME)
UsingCat(UnicodeCategory.OtherPunctuation);
m_gencat = UnicodeCategory.OtherPunctuation;
#endif
new Tfactory(this,"TOKEN",new TCreator(Tokenfactory));
}
/// <exclude/>
protected object Tokenfactory(Lexer yyl)
{
return new TOKEN(yyl);
}
#if (GENTIME)
/// <exclude/>
public Charset UsingCat(UnicodeCategory cat)
{
if (cat==m_gencat)
{
for (int j=0;j<28;j++)
{
if (!Enum.IsDefined(typeof(UnicodeCategory),j))
continue;
UnicodeCategory u = (UnicodeCategory)j;
if (u==UnicodeCategory.Surrogate)
continue;
if (cats[u]==null)
{
UsingCat(u);
m_gencat = u;
}
}
return (Charset)cats[cat];
}
if (cats[cat]!=null)
return (Charset)cats[cat];
Charset rv = new Charset(cat);
cats[cat] = rv;
return rv;
}
internal void UsingChar(char ch)
{
UnicodeCategory cat = Char.GetUnicodeCategory(ch);
Charset cs = UsingCat(cat);
if (cs.m_generic==ch)
{
do
{
if (cs.m_generic==char.MaxValue)
{
cs.m_generic = ch; // all used: this m_generic will never be used
return;
}
cs.m_generic++;
} while (Char.GetUnicodeCategory(cs.m_generic)!=cs.m_cat ||
cs.m_chars.Contains(cs.m_generic));
cs.m_chars[cs.m_generic] = true;
}
else
cs.m_chars[ch] = true;
}
#endif
internal char Filter(char ch)
{
UnicodeCategory cat = Char.GetUnicodeCategory(ch);
Charset cs = (Charset)cats[cat];
if (cs==null)
cs = (Charset)cats[m_gencat];
if (cs.m_chars.Contains(ch))
return ch;
return cs.m_generic;
}
bool testEOF(char ch)
{
UnicodeCategory cat = Char.GetUnicodeCategory(ch);
return (cat==UnicodeCategory.OtherNotAssigned);
}
#if (GENTIME)
bool CharIsSymbol(char c)
{
UnicodeCategory u = Char.GetUnicodeCategory(c);
return (u==UnicodeCategory.OtherSymbol || u==UnicodeCategory.ModifierSymbol ||
u==UnicodeCategory.CurrencySymbol || u==UnicodeCategory.MathSymbol);
}
bool CharIsSeparator(char c)
{
UnicodeCategory u = Char.GetUnicodeCategory(c);
return (u==UnicodeCategory.ParagraphSeparator || u==UnicodeCategory.LineSeparator ||
u==UnicodeCategory.SpaceSeparator);
}
internal ChTest GetTest(string name)
{
try {
object o = Enum.Parse(typeof(UnicodeCategory),name);
if (o!=null)
{
UnicodeCategory cat = (UnicodeCategory)o;
UsingCat(cat);
return new ChTest(new CatTest(cat).Test);
}
} catch (Exception) {}
switch (name)
{
case "Symbol":
UsingCat(UnicodeCategory.OtherSymbol);
UsingCat(UnicodeCategory.ModifierSymbol);
UsingCat(UnicodeCategory.CurrencySymbol);
UsingCat(UnicodeCategory.MathSymbol);
return new ChTest(CharIsSymbol);
case "Punctuation":
UsingCat(UnicodeCategory.OtherPunctuation);
UsingCat(UnicodeCategory.FinalQuotePunctuation);
UsingCat(UnicodeCategory.InitialQuotePunctuation);
UsingCat(UnicodeCategory.ClosePunctuation);
UsingCat(UnicodeCategory.OpenPunctuation);
UsingCat(UnicodeCategory.DashPunctuation);
UsingCat(UnicodeCategory.ConnectorPunctuation);
return new ChTest(Char.IsPunctuation);
/* case "PrivateUse":
UsingCat(UnicodeCategory.PrivateUse);
return new ChTest(Char.IsPrivateUse); */
case "Separator":
UsingCat(UnicodeCategory.ParagraphSeparator);
UsingCat(UnicodeCategory.LineSeparator);
UsingCat(UnicodeCategory.SpaceSeparator);
return new ChTest(CharIsSeparator);
case "WhiteSpace":
UsingCat(UnicodeCategory.Control);
UsingCat(UnicodeCategory.ParagraphSeparator);
UsingCat(UnicodeCategory.LineSeparator);
UsingCat(UnicodeCategory.SpaceSeparator);
return new ChTest(Char.IsWhiteSpace);
case "Number":
UsingCat(UnicodeCategory.OtherNumber);
UsingCat(UnicodeCategory.LetterNumber);
UsingCat(UnicodeCategory.DecimalDigitNumber);
return new ChTest(Char.IsNumber);
case "Digit":
UsingCat(UnicodeCategory.DecimalDigitNumber);
return new ChTest(Char.IsDigit);
/* case "Mark":
UsingCat(UnicodeCategory.EnclosingMark);
UsingCat(UnicodeCategory.SpacingCombiningMark);
UsingCat(UnicodeCategory.NonSpacingMark);
return new ChTest(Char.IsMark); */
case "Letter":
UsingCat(UnicodeCategory.OtherLetter);
UsingCat(UnicodeCategory.ModifierLetter);
UsingCat(UnicodeCategory.TitlecaseLetter);
UsingCat(UnicodeCategory.LowercaseLetter);
UsingCat(UnicodeCategory.UppercaseLetter);
return new ChTest(Char.IsLetter);
case "Lower":
UsingCat(UnicodeCategory.LowercaseLetter);
return new ChTest(Char.IsLower);
case "Upper":
UsingCat(UnicodeCategory.UppercaseLetter);
return new ChTest(Char.IsUpper);
case "EOF":
UsingCat(UnicodeCategory.OtherNotAssigned);
UsingChar((char)0xFFFF);
usingEOF=true;
return new ChTest(testEOF);
default:
erh.Error(new CSToolsException(24,"No such Charset "+name));
break;
}
return new ChTest(Char.IsControl); // not reached
}
#endif
/// <exclude/>
public virtual TOKEN OldAction(Lexer yyl,ref string yytext,int action,ref bool reject)
{
return null;
}
/// <exclude/>
public IEnumerator GetEnumerator()
{
return tokens.Values.GetEnumerator();
}
}
/// <exclude/>
public class LineManager
{
/// <exclude/>
public int lines = 1; // for error messages etc
/// <exclude/>
public int end = 0; // high water mark of positions
/// <exclude/>
public LineList list = null;
/// <exclude/>
public LineManager() {}
/// <exclude/>
public void newline(int pos)
{
lines++;
backto(pos);
list = new LineList(pos,list);
}
/// <exclude/>
public void backto(int pos)
{
if (pos>end)
end = pos;
while (list!=null && list.head>=pos)
{
list = list.tail;
lines--;
}
}
/// <exclude/>
public void comment(int pos,int len)
{ // only for C-style comments not C++
if (pos>end)
end = pos;
if (list==null)
{
list = new LineList(0,list);
lines = 1;
}
list.comments = new CommentList(pos,len,list.comments);
}
}
#if (GENTIME)
/// <exclude/>
public abstract class TokensGen : GenBase
{
/// <exclude/>
public TokensGen(ErrorHandler eh):base(eh) {}
/// <exclude/>
protected bool m_showDfa;
/// <exclude/>
public YyLexer m_tokens; // the YyLexer class under construction
/// <exclude/>
// %defines in script
public Hashtable defines = new Hashtable(); // string->string
/// <exclude/>
// support for Nfa networks
int state = 0;
/// <exclude/>
public int NewState() { return ++state; } // for LNodes
/// <exclude/>
public ObjectList states = new ObjectList(); // Dfa
/// <exclude/>
public string FixActions(string str)
{
return str.Replace("yybegin","yym.yy_begin").Replace("yyl","(("+m_outname+")yym)");
}
}
#endif
// support for Unicode character sets
internal delegate bool ChTest(char ch);
/// <exclude/>
public class CatTest
{
UnicodeCategory cat;
/// <exclude/>
public CatTest(UnicodeCategory c) { cat = c; }
/// <exclude/>
public bool Test(char ch)
{
return Char.GetUnicodeCategory(ch)==cat;
}
}
/// <exclude/>
public class Charset
{
internal UnicodeCategory m_cat;
internal char m_generic; // not explicitly Using'ed allUsed
internal Hashtable m_chars = new Hashtable(); // char->bool
Charset(){}
#if (GENTIME)
internal Charset(UnicodeCategory cat)
{
m_cat = cat;
for (m_generic=char.MinValue;Char.GetUnicodeCategory(m_generic)!=cat;m_generic++)
;
m_chars[m_generic] = true;
}
#endif
/// <exclude/>
public static Encoding GetEncoding(string enc, ref bool toupper,ErrorHandler erh)
{
switch (enc)
{
case "": return Encoding.Default; // locale-specific
case "ASCII": return Encoding.ASCII;
case "ASCIICAPS": toupper=true; return Encoding.ASCII; // toupper is currently ignored in scripts
case "UTF7": return Encoding.UTF7;
case "UTF8": return Encoding.UTF8;
case "Unicode": return Encoding.Unicode;
default:
try
{
return Encoding.GetEncoding(int.Parse(enc)); // codepage
}
catch (Exception)
{
erh.Error(new CSToolsException(43,"Warning: Encoding "+enc+" unknown: ignored"));
}
break;
}
return Encoding.ASCII;
}
/// <exclude/>
public static object Serialise(object o,Serialiser s)
{
if (s==null)
return new Charset();
Charset c = (Charset)o;
if (s.Encode)
{
s.Serialise((int)c.m_cat);
s.Serialise(c.m_generic);
s.Serialise(c.m_chars);
return null;
}
c.m_cat = (UnicodeCategory)s.Deserialise();
c.m_generic = (char)s.Deserialise();
c.m_chars = (Hashtable)s.Deserialise();
return c;
}
}
// Support for runtime object creation
/// <exclude/>
public delegate object TCreator(Lexer yyl);
/// <exclude/>
public class Tfactory
{
/// <exclude/>
public static object create(string cls_name,Lexer yyl)
{
TCreator cr = (TCreator) yyl.tokens.types[cls_name];
// Console.WriteLine("TCreating {0} <{1}>",cls_name,yyl.yytext);
if (cr==null)
yyl.tokens.erh.Error(new CSToolsException(6,yyl,cls_name,String.Format("no factory for {0}",cls_name)));
try
{
return cr(yyl);
}
catch (CSToolsException x)
{
yyl.tokens.erh.Error(x);
}
catch (Exception e)
{
yyl.tokens.erh.Error(new CSToolsException(7,yyl,cls_name,
String.Format("Line {0}: Create of {1} failed ({2})",yyl.Saypos(yyl.m_pch),cls_name,e.Message)));
}
int j = cls_name.LastIndexOf('_');
if (j>0)
{
cr = (TCreator)yyl.tokens.types[cls_name.Substring(0,j)];
if (cr!=null)
return cr(yyl);
}
return null;
}
/// <exclude/>
public Tfactory(YyLexer tks,string cls_name,TCreator cr)
{
tks.types[cls_name] = cr;
}
}
/// <exclude/>
public class SourceLineInfo
{
/// <exclude/>
public int lineNumber;
/// <exclude/>
public int charPosition;
/// <exclude/>
public int startOfLine;
/// <exclude/>
public int endOfLine;
/// <exclude/>
public int rawCharPosition;
/// <exclude/>
public Lexer lxr = null;
/// <exclude/>
public SourceLineInfo(int pos) // this constructor is not used in anger
{
lineNumber = 1;
startOfLine = 0;
endOfLine = rawCharPosition = charPosition = pos;
}
/// <exclude/>
public SourceLineInfo(LineManager lm,int pos)
{
lineNumber = lm.lines;
startOfLine = 0;
endOfLine = lm.end;
charPosition = pos;
rawCharPosition = pos;
for (LineList p = lm.list; p!=null; p = p.tail, lineNumber-- )
if (p.head>pos)
endOfLine = p.head;
else
{
startOfLine = p.head+1;
rawCharPosition = p.getpos(pos);
charPosition = pos-startOfLine+1;
break;
}
}
/// <exclude/>
public SourceLineInfo(Lexer lx,int pos) :this(lx.m_LineManager,pos) { lxr=lx; } // 4.5c
/// <exclude/>
public override string ToString()
{
return "Line "+lineNumber+", char "+(rawCharPosition+1);
}
/// <exclude/>
public string sourceLine { get { if (lxr==null) return ""; return lxr.sourceLine(this); }}
}
/// <exclude/>
public class LineList
{
/// <exclude/>
public int head;
/// <exclude/>
public CommentList comments = null;
/// <exclude/>
public LineList tail; // previous line!
/// <exclude/>
public LineList(int h, LineList t)
{
head=h;
comments = null;
tail=t;
}
/// <exclude/>
public int getpos(int pos)
{
int n = pos-head;
for (CommentList c = comments; c!=null; c=c.tail)
if (pos>c.spos)
n += c.len;
return n;
}
}
/// <exclude/>
public class CommentList
{
/// <exclude/>
public int spos,len;
/// <exclude/>
public CommentList tail = null;
/// <exclude/>
public CommentList(int st,int ln, CommentList t)
{
spos = st; len = ln;
tail = t;
}
}
// the following class gets rid of comments for us
/// <exclude/>
public class CsReader
{
/// <exclude/>
public string fname = "";
TextReader m_stream;
/// <exclude/>
public LineManager lm = new LineManager();
int back; // one-char pushback
enum State
{
copy, sol, c_com, cpp_com, c_star, at_eof, transparent
}
State state;
int pos = 0;
bool sol = true;
/// <exclude/>
public CsReader(string data)
{
m_stream = new StringReader(data);
state= State.copy;
back = -1;
}
/// <exclude/>
public CsReader(string fileName,Encoding enc)
{
fname = fileName;
FileStream fs = new FileStream(fileName,FileMode.Open,FileAccess.Read);
m_stream = new StreamReader(fs,enc);
state= State.copy; back = -1;
}
/// <exclude/>
public CsReader(CsReader inf,Encoding enc)
{
fname = inf.fname;
if (inf.m_stream is StreamReader)
m_stream = new StreamReader(((StreamReader)inf.m_stream).BaseStream,enc);
else
m_stream = new StreamReader(inf.m_stream.ReadToEnd());
state= State.copy; back = -1;
}
/// <exclude/>
public bool Eof() { return state==State.at_eof; }
/// <exclude/>
public int Read(char[] arr,int offset,int count)
{
int c,n;
for (n=0;count>0;count--,n++)
{
c = Read();
if (c<0)
break;
arr[offset+n] = (char)c;
}
return n;
}
/// <exclude/>
public string ReadLine()
{
int c=0,n;
char[] buf = new char[1024];
int count = 1024;
for (n=0;count>0;count--)
{
c = Read();
if (((char)c)=='\r')
continue;
if (c<0 || ((char)c)=='\n')
break;
buf[n++] = (char)c;
}
if (c<0)
state = State.at_eof;
return new string(buf,0,n);
}
/// <exclude/>
public int Read()
{
int c,comlen = 0;
if (state==State.at_eof)
return -1;
while (true)
{
// get a character
if (back>=0)
{ // back is used only in copy mode
c = back; back = -1;
}
else if (state==State.at_eof)
c = -1;
else
c = m_stream.Read();
if (c=='\r')
continue;
while (sol && c=='#') // deal with #line directive
{
while (c!=' ')
c = m_stream.Read();
lm.lines = 0;
while (c==' ')
c = m_stream.Read();
while (c>='0' && c<='9')
{
lm.lines = lm.lines*10+(c-'0');
c = m_stream.Read();
}
while (c==' ')
c = m_stream.Read();
if (c=='"')
{
fname = "";
c = m_stream.Read();
while (c!='"')
{
fname += c;
c = m_stream.Read();
}
}
while (c!='\n')
c = m_stream.Read();
if (c=='\r')
c = m_stream.Read();
}
if (c<0)
{ // at EOF we must leave the loop
if (state==State.sol)
c = '/';
state = State.at_eof;
pos++;
return c;
}
sol = false;
// otherwise work through a state machine
switch (state)
{
case State.copy:
if (c=='/')
state = State.sol;
else
{
if (c=='\n')
{
lm.newline(pos);
sol = true;
}
pos++;
return c;
} continue;
case State.sol: // solidus '/'
if (c=='*')
state = State.c_com;
else if (c=='/')
{
comlen = 2;
state = State.cpp_com;
}
else
{
back = c;
state = State.copy;
pos++;
return '/';
}
continue;
case State.c_com:
comlen++;
if (c=='\n')
{
lm.newline(pos);
comlen=0;
sol = true;
}
if (c=='*')
state = State.c_star;
continue;
case State.c_star:
comlen++;
if (c=='/')
{
lm.comment(pos,comlen);
state = State.copy;
}
else
state = State.c_com;
continue;
case State.cpp_com:
if (c=='\n')
{
state = State.copy;
sol = true;
pos++;
return c;
}
else
comlen++;
continue;
}
}
/* notreached */
}
}
/// <exclude/>
public class SYMBOL
{
/// <exclude/>
public object m_dollar;
/// <exclude/>
public static implicit operator int (SYMBOL s) // 4.0c
{
int rv = 0;
object d;
while (((d=s.m_dollar) is SYMBOL) && d!=null)
s = (SYMBOL)d;
try
{
rv =(int)d;
}
catch(Exception e)
{
Console.WriteLine("attempt to convert from "+s.m_dollar.GetType());
throw e;
}
return rv;
}
/// <exclude/>
public int pos;
/// <exclude/>
public int Line { get { return yylx.sourceLineInfo(pos).lineNumber; }}
/// <exclude/>
public int Position { get { return yylx.sourceLineInfo(pos).rawCharPosition; }}
/// <exclude/>
public string Pos { get { return yylx.Saypos(pos); }}
/// <exclude/>
protected SYMBOL() {}
/// <exclude/>
public Lexer yylx;
/// <exclude/>
public object yylval { get { return m_dollar; } set { m_dollar=value; } }
/// <exclude/>
public SYMBOL(Lexer yyl) { yylx=yyl; }
/// <exclude/>
public virtual int yynum { get { return 0; }}
/// <exclude/>
public virtual bool IsTerminal() { return false; }
/// <exclude/>
public virtual bool IsAction() { return false; }
/// <exclude/>
public virtual bool IsCSymbol() { return false; }
/// <exclude/>
public Parser yyps = null;
/// <exclude/>
public YyParser yyact { get { return (yyps!=null)?yyps.m_symbols:null; }}
/// <exclude/>
public SYMBOL(Parser yyp) { yyps=yyp; yylx=yyp.m_lexer; }
/// <exclude/>
public virtual bool Pass(YyParser syms,int snum,out ParserEntry entry)
{
ParsingInfo pi = (ParsingInfo)syms.symbolInfo[yynum];
if (pi==null)
{
string s = string.Format("No parsinginfo for symbol {0} {1}",yyname,yynum);
syms.erh.Error(new CSToolsFatalException(9,yylx,yyname,s));
}
bool r = pi.m_parsetable.Contains(snum);
entry = r?((ParserEntry)pi.m_parsetable[snum]):null;
return r;
}
/// <exclude/>
public virtual string yyname { get { return "SYMBOL"; }}
/// <exclude/>
public override string ToString() { return yyname; }
/// <exclude/>
public virtual bool Matches(string s) { return false; }
/// <exclude/>
public virtual void Print() { Console.WriteLine(ToString()); }
// 4.2a Support for automatic display of concrete syntax tree
/// <exclude/>
public ObjectList kids = new ObjectList();
void ConcreteSyntaxTree(string n)
{
if (this is error)
Console.WriteLine(n+" "+ToString());
else
Console.WriteLine(n+"-"+ToString());
int j=0;
foreach(SYMBOL s in kids)
s.ConcreteSyntaxTree(n+((j++==kids.Count-1)?" ":" |"));
}
/// <exclude/>
public virtual void ConcreteSyntaxTree() { ConcreteSyntaxTree(""); }
}
/// <exclude/>
public class TOKEN : SYMBOL
{
/// <exclude/>
public string yytext { get { return m_str; } set { m_str=value; } }
string m_str;
/// <exclude/>
public TOKEN(Parser yyp):base(yyp) {}
/// <exclude/>
public TOKEN(Lexer yyl) : base(yyl) { if (yyl!=null) m_str=yyl.yytext; }
/// <exclude/>
public TOKEN(Lexer yyl,string s) :base(yyl) { m_str=s; }
/// <exclude/>
protected TOKEN() {}
/// <exclude/>
public override bool IsTerminal() { return true; }
int num = 1;
/// <exclude/>
public override bool Pass(YyParser syms,int snum,out ParserEntry entry)
{
if (yynum==1)
{
Literal lit = (Literal)syms.literals[yytext];
if (lit!=null)
num = (int)lit.m_yynum;
}
ParsingInfo pi = (ParsingInfo)syms.symbolInfo[yynum];
if (pi==null)
{
string s = string.Format("Parser does not recognise literal {0}",yytext);
syms.erh.Error(new CSToolsFatalException(9,yylx,yyname,s));
}
bool r = pi.m_parsetable.Contains(snum);
entry = r?((ParserEntry)pi.m_parsetable[snum]):null;
return r;
}
/// <exclude/>
public override string yyname { get { return "TOKEN"; }}
/// <exclude/>
public override int yynum { get { return num; }}
/// <exclude/>
public override bool Matches(string s) { return s.Equals(m_str); }
/// <exclude/>
public override string ToString() { return yyname+"<"+ yytext+">"; }
/// <exclude/>
public override void Print() { Console.WriteLine(ToString()); }
}
/// <exclude/>
public class Lexer
{
/// <exclude/>
public bool m_debug = false;
// source line control
/// <exclude/>
public string m_buf;
internal LineManager m_LineManager = new LineManager(); // 4.5b see EOF
/// <exclude/>
public SourceLineInfo sourceLineInfo(int pos)
{
return new SourceLineInfo(this,pos); // 4.5c
}
/// <exclude/>
public string sourceLine(SourceLineInfo s)
{
// This is the sourceLine after removal of comments
// The position in this line is s.charPosition
// If you want the comments as well, then you should re-read the source file
// and the position in the line is s.rawCharPosition
return m_buf.Substring(s.startOfLine,s.endOfLine-s.startOfLine);
}
/// <exclude/>
public string Saypos(int pos)
{
return sourceLineInfo(pos).ToString();
}
// the heart of the lexer is the DFA
/// <exclude/>
public Dfa m_start { get { return (Dfa)m_tokens.starts[m_state]; }}
/// <exclude/>
public string m_state = "YYINITIAL"; // exposed for debugging (by request)
/// <exclude/>
public Lexer(YyLexer tks)
{
m_state="YYINITIAL";
tokens = tks;
}
YyLexer m_tokens;
/// <exclude/>
public YyLexer tokens { get { return m_tokens; } // 4.2d
set { m_tokens=value; m_tokens.GetDfa(); }
}
/// <exclude/>
public string yytext; // for collection when a TOKEN is created
/// <exclude/>
public int m_pch = 0;
/// <exclude/>
public int yypos { get { return m_pch; }}
/// <exclude/>
public void yy_begin(string newstate)
{
m_state = newstate;
}
bool m_matching;
int m_startMatch;
// match a Dfa against lexer's input
bool Match(ref TOKEN tok,Dfa dfa)
{
char ch=PeekChar();
int op=m_pch, mark=0;
Dfa next;
if (m_debug)
{
Console.Write("state {0} with ",dfa.m_state);
if (char.IsLetterOrDigit(ch)||char.IsPunctuation(ch))
Console.WriteLine(ch);
else
Console.WriteLine("#"+(int)ch);
}
if (dfa.m_actions!=null)
{
mark = Mark();
}
if (// ch==0 ||
(next=((Dfa)dfa.m_map[m_tokens.Filter(ch)]))==null)
{
if (m_debug)
Console.Write("{0} no arc",dfa.m_state);
if (dfa.m_actions!=null)
{
if (m_debug)
Console.WriteLine(" terminal");
return TryActions(dfa,ref tok); // fails on REJECT
}
if (m_debug)
Console.WriteLine(" fails");
return false;
}
Advance();
if (!Match(ref tok, next))
{ // rest of string fails
if (m_debug)
Console.WriteLine("back to {0} with {1}",dfa.m_state,ch);
if (dfa.m_actions!=null)
{ // this is still okay at a terminal
if (m_debug)
Console.WriteLine("{0} succeeds",dfa.m_state);
Restore(mark);
return TryActions(dfa,ref tok);
}
if (m_debug)
Console.WriteLine("{0} fails",dfa.m_state);
return false;
}
if (dfa.m_reswds>=0)
{
((ResWds)m_tokens.reswds[dfa.m_reswds]).Check(this,ref tok);
}
if (m_debug)
{
Console.Write("{0} matched ",dfa.m_state);
if (m_pch<=m_buf.Length)
Console.WriteLine(m_buf.Substring(op,m_pch-op));
else
Console.WriteLine(m_buf.Substring(op));
}
return true;
}
// start lexing
/// <exclude/>
public void Start(StreamReader inFile)
{
m_state="YYINITIAL"; // 4.3e
m_LineManager.lines = 1; //
m_LineManager.list = null; //
inFile = new StreamReader(inFile.BaseStream,m_tokens.m_encoding);
m_buf = inFile.ReadToEnd();
if (m_tokens.toupper)
m_buf = m_buf.ToUpper();
for (m_pch=0; m_pch<m_buf.Length; m_pch++)
if (m_buf[m_pch]=='\n')
m_LineManager.newline(m_pch);
m_pch = 0;
}
/// <exclude/>
public void Start(CsReader inFile)
{
m_state="YYINITIAL"; // 4.3e
inFile = new CsReader(inFile,m_tokens.m_encoding);
m_LineManager = inFile.lm;
if (!inFile.Eof())
for (m_buf = inFile.ReadLine(); !inFile.Eof(); m_buf += inFile.ReadLine())
m_buf+="\n";
if (m_tokens.toupper)
m_buf = m_buf.ToUpper();
m_pch = 0;
}
/// <exclude/>
public void Start(string buf)
{
m_state="YYINITIAL"; // 4.3e
m_LineManager.lines = 1; //
m_LineManager.list = null; //
m_buf = buf+"\n";
for (m_pch=0; m_pch<m_buf.Length; m_pch++)
if (m_buf[m_pch]=='\n')
m_LineManager.newline(m_pch);
if (m_tokens.toupper)
m_buf = m_buf.ToUpper();
m_pch = 0;
}
/// <exclude/>
public TOKEN Next()
{
TOKEN rv = null;
while (PeekChar()!=0)
{
Matching(true);
if (!Match(ref rv,(Dfa)m_tokens.starts[m_state]))
{
if (yypos==0)
System.Console.Write("Check text encoding.. ");
int c = PeekChar();
m_tokens.erh.Error(new CSToolsStopException(2,this,"illegal character <"+(char)c+"> "+c));
return null;
}
Matching (false);
if (rv!=null)
{ // or special value for empty action?
rv.pos = m_pch-yytext.Length;
return rv;
}
}
return null;
}
bool TryActions(Dfa dfa,ref TOKEN tok)
{
int len = m_pch-m_startMatch;
if (len==0)
return false;
if (m_startMatch+len<=m_buf.Length)
yytext = m_buf.Substring(m_startMatch,len);
else // can happen with {EOF} rules
yytext = m_buf.Substring(m_startMatch);
// actions is a list of old-style actions for this DFA in order of priority
// there is a list because of the chance that any of them may REJECT
Dfa.Action a = dfa.m_actions;
bool reject = true;
while (reject && a!=null)
{
int action = a.a_act;
reject = false;
a = a.a_next;
if (a==null && dfa.m_tokClass!="")
{ // last one might not be an old-style action
if (m_debug)
Console.WriteLine("creating a "+dfa.m_tokClass);
tok=(TOKEN)Tfactory.create(dfa.m_tokClass,this);
}
else
{
tok = m_tokens.OldAction(this,ref yytext,action,ref reject);
if (m_debug && !reject)
Console.WriteLine("Old action "+action);
}
}
return !reject;
}
/// <exclude/>
public char PeekChar()
{
if (m_pch<m_buf.Length)
return m_buf[m_pch];
if (m_pch==m_buf.Length && m_tokens.usingEOF)
return (char)0xFFFF;
return (char)0;
}
/// <exclude/>
public void Advance() { ++m_pch; }
/// <exclude/>
public virtual int GetChar()
{
int r=PeekChar(); ++m_pch;
return r;
}
/// <exclude/>
public void UnGetChar() { if (m_pch>0) --m_pch; }
int Mark()
{
return m_pch-m_startMatch;
}
void Restore(int mark)
{
m_pch = m_startMatch + mark;
}
void Matching(bool b)
{
m_matching = b;
if (b)
m_startMatch = m_pch;
}
/// <exclude/>
public _Enumerator GetEnumerator()
{
return new _Enumerator(this);
}
/// <exclude/>
public void Reset()
{
m_pch = 0;
m_LineManager.backto(0);
}
/// <exclude/>
public class _Enumerator
{
Lexer lxr;
TOKEN t;
/// <exclude/>
public _Enumerator(Lexer x) { lxr = x; t = null; }
/// <exclude/>
public bool MoveNext()
{
t = lxr.Next();
return t!=null;
}
/// <exclude/>
public TOKEN Current { get { return t; } }
/// <exclude/>
public void Reset() { lxr.Reset(); }
}
}
/// <exclude/>
public class CSToolsException : Exception
{
/// <exclude/>
public int nExceptionNumber;
/// <exclude/>
public SourceLineInfo slInfo;
/// <exclude/>
public string sInput;
/// <exclude/>
public SYMBOL sym = null;
/// <exclude/>
public bool handled = false;
/// <exclude/>
public CSToolsException(int n,string s) : this(n,new SourceLineInfo(0),"",s) {}
/// <exclude/>
public CSToolsException(int n,Lexer yl,string s) : this(n,yl,yl.yytext,s) {}
/// <exclude/>
public CSToolsException(int n,Lexer yl,string yy,string s) : this(n,yl,yl.m_pch,yy,s) {}
/// <exclude/>
public CSToolsException(int n,TOKEN t,string s) : this(n,t.yylx,t.pos,t.yytext,s) { sym=t; }
/// <exclude/>
public CSToolsException(int n,SYMBOL t,string s) : this(n,t.yylx,t.pos,t.yyname,s) { sym=t; }
/// <exclude/>
public CSToolsException(int en,Lexer yl,int p, string y, string s) : this(en,yl.sourceLineInfo(p),y,s) {}
/// <exclude/>
public CSToolsException(int en,SourceLineInfo s, string y, string m) : base(s.ToString()+": "+m)
{
nExceptionNumber = en;
slInfo = s;
sInput = y;
}
/// <exclude/>
public virtual void Handle(ErrorHandler erh) // provides the default ErrorHandling implementation
{
if (erh.throwExceptions)
throw this;
if (handled)
return;
handled = true;
erh.Report(this); // the parse table may allow recovery from this error
}
}
/// <exclude/>
public class CSToolsFatalException: CSToolsException
{
/// <exclude/>
public CSToolsFatalException(int n,string s) : base(n,s) {}
/// <exclude/>
public CSToolsFatalException(int n,Lexer yl,string s) : base(n,yl,yl.yytext,s) {}
/// <exclude/>
public CSToolsFatalException(int n,Lexer yl,string yy,string s) : base(n,yl,yl.m_pch,yy,s) {}
/// <exclude/>
public CSToolsFatalException(int n,Lexer yl,int p, string y, string s) : base(n,yl,p,y,s) {}
/// <exclude/>
public CSToolsFatalException(int n,TOKEN t,string s) : base(n,t,s) {}
/// <exclude/>
public CSToolsFatalException(int en,SourceLineInfo s, string y, string m) : base(en,s,y,m) {}
/// <exclude/>
public override void Handle(ErrorHandler erh)
{
throw this; // we expect to bomb out to the environment with CLR traceback
}
}
/// <exclude/>
public class CSToolsStopException: CSToolsException
{
/// <exclude/>
public CSToolsStopException(int n,string s) : base(n,s) {}
/// <exclude/>
public CSToolsStopException(int n,Lexer yl,string s) : base(n,yl,yl.yytext,s) {}
/// <exclude/>
public CSToolsStopException(int n,Lexer yl,string yy,string s) : base(n,yl,yl.m_pch,yy,s) {}
/// <exclude/>
public CSToolsStopException(int n,Lexer yl,int p, string y, string s) : base(n,yl,p,y,s) {}
/// <exclude/>
public CSToolsStopException(int n,TOKEN t,string s) : base(n,t,s) {}
/// <exclude/>
public CSToolsStopException(int n,SYMBOL t,string s) : base(n,t,s) {}
/// <exclude/>
public CSToolsStopException(int en,SourceLineInfo s, string y, string m) : base(en,s,y,m) {}
/// <exclude/>
public override void Handle(ErrorHandler erh)
{ // 4.5b
throw this; // we expect Parser.Parse() to catch this but stop the parse
}
}
/// <exclude/>
public class ErrorHandler
{
/// <exclude/>
public int counter = 0;
/// <exclude/>
public bool throwExceptions = false;
/// <exclude/>
public ErrorHandler() {}
/// <exclude/>
public ErrorHandler(bool ee){ throwExceptions = ee;}
/// <exclude/>
public virtual void Error(CSToolsException e)
{
counter++;
e.Handle(this);
}
/// <exclude/>
public virtual void Report(CSToolsException e)
{
// I don't want to see error messages.
//Console.WriteLine(e.Message);
}
}
}
| |
using System;
using System.Collections;
using System.IO;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.Cmp;
using Org.BouncyCastle.Asn1.Cms;
using Org.BouncyCastle.Asn1.Tsp;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Utilities.Date;
namespace Org.BouncyCastle.Tsp
{
/**
* Generator for RFC 3161 Time Stamp Responses.
*/
public class TimeStampResponseGenerator
{
private PkiStatus status;
private Asn1EncodableVector statusStrings;
private int failInfo;
private TimeStampTokenGenerator tokenGenerator;
private IList acceptedAlgorithms;
private IList acceptedPolicies;
private IList acceptedExtensions;
public TimeStampResponseGenerator(
TimeStampTokenGenerator tokenGenerator,
IList acceptedAlgorithms)
: this(tokenGenerator, acceptedAlgorithms, null, null)
{
}
public TimeStampResponseGenerator(
TimeStampTokenGenerator tokenGenerator,
IList acceptedAlgorithms,
IList acceptedPolicy)
: this(tokenGenerator, acceptedAlgorithms, acceptedPolicy, null)
{
}
public TimeStampResponseGenerator(
TimeStampTokenGenerator tokenGenerator,
IList acceptedAlgorithms,
IList acceptedPolicies,
IList acceptedExtensions)
{
this.tokenGenerator = tokenGenerator;
this.acceptedAlgorithms = acceptedAlgorithms;
this.acceptedPolicies = acceptedPolicies;
this.acceptedExtensions = acceptedExtensions;
statusStrings = new Asn1EncodableVector();
}
private void AddStatusString(string statusString)
{
statusStrings.Add(new DerUtf8String(statusString));
}
private void SetFailInfoField(int field)
{
failInfo |= field;
}
private PkiStatusInfo GetPkiStatusInfo()
{
Asn1EncodableVector v = new Asn1EncodableVector(
new DerInteger((int)status));
if (statusStrings.Count > 0)
{
v.Add(new PkiFreeText(new DerSequence(statusStrings)));
}
if (failInfo != 0)
{
v.Add(new FailInfo(failInfo));
}
return new PkiStatusInfo(new DerSequence(v));
}
public TimeStampResponse Generate(
TimeStampRequest request,
IBigInteger serialNumber,
DateTime genTime)
{
return Generate(request, serialNumber, new DateTimeObject(genTime));
}
/**
* Return an appropriate TimeStampResponse.
* <p>
* If genTime is null a timeNotAvailable error response will be returned.
*
* @param request the request this response is for.
* @param serialNumber serial number for the response token.
* @param genTime generation time for the response token.
* @param provider provider to use for signature calculation.
* @return
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
* @throws TSPException
* </p>
*/
public TimeStampResponse Generate(
TimeStampRequest request,
IBigInteger serialNumber,
DateTimeObject genTime)
{
TimeStampResp resp;
try
{
if (genTime == null)
throw new TspValidationException("The time source is not available.",
PkiFailureInfo.TimeNotAvailable);
request.Validate(acceptedAlgorithms, acceptedPolicies, acceptedExtensions);
this.status = PkiStatus.Granted;
this.AddStatusString("Operation Okay");
PkiStatusInfo pkiStatusInfo = GetPkiStatusInfo();
ContentInfo tstTokenContentInfo;
try
{
TimeStampToken token = tokenGenerator.Generate(request, serialNumber, genTime.Value);
byte[] encoded = token.ToCmsSignedData().GetEncoded();
tstTokenContentInfo = ContentInfo.GetInstance(Asn1Object.FromByteArray(encoded));
}
catch (IOException e)
{
throw new TspException("Timestamp token received cannot be converted to ContentInfo", e);
}
resp = new TimeStampResp(pkiStatusInfo, tstTokenContentInfo);
}
catch (TspValidationException e)
{
status = PkiStatus.Rejection;
this.SetFailInfoField(e.FailureCode);
this.AddStatusString(e.Message);
PkiStatusInfo pkiStatusInfo = GetPkiStatusInfo();
resp = new TimeStampResp(pkiStatusInfo, null);
}
try
{
return new TimeStampResponse(resp);
}
catch (IOException e)
{
throw new TspException("created badly formatted response!", e);
}
}
class FailInfo
: DerBitString
{
internal FailInfo(
int failInfoValue)
: base(GetBytes(failInfoValue), GetPadBits(failInfoValue))
{
}
}
/**
* Generate a TimeStampResponse with chosen status and FailInfoField.
*
* @param status the PKIStatus to set.
* @param failInfoField the FailInfoField to set.
* @param statusString an optional string describing the failure.
* @return a TimeStampResponse with a failInfoField and optional statusString
* @throws TSPException in case the response could not be created
*/
public TimeStampResponse GenerateFailResponse(PkiStatus status, int failInfoField, string statusString)
{
this.status = status;
this.SetFailInfoField(failInfoField);
if (statusString != null)
{
this.AddStatusString(statusString);
}
PkiStatusInfo pkiStatusInfo = GetPkiStatusInfo();
TimeStampResp resp = new TimeStampResp(pkiStatusInfo, null);
try
{
return new TimeStampResponse(resp);
}
catch (IOException e)
{
throw new TspException("created badly formatted response!", e);
}
}
}
}
| |
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Utils;
using osu.Game.Beatmaps;
using osu.Game.Configuration;
using osu.Game.Rulesets;
using osu.Game.Screens.Select;
using osu.Game.Screens.Select.Carousel;
using osu.Game.Screens.Select.Filter;
using osuTK.Input;
namespace osu.Game.Tests.Visual.SongSelect
{
[TestFixture]
public class TestSceneBeatmapCarousel : OsuManualInputManagerTestScene
{
private TestBeatmapCarousel carousel;
private RulesetStore rulesets;
private readonly Stack<BeatmapSetInfo> selectedSets = new Stack<BeatmapSetInfo>();
private readonly HashSet<int> eagerSelectedIDs = new HashSet<int>();
private BeatmapInfo currentSelection => carousel.SelectedBeatmapInfo;
private const int set_count = 5;
[BackgroundDependencyLoader]
private void load(RulesetStore rulesets)
{
this.rulesets = rulesets;
}
[Test]
public void TestManyPanels()
{
loadBeatmaps(count: 5000, randomDifficulties: true);
}
[Test]
public void TestKeyRepeat()
{
loadBeatmaps();
advanceSelection(false);
AddStep("press down arrow", () => InputManager.PressKey(Key.Down));
BeatmapInfo selection = null;
checkSelectionIterating(true);
AddStep("press up arrow", () => InputManager.PressKey(Key.Up));
checkSelectionIterating(true);
AddStep("release down arrow", () => InputManager.ReleaseKey(Key.Down));
checkSelectionIterating(true);
AddStep("release up arrow", () => InputManager.ReleaseKey(Key.Up));
checkSelectionIterating(false);
void checkSelectionIterating(bool isIterating)
{
for (int i = 0; i < 3; i++)
{
AddStep("store selection", () => selection = carousel.SelectedBeatmapInfo);
if (isIterating)
AddUntilStep("selection changed", () => carousel.SelectedBeatmapInfo != selection);
else
AddUntilStep("selection not changed", () => carousel.SelectedBeatmapInfo == selection);
}
}
}
[Test]
public void TestRecommendedSelection()
{
loadBeatmaps(carouselAdjust: carousel => carousel.GetRecommendedBeatmap = beatmaps => beatmaps.LastOrDefault());
AddStep("select last", () => carousel.SelectBeatmap(carousel.BeatmapSets.Last().Beatmaps.Last()));
// check recommended was selected
advanceSelection(direction: 1, diff: false);
waitForSelection(1, 3);
// change away from recommended
advanceSelection(direction: -1, diff: true);
waitForSelection(1, 2);
// next set, check recommended
advanceSelection(direction: 1, diff: false);
waitForSelection(2, 3);
// next set, check recommended
advanceSelection(direction: 1, diff: false);
waitForSelection(3, 3);
// go back to first set and ensure user selection was retained
advanceSelection(direction: -1, diff: false);
advanceSelection(direction: -1, diff: false);
waitForSelection(1, 2);
}
/// <summary>
/// Test keyboard traversal
/// </summary>
[Test]
public void TestTraversal()
{
loadBeatmaps();
AddStep("select first", () => carousel.SelectBeatmap(carousel.BeatmapSets.First().Beatmaps.First()));
waitForSelection(1, 1);
advanceSelection(direction: 1, diff: true);
waitForSelection(1, 2);
advanceSelection(direction: -1, diff: false);
waitForSelection(set_count, 1);
advanceSelection(direction: -1, diff: true);
waitForSelection(set_count - 1, 3);
advanceSelection(diff: false);
advanceSelection(diff: false);
waitForSelection(1, 2);
advanceSelection(direction: -1, diff: true);
advanceSelection(direction: -1, diff: true);
waitForSelection(set_count, 3);
}
[TestCase(true)]
[TestCase(false)]
public void TestTraversalBeyondVisible(bool forwards)
{
var sets = new List<BeatmapSetInfo>();
const int total_set_count = 200;
for (int i = 0; i < total_set_count; i++)
sets.Add(createTestBeatmapSet(i + 1));
loadBeatmaps(sets);
for (int i = 1; i < total_set_count; i += i)
selectNextAndAssert(i);
void selectNextAndAssert(int amount)
{
setSelected(forwards ? 1 : total_set_count, 1);
AddStep($"{(forwards ? "Next" : "Previous")} beatmap {amount} times", () =>
{
for (int i = 0; i < amount; i++)
{
carousel.SelectNext(forwards ? 1 : -1);
}
});
waitForSelection(forwards ? amount + 1 : total_set_count - amount);
}
}
[Test]
public void TestTraversalBeyondVisibleDifficulties()
{
var sets = new List<BeatmapSetInfo>();
const int total_set_count = 20;
for (int i = 0; i < total_set_count; i++)
sets.Add(createTestBeatmapSet(i + 1));
loadBeatmaps(sets);
// Selects next set once, difficulty index doesn't change
selectNextAndAssert(3, true, 2, 1);
// Selects next set 16 times (50 \ 3 == 16), difficulty index changes twice (50 % 3 == 2)
selectNextAndAssert(50, true, 17, 3);
// Travels around the carousel thrice (200 \ 60 == 3)
// continues to select 20 times (200 \ 60 == 20)
// selects next set 6 times (20 \ 3 == 6)
// difficulty index changes twice (20 % 3 == 2)
selectNextAndAssert(200, true, 7, 3);
// All same but in reverse
selectNextAndAssert(3, false, 19, 3);
selectNextAndAssert(50, false, 4, 1);
selectNextAndAssert(200, false, 14, 1);
void selectNextAndAssert(int amount, bool forwards, int expectedSet, int expectedDiff)
{
// Select very first or very last difficulty
setSelected(forwards ? 1 : 20, forwards ? 1 : 3);
AddStep($"{(forwards ? "Next" : "Previous")} difficulty {amount} times", () =>
{
for (int i = 0; i < amount; i++)
carousel.SelectNext(forwards ? 1 : -1, false);
});
waitForSelection(expectedSet, expectedDiff);
}
}
/// <summary>
/// Test filtering
/// </summary>
[Test]
public void TestFiltering()
{
loadBeatmaps();
// basic filtering
setSelected(1, 1);
AddStep("Filter", () => carousel.Filter(new FilterCriteria { SearchText = "set #3!" }, false));
checkVisibleItemCount(diff: false, count: 1);
checkVisibleItemCount(diff: true, count: 3);
waitForSelection(3, 1);
advanceSelection(diff: true, count: 4);
waitForSelection(3, 2);
AddStep("Un-filter (debounce)", () => carousel.Filter(new FilterCriteria()));
AddUntilStep("Wait for debounce", () => !carousel.PendingFilterTask);
checkVisibleItemCount(diff: false, count: set_count);
checkVisibleItemCount(diff: true, count: 3);
// test filtering some difficulties (and keeping current beatmap set selected).
setSelected(1, 2);
AddStep("Filter some difficulties", () => carousel.Filter(new FilterCriteria { SearchText = "Normal" }, false));
waitForSelection(1, 1);
AddStep("Un-filter", () => carousel.Filter(new FilterCriteria(), false));
waitForSelection(1, 1);
AddStep("Filter all", () => carousel.Filter(new FilterCriteria { SearchText = "Dingo" }, false));
checkVisibleItemCount(false, 0);
checkVisibleItemCount(true, 0);
AddAssert("Selection is null", () => currentSelection == null);
advanceSelection(true);
AddAssert("Selection is null", () => currentSelection == null);
advanceSelection(false);
AddAssert("Selection is null", () => currentSelection == null);
AddStep("Un-filter", () => carousel.Filter(new FilterCriteria(), false));
AddAssert("Selection is non-null", () => currentSelection != null);
setSelected(1, 3);
}
[Test]
public void TestFilterRange()
{
loadBeatmaps();
// buffer the selection
setSelected(3, 2);
setSelected(1, 3);
AddStep("Apply a range filter", () => carousel.Filter(new FilterCriteria
{
SearchText = "#3",
StarDifficulty = new FilterCriteria.OptionalRange<double>
{
Min = 2,
Max = 5.5,
IsLowerInclusive = true
}
}, false));
// should reselect the buffered selection.
waitForSelection(3, 2);
}
/// <summary>
/// Test random non-repeating algorithm
/// </summary>
[Test]
public void TestRandom()
{
loadBeatmaps();
setSelected(1, 1);
nextRandom();
ensureRandomDidntRepeat();
nextRandom();
ensureRandomDidntRepeat();
nextRandom();
ensureRandomDidntRepeat();
prevRandom();
ensureRandomFetchSuccess();
prevRandom();
ensureRandomFetchSuccess();
nextRandom();
ensureRandomDidntRepeat();
nextRandom();
ensureRandomDidntRepeat();
nextRandom();
AddAssert("ensure repeat", () => selectedSets.Contains(carousel.SelectedBeatmapSet));
AddStep("Add set with 100 difficulties", () => carousel.UpdateBeatmapSet(createTestBeatmapSetWithManyDifficulties(set_count + 1)));
AddStep("Filter Extra", () => carousel.Filter(new FilterCriteria { SearchText = "Extra 10" }, false));
checkInvisibleDifficultiesUnselectable();
checkInvisibleDifficultiesUnselectable();
checkInvisibleDifficultiesUnselectable();
checkInvisibleDifficultiesUnselectable();
checkInvisibleDifficultiesUnselectable();
AddStep("Un-filter", () => carousel.Filter(new FilterCriteria(), false));
}
/// <summary>
/// Test adding and removing beatmap sets
/// </summary>
[Test]
public void TestAddRemove()
{
loadBeatmaps();
AddStep("Add new set", () => carousel.UpdateBeatmapSet(createTestBeatmapSet(set_count + 1)));
AddStep("Add new set", () => carousel.UpdateBeatmapSet(createTestBeatmapSet(set_count + 2)));
checkVisibleItemCount(false, set_count + 2);
AddStep("Remove set", () => carousel.RemoveBeatmapSet(createTestBeatmapSet(set_count + 2)));
checkVisibleItemCount(false, set_count + 1);
setSelected(set_count + 1, 1);
AddStep("Remove set", () => carousel.RemoveBeatmapSet(createTestBeatmapSet(set_count + 1)));
checkVisibleItemCount(false, set_count);
waitForSelection(set_count);
}
[Test]
public void TestSelectionEnteringFromEmptyRuleset()
{
var sets = new List<BeatmapSetInfo>();
AddStep("Create beatmaps for taiko only", () =>
{
sets.Clear();
var rulesetBeatmapSet = createTestBeatmapSet(1);
var taikoRuleset = rulesets.AvailableRulesets.ElementAt(1);
rulesetBeatmapSet.Beatmaps.ForEach(b =>
{
b.Ruleset = taikoRuleset;
b.RulesetID = 1;
});
sets.Add(rulesetBeatmapSet);
});
loadBeatmaps(sets, () => new FilterCriteria { Ruleset = rulesets.AvailableRulesets.ElementAt(0) });
AddStep("Set non-empty mode filter", () =>
carousel.Filter(new FilterCriteria { Ruleset = rulesets.AvailableRulesets.ElementAt(1) }, false));
AddAssert("Something is selected", () => carousel.SelectedBeatmapInfo != null);
}
/// <summary>
/// Test sorting
/// </summary>
[Test]
public void TestSorting()
{
loadBeatmaps();
AddStep("Sort by author", () => carousel.Filter(new FilterCriteria { Sort = SortMode.Author }, false));
AddAssert("Check zzzzz is at bottom", () => carousel.BeatmapSets.Last().Metadata.AuthorString == "zzzzz");
AddStep("Sort by artist", () => carousel.Filter(new FilterCriteria { Sort = SortMode.Artist }, false));
AddAssert($"Check #{set_count} is at bottom", () => carousel.BeatmapSets.Last().Metadata.Title.EndsWith($"#{set_count}!", StringComparison.Ordinal));
}
[Test]
public void TestSortingStability()
{
var sets = new List<BeatmapSetInfo>();
for (int i = 0; i < 20; i++)
{
var set = createTestBeatmapSet(i);
set.Metadata.Artist = "same artist";
set.Metadata.Title = "same title";
sets.Add(set);
}
loadBeatmaps(sets);
AddStep("Sort by artist", () => carousel.Filter(new FilterCriteria { Sort = SortMode.Artist }, false));
AddAssert("Items remain in original order", () => carousel.BeatmapSets.Select((set, index) => set.ID == index).All(b => b));
AddStep("Sort by title", () => carousel.Filter(new FilterCriteria { Sort = SortMode.Title }, false));
AddAssert("Items remain in original order", () => carousel.BeatmapSets.Select((set, index) => set.ID == index).All(b => b));
}
[Test]
public void TestSortingWithFiltered()
{
List<BeatmapSetInfo> sets = new List<BeatmapSetInfo>();
for (int i = 0; i < 3; i++)
{
var set = createTestBeatmapSet(i);
set.Beatmaps[0].StarDifficulty = 3 - i;
set.Beatmaps[2].StarDifficulty = 6 + i;
sets.Add(set);
}
loadBeatmaps(sets);
AddStep("Filter to normal", () => carousel.Filter(new FilterCriteria { Sort = SortMode.Difficulty, SearchText = "Normal" }, false));
AddAssert("Check first set at end", () => carousel.BeatmapSets.First() == sets.Last());
AddAssert("Check last set at start", () => carousel.BeatmapSets.Last() == sets.First());
AddStep("Filter to insane", () => carousel.Filter(new FilterCriteria { Sort = SortMode.Difficulty, SearchText = "Insane" }, false));
AddAssert("Check first set at start", () => carousel.BeatmapSets.First() == sets.First());
AddAssert("Check last set at end", () => carousel.BeatmapSets.Last() == sets.Last());
}
[Test]
public void TestRemoveAll()
{
loadBeatmaps();
setSelected(2, 1);
AddAssert("Selection is non-null", () => currentSelection != null);
AddStep("Remove selected", () => carousel.RemoveBeatmapSet(carousel.SelectedBeatmapSet));
waitForSelection(2);
AddStep("Remove first", () => carousel.RemoveBeatmapSet(carousel.BeatmapSets.First()));
AddStep("Remove first", () => carousel.RemoveBeatmapSet(carousel.BeatmapSets.First()));
waitForSelection(1);
AddUntilStep("Remove all", () =>
{
if (!carousel.BeatmapSets.Any()) return true;
carousel.RemoveBeatmapSet(carousel.BeatmapSets.Last());
return false;
});
checkNoSelection();
}
[Test]
public void TestEmptyTraversal()
{
loadBeatmaps(new List<BeatmapSetInfo>());
advanceSelection(direction: 1, diff: false);
checkNoSelection();
advanceSelection(direction: 1, diff: true);
checkNoSelection();
advanceSelection(direction: -1, diff: false);
checkNoSelection();
advanceSelection(direction: -1, diff: true);
checkNoSelection();
}
[Test]
public void TestHiding()
{
BeatmapSetInfo hidingSet = null;
List<BeatmapSetInfo> hiddenList = new List<BeatmapSetInfo>();
AddStep("create hidden set", () =>
{
hidingSet = createTestBeatmapSet(1);
hidingSet.Beatmaps[1].Hidden = true;
hiddenList.Clear();
hiddenList.Add(hidingSet);
});
loadBeatmaps(hiddenList);
setSelected(1, 1);
checkVisibleItemCount(true, 2);
advanceSelection(true);
waitForSelection(1, 3);
setHidden(3);
waitForSelection(1, 1);
setHidden(2, false);
advanceSelection(true);
waitForSelection(1, 2);
setHidden(1);
waitForSelection(1, 2);
setHidden(2);
checkNoSelection();
void setHidden(int diff, bool hidden = true)
{
AddStep((hidden ? "" : "un") + $"hide diff {diff}", () =>
{
hidingSet.Beatmaps[diff - 1].Hidden = hidden;
carousel.UpdateBeatmapSet(hidingSet);
});
}
}
[Test]
public void TestSelectingFilteredRuleset()
{
BeatmapSetInfo testMixed = null;
createCarousel();
AddStep("add mixed ruleset beatmapset", () =>
{
testMixed = createTestBeatmapSet(set_count + 1);
for (int i = 0; i <= 2; i++)
{
testMixed.Beatmaps[i].Ruleset = rulesets.AvailableRulesets.ElementAt(i);
testMixed.Beatmaps[i].RulesetID = i;
}
carousel.UpdateBeatmapSet(testMixed);
});
AddStep("filter to ruleset 0", () =>
carousel.Filter(new FilterCriteria { Ruleset = rulesets.AvailableRulesets.ElementAt(0) }, false));
AddStep("select filtered map skipping filtered", () => carousel.SelectBeatmap(testMixed.Beatmaps[1], false));
AddAssert("unfiltered beatmap not selected", () => carousel.SelectedBeatmapInfo.RulesetID == 0);
AddStep("remove mixed set", () =>
{
carousel.RemoveBeatmapSet(testMixed);
testMixed = null;
});
BeatmapSetInfo testSingle = null;
AddStep("add single ruleset beatmapset", () =>
{
testSingle = createTestBeatmapSet(set_count + 2);
testSingle.Beatmaps.ForEach(b =>
{
b.Ruleset = rulesets.AvailableRulesets.ElementAt(1);
b.RulesetID = b.Ruleset.ID ?? 1;
});
carousel.UpdateBeatmapSet(testSingle);
});
AddStep("select filtered map skipping filtered", () => carousel.SelectBeatmap(testSingle.Beatmaps[0], false));
checkNoSelection();
AddStep("remove single ruleset set", () => carousel.RemoveBeatmapSet(testSingle));
}
[Test]
public void TestCarouselRemembersSelection()
{
List<BeatmapSetInfo> manySets = new List<BeatmapSetInfo>();
for (int i = 1; i <= 50; i++)
manySets.Add(createTestBeatmapSet(i));
loadBeatmaps(manySets);
advanceSelection(direction: 1, diff: false);
for (int i = 0; i < 5; i++)
{
AddStep("Toggle non-matching filter", () =>
{
carousel.Filter(new FilterCriteria { SearchText = Guid.NewGuid().ToString() }, false);
});
AddStep("Restore no filter", () =>
{
carousel.Filter(new FilterCriteria(), false);
eagerSelectedIDs.Add(carousel.SelectedBeatmapSet.ID);
});
}
// always returns to same selection as long as it's available.
AddAssert("Selection was remembered", () => eagerSelectedIDs.Count == 1);
}
[Test]
public void TestRandomFallbackOnNonMatchingPrevious()
{
List<BeatmapSetInfo> manySets = new List<BeatmapSetInfo>();
AddStep("populate maps", () =>
{
for (int i = 0; i < 10; i++)
{
var set = createTestBeatmapSet(i);
foreach (var b in set.Beatmaps)
{
// all taiko except for first
int ruleset = i > 0 ? 1 : 0;
b.Ruleset = rulesets.GetRuleset(ruleset);
b.RulesetID = ruleset;
}
manySets.Add(set);
}
});
loadBeatmaps(manySets);
for (int i = 0; i < 10; i++)
{
AddStep("Reset filter", () => carousel.Filter(new FilterCriteria(), false));
AddStep("select first beatmap", () => carousel.SelectBeatmap(manySets.First().Beatmaps.First()));
AddStep("Toggle non-matching filter", () =>
{
carousel.Filter(new FilterCriteria { SearchText = Guid.NewGuid().ToString() }, false);
});
AddAssert("selection lost", () => carousel.SelectedBeatmapInfo == null);
AddStep("Restore different ruleset filter", () =>
{
carousel.Filter(new FilterCriteria { Ruleset = rulesets.GetRuleset(1) }, false);
eagerSelectedIDs.Add(carousel.SelectedBeatmapSet.ID);
});
AddAssert("selection changed", () => carousel.SelectedBeatmapInfo != manySets.First().Beatmaps.First());
}
AddAssert("Selection was random", () => eagerSelectedIDs.Count > 2);
}
[Test]
public void TestFilteringByUserStarDifficulty()
{
BeatmapSetInfo set = null;
loadBeatmaps(new List<BeatmapSetInfo>());
AddStep("add mixed difficulty set", () =>
{
set = createTestBeatmapSet(1);
set.Beatmaps.Clear();
for (int i = 1; i <= 15; i++)
{
set.Beatmaps.Add(new BeatmapInfo
{
Version = $"Stars: {i}",
StarDifficulty = i,
});
}
carousel.UpdateBeatmapSet(set);
});
AddStep("select added set", () => carousel.SelectBeatmap(set.Beatmaps[0], false));
AddStep("filter [5..]", () => carousel.Filter(new FilterCriteria { UserStarDifficulty = { Min = 5 } }));
AddUntilStep("Wait for debounce", () => !carousel.PendingFilterTask);
checkVisibleItemCount(true, 11);
AddStep("filter to [0..7]", () => carousel.Filter(new FilterCriteria { UserStarDifficulty = { Max = 7 } }));
AddUntilStep("Wait for debounce", () => !carousel.PendingFilterTask);
checkVisibleItemCount(true, 7);
AddStep("filter to [5..7]", () => carousel.Filter(new FilterCriteria { UserStarDifficulty = { Min = 5, Max = 7 } }));
AddUntilStep("Wait for debounce", () => !carousel.PendingFilterTask);
checkVisibleItemCount(true, 3);
AddStep("filter [2..2]", () => carousel.Filter(new FilterCriteria { UserStarDifficulty = { Min = 2, Max = 2 } }));
AddUntilStep("Wait for debounce", () => !carousel.PendingFilterTask);
checkVisibleItemCount(true, 1);
AddStep("filter to [0..]", () => carousel.Filter(new FilterCriteria { UserStarDifficulty = { Min = 0 } }));
AddUntilStep("Wait for debounce", () => !carousel.PendingFilterTask);
checkVisibleItemCount(true, 15);
}
private void loadBeatmaps(List<BeatmapSetInfo> beatmapSets = null, Func<FilterCriteria> initialCriteria = null, Action<BeatmapCarousel> carouselAdjust = null, int? count = null, bool randomDifficulties = false)
{
bool changed = false;
createCarousel(c =>
{
carouselAdjust?.Invoke(c);
if (beatmapSets == null)
{
beatmapSets = new List<BeatmapSetInfo>();
for (int i = 1; i <= (count ?? set_count); i++)
beatmapSets.Add(createTestBeatmapSet(i, randomDifficulties));
}
carousel.Filter(initialCriteria?.Invoke() ?? new FilterCriteria());
carousel.BeatmapSetsChanged = () => changed = true;
carousel.BeatmapSets = beatmapSets;
});
AddUntilStep("Wait for load", () => changed);
}
private void createCarousel(Action<BeatmapCarousel> carouselAdjust = null, Container target = null)
{
AddStep("Create carousel", () =>
{
selectedSets.Clear();
eagerSelectedIDs.Clear();
carousel = new TestBeatmapCarousel
{
RelativeSizeAxes = Axes.Both,
};
carouselAdjust?.Invoke(carousel);
(target ?? this).Child = carousel;
});
}
private void ensureRandomFetchSuccess() =>
AddAssert("ensure prev random fetch worked", () => selectedSets.Peek() == carousel.SelectedBeatmapSet);
private void waitForSelection(int set, int? diff = null) =>
AddUntilStep($"selected is set{set}{(diff.HasValue ? $" diff{diff.Value}" : "")}", () =>
{
if (diff != null)
return carousel.SelectedBeatmapInfo == carousel.BeatmapSets.Skip(set - 1).First().Beatmaps.Skip(diff.Value - 1).First();
return carousel.BeatmapSets.Skip(set - 1).First().Beatmaps.Contains(carousel.SelectedBeatmapInfo);
});
private void setSelected(int set, int diff) =>
AddStep($"select set{set} diff{diff}", () =>
carousel.SelectBeatmap(carousel.BeatmapSets.Skip(set - 1).First().Beatmaps.Skip(diff - 1).First()));
private void advanceSelection(bool diff, int direction = 1, int count = 1)
{
if (count == 1)
{
AddStep($"select {(direction > 0 ? "next" : "prev")} {(diff ? "diff" : "set")}", () =>
carousel.SelectNext(direction, !diff));
}
else
{
AddRepeatStep($"select {(direction > 0 ? "next" : "prev")} {(diff ? "diff" : "set")}", () =>
carousel.SelectNext(direction, !diff), count);
}
}
private void checkVisibleItemCount(bool diff, int count)
{
// until step required as we are querying against alive items, which are loaded asynchronously inside DrawableCarouselBeatmapSet.
AddUntilStep($"{count} {(diff ? "diffs" : "sets")} visible", () =>
carousel.Items.Count(s => (diff ? s.Item is CarouselBeatmap : s.Item is CarouselBeatmapSet) && s.Item.Visible) == count);
}
private void checkNoSelection() => AddAssert("Selection is null", () => currentSelection == null);
private void nextRandom() =>
AddStep("select random next", () =>
{
carousel.RandomAlgorithm.Value = RandomSelectAlgorithm.RandomPermutation;
if (!selectedSets.Any() && carousel.SelectedBeatmapInfo != null)
selectedSets.Push(carousel.SelectedBeatmapSet);
carousel.SelectNextRandom();
selectedSets.Push(carousel.SelectedBeatmapSet);
});
private void ensureRandomDidntRepeat() =>
AddAssert("ensure no repeats", () => selectedSets.Distinct().Count() == selectedSets.Count);
private void prevRandom() => AddStep("select random last", () =>
{
carousel.SelectPreviousRandom();
selectedSets.Pop();
});
private bool selectedBeatmapVisible()
{
var currentlySelected = carousel.Items.FirstOrDefault(s => s.Item is CarouselBeatmap && s.Item.State.Value == CarouselItemState.Selected);
if (currentlySelected == null)
return true;
return currentlySelected.Item.Visible;
}
private void checkInvisibleDifficultiesUnselectable()
{
nextRandom();
AddAssert("Selection is visible", selectedBeatmapVisible);
}
private BeatmapSetInfo createTestBeatmapSet(int id, bool randomDifficultyCount = false)
{
return new BeatmapSetInfo
{
ID = id,
OnlineBeatmapSetID = id,
Hash = new MemoryStream(Encoding.UTF8.GetBytes(Guid.NewGuid().ToString())).ComputeMD5Hash(),
Metadata = new BeatmapMetadata
{
// Create random metadata, then we can check if sorting works based on these
Artist = $"peppy{id.ToString().PadLeft(6, '0')}",
Title = $"test set #{id}!",
AuthorString = string.Concat(Enumerable.Repeat((char)('z' - Math.Min(25, id - 1)), 5))
},
Beatmaps = getBeatmaps(randomDifficultyCount ? RNG.Next(1, 20) : 3).ToList()
};
}
private IEnumerable<BeatmapInfo> getBeatmaps(int count)
{
int id = 0;
for (int i = 0; i < count; i++)
{
float diff = (float)i / count * 10;
string version = "Normal";
if (diff > 6.6)
version = "Insane";
else if (diff > 3.3)
version = "Hard";
yield return new BeatmapInfo
{
OnlineBeatmapID = id++ * 10,
Version = version,
StarDifficulty = diff,
BaseDifficulty = new BeatmapDifficulty
{
OverallDifficulty = diff,
}
};
}
}
private BeatmapSetInfo createTestBeatmapSetWithManyDifficulties(int id)
{
var toReturn = new BeatmapSetInfo
{
ID = id,
OnlineBeatmapSetID = id,
Hash = new MemoryStream(Encoding.UTF8.GetBytes(Guid.NewGuid().ToString())).ComputeMD5Hash(),
Metadata = new BeatmapMetadata
{
// Create random metadata, then we can check if sorting works based on these
Artist = $"peppy{id.ToString().PadLeft(6, '0')}",
Title = $"test set #{id}!",
AuthorString = string.Concat(Enumerable.Repeat((char)('z' - Math.Min(25, id - 1)), 5))
},
Beatmaps = new List<BeatmapInfo>(),
};
for (int b = 1; b < 101; b++)
{
toReturn.Beatmaps.Add(new BeatmapInfo
{
OnlineBeatmapID = b * 10,
Path = $"extra{b}.osu",
Version = $"Extra {b}",
Ruleset = rulesets.GetRuleset((b - 1) % 4),
StarDifficulty = 2,
BaseDifficulty = new BeatmapDifficulty
{
OverallDifficulty = 3.5f,
}
});
}
return toReturn;
}
private class TestBeatmapCarousel : BeatmapCarousel
{
public bool PendingFilterTask => PendingFilter != null;
public IEnumerable<DrawableCarouselItem> Items
{
get
{
foreach (var item in Scroll.Children)
{
yield return item;
if (item is DrawableCarouselBeatmapSet set)
{
foreach (var difficulty in set.DrawableBeatmaps)
yield return difficulty;
}
}
}
}
protected override IEnumerable<BeatmapSetInfo> GetLoadableBeatmaps() => Enumerable.Empty<BeatmapSetInfo>();
}
}
}
| |
#region License
// SLNTools
// Copyright (c) 2009
// by Christian Warren
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using System.Xml;
namespace CWDev.SLNTools.Core
{
using Merge;
public class Project
{
private readonly SolutionFile r_container;
private readonly string r_projectGuid;
private string m_projectTypeGuid;
private string m_projectName;
private string m_relativePath;
private string m_parentFolderGuid;
private readonly SectionHashList r_projectSections;
private readonly PropertyLineHashList r_versionControlLines;
private readonly PropertyLineHashList r_projectConfigurationPlatformsLines;
public Project(SolutionFile container, Project original)
: this(
container,
original.ProjectGuid,
original.ProjectTypeGuid,
original.ProjectName,
original.RelativePath,
original.ParentFolderGuid,
original.ProjectSections,
original.VersionControlLines,
original.ProjectConfigurationPlatformsLines)
{
}
public Project(
SolutionFile container,
string projectGuid,
string projectTypeGuid,
string projectName,
string relativePath,
string parentFolderGuid,
IEnumerable<Section> projectSections,
IEnumerable<PropertyLine> versionControlLines,
IEnumerable<PropertyLine> projectConfigurationPlatformsLines)
{
r_container = container;
r_projectGuid = projectGuid;
m_projectTypeGuid = projectTypeGuid;
m_projectName = projectName;
m_relativePath = relativePath;
m_parentFolderGuid = parentFolderGuid;
r_projectSections = new SectionHashList(projectSections);
r_versionControlLines = new PropertyLineHashList(versionControlLines);
r_projectConfigurationPlatformsLines = new PropertyLineHashList(projectConfigurationPlatformsLines);
}
public string ProjectGuid
{
get { return r_projectGuid; }
}
public string ProjectTypeGuid
{
get { return m_projectTypeGuid; }
set { m_projectTypeGuid = value; }
}
public string ProjectName
{
get { return m_projectName; }
set { m_projectName = value; }
}
public string RelativePath
{
get { return m_relativePath; }
set { m_relativePath = value; }
}
public string FullPath
{
get { return Environment.ExpandEnvironmentVariables(Path.Combine(Path.GetDirectoryName(r_container.SolutionFullPath), m_relativePath)); }
}
public string ParentFolderGuid
{
get { return m_parentFolderGuid; }
set { m_parentFolderGuid = value; }
}
public SectionHashList ProjectSections
{
get { return r_projectSections; }
}
public PropertyLineHashList VersionControlLines
{
get { return r_versionControlLines; }
}
public PropertyLineHashList ProjectConfigurationPlatformsLines
{
get { return r_projectConfigurationPlatformsLines; }
}
public Project ParentFolder
{
get
{
if (m_parentFolderGuid == null)
return null;
return FindProjectInContainer(
m_parentFolderGuid,
"Cannot find the parent folder of project '{0}'. \nProject guid: {1}\nParent folder guid: {2}",
m_projectName,
r_projectGuid,
m_parentFolderGuid);
}
}
public string ProjectFullName
{
get
{
if (this.ParentFolder != null)
{
return this.ParentFolder.ProjectFullName + @"\" + this.ProjectName;
}
else
{
return this.ProjectName;
}
}
}
public IEnumerable<Project> Childs
{
get
{
if (m_projectTypeGuid == KnownProjectTypeGuid.SolutionFolder)
{
foreach (Project project in r_container.Projects)
{
if (project.m_parentFolderGuid == r_projectGuid)
yield return project;
}
}
}
}
public IEnumerable<Project> AllDescendants
{
get
{
foreach (var child in this.Childs)
{
yield return child;
foreach (var subchild in child.AllDescendants)
{
yield return subchild;
}
}
}
}
public IEnumerable<Project> Dependencies
{
get
{
if (this.ParentFolder != null)
{
yield return this.ParentFolder;
}
if (r_projectSections.Contains("ProjectDependencies"))
{
foreach (var propertyLine in r_projectSections["ProjectDependencies"].PropertyLines)
{
var dependencyGuid = propertyLine.Name;
yield return FindProjectInContainer(
dependencyGuid,
"Cannot find one of the dependency of project '{0}'.\nProject guid: {1}\nDependency guid: {2}\nReference found in: ProjectDependencies section of the solution file",
m_projectName,
r_projectGuid,
dependencyGuid);
}
}
switch (m_projectTypeGuid)
{
case KnownProjectTypeGuid.VisualBasic:
case KnownProjectTypeGuid.CSharp:
case KnownProjectTypeGuid.JSharp:
case KnownProjectTypeGuid.FSharp:
default:
if (! File.Exists(this.FullPath))
{
throw new SolutionFileException(string.Format(
"Cannot detect dependencies of projet '{0}' because the project file cannot be found.\nProject full path: '{1}'",
m_projectName,
this.FullPath));
}
var docManaged = new XmlDocument();
docManaged.Load(this.FullPath);
var xmlManager = new XmlNamespaceManager(docManaged.NameTable);
xmlManager.AddNamespace("prefix", "http://schemas.microsoft.com/developer/msbuild/2003");
foreach (XmlNode xmlNode in docManaged.SelectNodes(@"//prefix:ProjectReference", xmlManager))
{
string dependencyGuid = xmlNode.SelectSingleNode(@"prefix:Project", xmlManager).InnerText.Trim(); // TODO handle null
string dependencyName = xmlNode.SelectSingleNode(@"prefix:Name", xmlManager).InnerText.Trim(); // TODO handle null
yield return FindProjectInContainer(
dependencyGuid,
"Cannot find one of the dependency of project '{0}'.\nProject guid: {1}\nDependency guid: {2}\nDependency name: {3}\nReference found in: ProjectReference node of file '{4}'",
m_projectName,
r_projectGuid,
dependencyGuid,
dependencyName,
this.FullPath);
}
break;
case KnownProjectTypeGuid.SolutionFolder:
break;
case KnownProjectTypeGuid.VisualC:
if (!File.Exists(this.FullPath))
{
throw new SolutionFileException(string.Format(
"Cannot detect dependencies of projet '{0}' because the project file cannot be found.\nProject full path: '{1}'",
m_projectName,
this.FullPath));
}
var docVisualC = new XmlDocument();
docVisualC.Load(this.FullPath);
foreach (XmlNode xmlNode in docVisualC.SelectNodes(@"//ProjectReference"))
{
var dependencyGuid = xmlNode.Attributes["ReferencedProjectIdentifier"].Value; // TODO handle null
string dependencyRelativePathToProject;
XmlNode relativePathToProjectNode = xmlNode.Attributes["RelativePathToProject"];
if (relativePathToProjectNode != null)
{
dependencyRelativePathToProject = relativePathToProjectNode.Value;
}
else
{
dependencyRelativePathToProject = "???";
}
yield return FindProjectInContainer(
dependencyGuid,
"Cannot find one of the dependency of project '{0}'.\nProject guid: {1}\nDependency guid: {2}\nDependency relative path: '{3}'\nReference found in: ProjectReference node of file '{4}'",
m_projectName,
r_projectGuid,
dependencyGuid,
dependencyRelativePathToProject,
this.FullPath);
}
break;
case KnownProjectTypeGuid.Setup:
if (!File.Exists(this.FullPath))
{
throw new SolutionFileException(string.Format(
"Cannot detect dependencies of projet '{0}' because the project file cannot be found.\nProject full path: '{1}'",
m_projectName,
this.FullPath));
}
foreach (string line in File.ReadAllLines(this.FullPath))
{
var regex = new Regex("^\\s*\"OutputProjectGuid\" = \"\\d*\\:(?<PROJECTGUID>.*)\"$");
var match = regex.Match(line);
if (match.Success)
{
var dependencyGuid = match.Groups["PROJECTGUID"].Value.Trim();
yield return FindProjectInContainer(
dependencyGuid,
"Cannot find one of the dependency of project '{0}'.\nProject guid: {1}\nDependency guid: {2}\nReference found in: OutputProjectGuid line of file '{3}'",
m_projectName,
r_projectGuid,
dependencyGuid,
this.FullPath);
}
}
break;
case KnownProjectTypeGuid.WebProject:
// Format is: "({GUID}|ProjectName;)*"
// Example: "{GUID}|Infra.dll;{GUID2}|Services.dll;"
var propertyLine = r_projectSections["WebsiteProperties"].PropertyLines["ProjectReferences"];
var value = propertyLine.Value;
if (value.StartsWith("\""))
value = value.Substring(1);
if (value.EndsWith("\""))
value = value.Substring(0, value.Length - 1);
foreach (string dependency in value.Split(';'))
{
if (dependency.Trim().Length > 0)
{
var parts = dependency.Split('|');
var dependencyGuid = parts[0];
var dependencyName = parts[1]; // TODO handle null
yield return FindProjectInContainer(
dependencyGuid,
"Cannot find one of the dependency of project '{0}'.\nProject guid: {1}\nDependency guid: {2}\nDependency name: {3}\nReference found in: ProjectReferences line in WebsiteProperties section of the solution file",
m_projectName,
r_projectGuid,
dependencyGuid,
dependencyName);
}
}
break;
}
}
}
public override string ToString()
{
return string.Format("Project '{0}'", this.ProjectFullName);
}
private Project FindProjectInContainer(string projectGuid, string errorMessageFormat, params object[] errorMessageParams)
{
var project = r_container.Projects.FindByGuid(projectGuid);
if (project == null)
{
throw new SolutionFileException(string.Format(errorMessageFormat, errorMessageParams));
}
return project;
}
#region public: Methods ToElement / FromElement
private const string TagProjectTypeGuid = "ProjectTypeGuid";
private const string TagProjectName = "ProjectName";
private const string TagRelativePath = "RelativePath";
private const string TagParentFolder = "ParentFolder";
private const string TagProjectSection = "S_";
private const string TagVersionControlLines = "VCL_";
private const string TagProjectConfigurationPlatformsLines = "PCPL_";
public NodeElement ToElement(ElementIdentifier identifier)
{
var childs = new List<Element>
{
new ValueElement(new ElementIdentifier(TagProjectTypeGuid), this.ProjectTypeGuid),
new ValueElement(new ElementIdentifier(TagProjectName), this.ProjectName),
new ValueElement(new ElementIdentifier(TagRelativePath), this.RelativePath)
};
if (this.ParentFolder != null)
{
childs.Add(new ValueElement(
new ElementIdentifier(TagParentFolder),
this.ParentFolder.ProjectFullName));
}
foreach (var projectSection in this.ProjectSections)
{
childs.Add(
projectSection.ToElement(
new ElementIdentifier(
TagProjectSection + projectSection.Name,
string.Format("{0} \"{1}\"", projectSection.SectionType, projectSection.Name))));
}
foreach (var propertyLine in this.VersionControlLines)
{
childs.Add(
new ValueElement(
new ElementIdentifier(
TagVersionControlLines + propertyLine.Name,
@"VersionControlLine\" + propertyLine.Name),
propertyLine.Value));
}
foreach (var propertyLine in this.ProjectConfigurationPlatformsLines)
{
childs.Add(
new ValueElement(
new ElementIdentifier(
TagProjectConfigurationPlatformsLines + propertyLine.Name,
@"ProjectConfigurationPlatformsLine\" + propertyLine.Name),
propertyLine.Value));
}
return new NodeElement(
identifier,
childs);
}
public static Project FromElement(string projectGuid, NodeElement element, Dictionary<string, string> solutionFolderGuids)
{
string projectTypeGuid = null;
string projectName = null;
string relativePath = null;
string parentFolderGuid = null;
var projectSections = new List<Section>();
var versionControlLines = new List<PropertyLine>();
var projectConfigurationPlatformsLines = new List<PropertyLine>();
foreach (var child in element.Childs)
{
var identifier = child.Identifier;
if (identifier.Name == TagProjectTypeGuid)
{
projectTypeGuid = ((ValueElement)child).Value;
}
else if (identifier.Name == TagProjectName)
{
projectName = ((ValueElement)child).Value;
}
else if (identifier.Name == TagRelativePath)
{
relativePath = ((ValueElement)child).Value;
}
else if (identifier.Name == TagParentFolder)
{
var parentProjectFullName = ((ValueElement)child).Value;
if (! solutionFolderGuids.ContainsKey(parentProjectFullName))
{
throw new Exception("TODO");
}
parentFolderGuid = solutionFolderGuids[parentProjectFullName];
}
else if (identifier.Name.StartsWith(TagProjectSection))
{
var sectionName = identifier.Name.Substring(TagProjectSection.Length);
projectSections.Add(
Section.FromElement(
sectionName,
(NodeElement)child));
}
else if (identifier.Name.StartsWith(TagVersionControlLines))
{
var name = identifier.Name.Substring(TagVersionControlLines.Length);
var value = ((ValueElement)child).Value;
versionControlLines.Add(new PropertyLine(name, value));
}
else if (identifier.Name.StartsWith(TagProjectConfigurationPlatformsLines))
{
var name = identifier.Name.Substring(TagProjectConfigurationPlatformsLines.Length);
var value = ((ValueElement)child).Value;
projectConfigurationPlatformsLines.Add(new PropertyLine(name, value));
}
else
{
throw new SolutionFileException(string.Format("Invalid identifier '{0}'.", identifier.Name));
}
}
if (projectTypeGuid == null)
throw new SolutionFileException(string.Format("Missing subelement '{0}' in a section element.", TagProjectTypeGuid));
if (projectName == null)
throw new SolutionFileException(string.Format("Missing subelement '{0}' in a section element.", TagProjectName));
if (relativePath == null)
throw new SolutionFileException(string.Format("Missing subelement '{0}' in a section element.", TagRelativePath));
return new Project(
null,
projectGuid,
projectTypeGuid,
projectName,
relativePath,
parentFolderGuid,
projectSections,
versionControlLines,
projectConfigurationPlatformsLines);
}
#endregion
}
}
| |
// Copyright (c) 2007-2017 ppy Pty Ltd <[email protected]>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using System.Collections.Generic;
using System.Linq;
using OpenTK;
using OpenTK.Graphics;
using osu.Framework.Allocation;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Colour;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.Textures;
using osu.Framework.Localisation;
using osu.Game.Beatmaps;
using osu.Game.Database;
using osu.Game.Graphics;
using osu.Game.Graphics.Sprites;
using osu.Game.Graphics.UserInterface;
using osu.Game.Rulesets.Scoring;
using osu.Game.Screens.Play;
using osu.Game.Screens.Select.Leaderboards;
using osu.Game.Users;
namespace osu.Game.Screens.Ranking
{
internal class ResultsPageScore : ResultsPage
{
private ScoreCounter scoreCounter;
public ResultsPageScore(Score score, WorkingBeatmap beatmap) : base(score, beatmap) { }
private FillFlowContainer<DrawableScoreStatistic> statisticsContainer;
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
const float user_header_height = 120;
Children = new Drawable[]
{
new Container
{
RelativeSizeAxes = Axes.Both,
Padding = new MarginPadding { Top = user_header_height },
Children = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = Color4.White,
},
}
},
new FillFlowContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Direction = FillDirection.Vertical,
Children = new Drawable[]
{
new UserHeader(Score.User)
{
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
RelativeSizeAxes = Axes.X,
Height = user_header_height,
},
new DrawableRank(Score.Rank)
{
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
Size = new Vector2(150, 60),
Margin = new MarginPadding(20),
},
new Container
{
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
RelativeSizeAxes = Axes.X,
Height = 60,
Children = new Drawable[]
{
new SongProgressGraph
{
RelativeSizeAxes = Axes.Both,
Alpha = 0.5f,
Objects = Beatmap.Beatmap.HitObjects,
},
scoreCounter = new SlowScoreCounter(6)
{
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
Colour = colours.PinkDarker,
Y = 10,
TextSize = 56,
},
}
},
new OsuSpriteText
{
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
Colour = colours.PinkDarker,
Shadow = false,
Font = @"Exo2.0-Bold",
TextSize = 16,
Text = "total score",
Margin = new MarginPadding { Bottom = 15 },
},
new BeatmapDetails(Beatmap.BeatmapInfo)
{
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
Margin = new MarginPadding { Bottom = 10 },
},
new DateTimeDisplay(Score.Date.LocalDateTime)
{
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
},
new Container
{
RelativeSizeAxes = Axes.X,
Size = new Vector2(0.75f, 1),
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
Margin = new MarginPadding { Top = 10, Bottom = 10 },
Children = new Drawable[]
{
new Box
{
ColourInfo = ColourInfo.GradientHorizontal(
colours.GrayC.Opacity(0),
colours.GrayC.Opacity(0.9f)),
RelativeSizeAxes = Axes.Both,
Size = new Vector2(0.5f, 1),
},
new Box
{
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
ColourInfo = ColourInfo.GradientHorizontal(
colours.GrayC.Opacity(0.9f),
colours.GrayC.Opacity(0)),
RelativeSizeAxes = Axes.Both,
Size = new Vector2(0.5f, 1),
},
}
},
statisticsContainer = new FillFlowContainer<DrawableScoreStatistic>
{
AutoSizeAxes = Axes.Both,
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
Direction = FillDirection.Horizontal,
LayoutDuration = 200,
LayoutEasing = EasingTypes.OutQuint
}
}
}
};
statisticsContainer.Children = Score.Statistics.Select(s => new DrawableScoreStatistic(s));
}
protected override void LoadComplete()
{
base.LoadComplete();
Schedule(() =>
{
scoreCounter.Increment(Score.TotalScore);
int delay = 0;
foreach (var s in statisticsContainer.Children)
{
s.FadeOut();
s.Delay(delay += 200);
s.FadeIn(300 + delay, EasingTypes.Out);
}
});
}
private class DrawableScoreStatistic : Container
{
private readonly KeyValuePair<string, dynamic> statistic;
public DrawableScoreStatistic(KeyValuePair<string, dynamic> statistic)
{
this.statistic = statistic;
AutoSizeAxes = Axes.Both;
Margin = new MarginPadding { Left = 5, Right = 5 };
}
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
Children = new Drawable[]
{
new SpriteText {
Text = statistic.Value.ToString().PadLeft(4, '0'),
Colour = colours.Gray7,
TextSize = 30,
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
},
new SpriteText {
Text = statistic.Key,
Colour = colours.Gray7,
Font = @"Exo2.0-Bold",
Y = 26,
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
},
};
}
}
private class DateTimeDisplay : Container
{
private DateTime datetime;
public DateTimeDisplay(DateTime datetime)
{
this.datetime = datetime;
AutoSizeAxes = Axes.Y;
Width = 140;
Masking = true;
CornerRadius = 5;
}
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
Children = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = colours.Gray6,
},
new OsuSpriteText
{
Origin = Anchor.CentreLeft,
Anchor = Anchor.CentreLeft,
Text = datetime.ToString("HH:mm"),
Padding = new MarginPadding { Left = 10, Right = 10, Top = 5, Bottom = 5 },
Colour = Color4.White,
},
new OsuSpriteText
{
Origin = Anchor.CentreRight,
Anchor = Anchor.CentreRight,
Text = datetime.ToString("yyyy/MM/dd"),
Padding = new MarginPadding { Left = 10, Right = 10, Top = 5, Bottom = 5 },
Colour = Color4.White,
}
};
}
}
private class BeatmapDetails : Container
{
private readonly BeatmapInfo beatmap;
private readonly OsuSpriteText title;
private readonly OsuSpriteText artist;
private readonly OsuSpriteText versionMapper;
public BeatmapDetails(BeatmapInfo beatmap)
{
this.beatmap = beatmap;
AutoSizeAxes = Axes.Both;
Children = new Drawable[]
{
new FillFlowContainer
{
Direction = FillDirection.Vertical,
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Children = new Drawable[]
{
title = new OsuSpriteText
{
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
Shadow = false,
TextSize = 24,
Font = @"Exo2.0-BoldItalic",
},
artist = new OsuSpriteText
{
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
Shadow = false,
TextSize = 20,
Font = @"Exo2.0-BoldItalic",
},
versionMapper = new OsuSpriteText
{
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
Shadow = false,
TextSize = 16,
Font = @"Exo2.0-Bold",
},
}
}
};
}
[BackgroundDependencyLoader]
private void load(OsuColour colours, LocalisationEngine localisation)
{
title.Colour = artist.Colour = colours.BlueDarker;
versionMapper.Colour = colours.Gray8;
versionMapper.Text = $"{beatmap.Version} - mapped by {beatmap.Metadata.Author}";
title.Current = localisation.GetUnicodePreference(beatmap.Metadata.TitleUnicode, beatmap.Metadata.Title);
artist.Current = localisation.GetUnicodePreference(beatmap.Metadata.ArtistUnicode, beatmap.Metadata.Artist);
}
}
private class UserHeader : Container
{
private readonly User user;
private readonly Sprite cover;
public UserHeader(User user)
{
this.user = user;
Children = new Drawable[]
{
cover = new Sprite
{
FillMode = FillMode.Fill,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
},
new OsuSpriteText
{
Font = @"Exo2.0-RegularItalic",
Text = user.Username,
Anchor = Anchor.BottomCentre,
Origin = Anchor.BottomCentre,
TextSize = 30,
Padding = new MarginPadding { Bottom = 10 },
}
};
}
[BackgroundDependencyLoader]
private void load(TextureStore textures)
{
if (!string.IsNullOrEmpty(user.CoverUrl))
cover.Texture = textures.Get(user.CoverUrl);
}
}
private class SlowScoreCounter : ScoreCounter
{
protected override double RollingDuration => 3000;
protected override EasingTypes RollingEasing => EasingTypes.OutPow10;
public SlowScoreCounter(uint leading = 0) : base(leading)
{
DisplayedCountSpriteText.Shadow = false;
DisplayedCountSpriteText.Font = @"Venera-Light";
UseCommaSeparator = true;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Web;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Com.Aspose.Storage.Model;
namespace Com.Aspose.Storage
{
public class ApiInvoker
{
private static readonly ApiInvoker _instance = new ApiInvoker();
private Dictionary<String, String> defaultHeaderMap = new Dictionary<String, String>();
public String APP_SID = "appSid";
public String API_KEY = "apiKey";
public static ApiInvoker GetInstance()
{
return _instance;
}
public void addDefaultHeader(string key, string value)
{
defaultHeaderMap.Add(key, value);
}
public string escapeString(string str)
{
return str;
}
public static object deserialize(string json, Type type)
{
try
{
return JsonConvert.DeserializeObject(json, type);
}
catch (IOException e)
{
throw new ApiException(500, e.Message);
}
}
public static object deserialize(byte[] BinaryData, Type type)
{
try
{
return new ResponseMessage(BinaryData);
}
catch (IOException e)
{
throw new ApiException(500, e.Message);
}
}
private static string Sign(string url, string appKey)
{
UriBuilder uriBuilder = new UriBuilder(url);
// Remove final slash here as it can be added automatically.
uriBuilder.Path = uriBuilder.Path.TrimEnd('/');
// Compute the hash.
byte[] privateKey = Encoding.UTF8.GetBytes(appKey);
HMACSHA1 algorithm = new HMACSHA1(privateKey);
byte[] sequence = ASCIIEncoding.ASCII.GetBytes(uriBuilder.Uri.AbsoluteUri);
byte[] hash = algorithm.ComputeHash(sequence);
string signature = Convert.ToBase64String(hash);
// Remove invalid symbols.
signature = signature.TrimEnd('=');
signature = HttpUtility.UrlEncode(signature);
// Convert codes to upper case as they can be updated automatically.
signature = Regex.Replace(signature, "%[0-9a-f]{2}", e => e.Value.ToUpper());
// Add the signature to query string.
return string.Format("{0}&signature={1}", uriBuilder.Uri.AbsoluteUri, signature);
}
public static string serialize(object obj)
{
try
{
return obj != null ? JsonConvert.SerializeObject(obj) : null;
}
catch (Exception e)
{
throw new ApiException(500, e.Message);
}
}
public string invokeAPI(string host, string path, string method, Dictionary<String, String> queryParams, object body, Dictionary<String, String> headerParams, Dictionary<String, object> formParams)
{
return invokeAPIInternal(host, path, method, false, queryParams, body, headerParams, formParams) as string;
}
public byte[] invokeBinaryAPI(string host, string path, string method, Dictionary<String, String> queryParams, object body, Dictionary<String, String> headerParams, Dictionary<String, object> formParams)
{
return invokeAPIInternal(host, path, method, true, queryParams, body, headerParams, formParams) as byte[];
}
private object invokeAPIInternal(string host, string path, string method, bool binaryResponse, Dictionary<String, String> queryParams, object body, Dictionary<String, String> headerParams, Dictionary<String, object> formParams)
{
path = path.Replace("{appSid}", this.defaultHeaderMap[APP_SID]);
path = Regex.Replace(path, @"{.+?}", "");
//var b = new StringBuilder();
host = host.EndsWith("/") ? host.Substring(0, host.Length - 1) : host;
path = Sign(host + path, this.defaultHeaderMap[API_KEY]);
var client = WebRequest.Create(path);
client.Method = method;
byte[] formData = null;
if (formParams.Count > 0)
{
//string formDataBoundary = String.Format("----------{0:N}", Guid.NewGuid());
//client.ContentType = "multipart/form-data; boundary=" + formDataBoundary;
//formData = GetMultipartFormData(formParams, formDataBoundary);
//client.ContentLength = formData.Length;
client.ContentType = "multipart/form-data";
formData = GetMultipartFormData(formParams, "");
client.ContentLength = formData.Length;
}
else
{
client.ContentType = "application/json";
}
foreach (var headerParamsItem in headerParams)
{
client.Headers.Add(headerParamsItem.Key, headerParamsItem.Value);
}
foreach (var defaultHeaderMapItem in defaultHeaderMap.Where(defaultHeaderMapItem => !headerParams.ContainsKey(defaultHeaderMapItem.Key)))
{
client.Headers.Add(defaultHeaderMapItem.Key, defaultHeaderMapItem.Value);
}
switch (method)
{
case "GET":
break;
case "POST":
case "PUT":
case "DELETE":
using (Stream requestStream = client.GetRequestStream())
{
if (formData != null)
{
requestStream.Write(formData, 0, formData.Length);
}
var swRequestWriter = new StreamWriter(requestStream);
swRequestWriter.Write(serialize(body));
swRequestWriter.Close();
}
break;
default:
throw new ApiException(500, "unknown method type " + method);
}
try
{
var webResponse = (HttpWebResponse)client.GetResponse();
if (webResponse.StatusCode != HttpStatusCode.OK)
{
webResponse.Close();
throw new ApiException((int)webResponse.StatusCode, webResponse.StatusDescription);
}
if (binaryResponse)
{
using (var memoryStream = new MemoryStream())
{
webResponse.GetResponseStream().CopyTo(memoryStream);
return memoryStream.ToArray();
}
}
else
{
using (var responseReader = new StreamReader(webResponse.GetResponseStream()))
{
var responseData = responseReader.ReadToEnd();
return responseData;
}
}
}
catch (WebException ex)
{
var response = ex.Response as HttpWebResponse;
int statusCode = 0;
if (response != null)
{
statusCode = (int)response.StatusCode;
response.Close();
}
throw new ApiException(statusCode, ex.Message);
}
}
private static byte[] GetMultipartFormData(Dictionary<string, object> postParameters, string boundary)
{
Stream formDataStream = new System.IO.MemoryStream();
//bool needsCLRF = false;
foreach (var param in postParameters)
{
// Thanks to feedback from commenters, add a CRLF to allow multiple parameters to be added.
// Skip it on the first parameter, add it to subsequent parameters.
//if (needsCLRF)
// formDataStream.Write(Encoding.UTF8.GetBytes("\r\n"), 0, Encoding.UTF8.GetByteCount("\r\n"));
//needsCLRF = true;
if (param.Value is byte[])
{
//string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n",
// boundary,
// param.Key,
// "application/octet-stream");
//formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData));
// Write the file data directly to the Stream, rather than serializing it to a string.
formDataStream.Write((param.Value as byte[]), 0, (param.Value as byte[]).Length);
}
else
{
//string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}",
// boundary,
// param.Key,
// param.Value);
string postData = (string)param.Value;
formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData));
}
}
// Add the end of the request. Start with a newline
//string footer = "\r\n--" + boundary + "--\r\n";
//formDataStream.Write(Encoding.UTF8.GetBytes(footer), 0, Encoding.UTF8.GetByteCount(footer));
// Dump the Stream into a byte[]
formDataStream.Position = 0;
byte[] formData = new byte[formDataStream.Length];
formDataStream.Read(formData, 0, formData.Length);
formDataStream.Close();
return formData;
}
/**
* Overloaded method for returning the path value
* For a string value an empty value is returned if the value is null
* @param value
* @return
*/
public String ToPathValue(String value)
{
return (value == null) ? "" : value;
}
public String ToPathValue(int value)
{
return value.ToString();
}
public String ToPathValue(float value)
{
return value.ToString();
}
public String ToPathValue(long value)
{
return value.ToString();
}
public String ToPathValue(bool value)
{
return value.ToString();
}
public String ToPathValue(Double value)
{
return value.ToString();
}
public String ToPathValue(Com.Aspose.Storage.Model.DateTime value)
{
//SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
//return format.format(value);
return value.ToString();
}
}
}
| |
#region Copyright notice and license
// Copyright 2015, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Google.ProtocolBuffers;
using grpc.testing;
using Grpc.Auth;
using Grpc.Core;
using Grpc.Core.Utils;
using NUnit.Framework;
namespace Grpc.IntegrationTesting
{
public class InteropClient
{
private const string ServiceAccountUser = "155450119199-3psnrh1sdr3d8cpj1v46naggf81mhdnk@developer.gserviceaccount.com";
private const string ComputeEngineUser = "155450119199-r5aaqa2vqoa9g5mv2m6s3m1l293rlmel@developer.gserviceaccount.com";
private const string AuthScope = "https://www.googleapis.com/auth/xapi.zoo";
private const string AuthScopeResponse = "xapi.zoo";
private class ClientOptions
{
public bool help;
public string serverHost = "127.0.0.1";
public string serverHostOverride = TestCredentials.DefaultHostOverride;
public int? serverPort;
public string testCase = "large_unary";
public bool useTls;
public bool useTestCa;
}
ClientOptions options;
private InteropClient(ClientOptions options)
{
this.options = options;
}
public static void Run(string[] args)
{
Console.WriteLine("gRPC C# interop testing client");
ClientOptions options = ParseArguments(args);
if (options.serverHost == null || !options.serverPort.HasValue || options.testCase == null)
{
Console.WriteLine("Missing required argument.");
Console.WriteLine();
options.help = true;
}
if (options.help)
{
Console.WriteLine("Usage:");
Console.WriteLine(" --server_host=HOSTNAME");
Console.WriteLine(" --server_host_override=HOSTNAME");
Console.WriteLine(" --server_port=PORT");
Console.WriteLine(" --test_case=TESTCASE");
Console.WriteLine(" --use_tls=BOOLEAN");
Console.WriteLine(" --use_test_ca=BOOLEAN");
Console.WriteLine();
Environment.Exit(1);
}
var interopClient = new InteropClient(options);
interopClient.Run();
}
private void Run()
{
Credentials credentials = null;
if (options.useTls)
{
credentials = TestCredentials.CreateTestClientCredentials(options.useTestCa);
}
List<ChannelOption> channelOptions = null;
if (!string.IsNullOrEmpty(options.serverHostOverride))
{
channelOptions = new List<ChannelOption>
{
new ChannelOption(ChannelOptions.SslTargetNameOverride, options.serverHostOverride)
};
}
using (Channel channel = new Channel(options.serverHost, options.serverPort.Value, credentials, channelOptions))
{
TestService.TestServiceClient client = new TestService.TestServiceClient(channel);
if (options.testCase == "service_account_creds" || options.testCase == "compute_engine_creds")
{
var credential = GoogleCredential.GetApplicationDefault();
if (credential.IsCreateScopedRequired)
{
credential = credential.CreateScoped(new[] { AuthScope });
}
client.HeaderInterceptor = OAuth2InterceptorFactory.Create(credential);
}
RunTestCase(options.testCase, client);
}
GrpcEnvironment.Shutdown();
}
private void RunTestCase(string testCase, TestService.TestServiceClient client)
{
switch (testCase)
{
case "empty_unary":
RunEmptyUnary(client);
break;
case "large_unary":
RunLargeUnary(client);
break;
case "client_streaming":
RunClientStreaming(client);
break;
case "server_streaming":
RunServerStreaming(client);
break;
case "ping_pong":
RunPingPong(client);
break;
case "empty_stream":
RunEmptyStream(client);
break;
case "service_account_creds":
RunServiceAccountCreds(client);
break;
case "compute_engine_creds":
RunComputeEngineCreds(client);
break;
case "oauth2_auth_token":
RunOAuth2AuthToken(client);
break;
case "per_rpc_creds":
RunPerRpcCreds(client);
break;
case "cancel_after_begin":
RunCancelAfterBegin(client);
break;
case "cancel_after_first_response":
RunCancelAfterFirstResponse(client);
break;
case "benchmark_empty_unary":
RunBenchmarkEmptyUnary(client);
break;
default:
throw new ArgumentException("Unknown test case " + testCase);
}
}
public static void RunEmptyUnary(TestService.ITestServiceClient client)
{
Console.WriteLine("running empty_unary");
var response = client.EmptyCall(Empty.DefaultInstance);
Assert.IsNotNull(response);
Console.WriteLine("Passed!");
}
public static void RunLargeUnary(TestService.ITestServiceClient client)
{
Console.WriteLine("running large_unary");
var request = SimpleRequest.CreateBuilder()
.SetResponseType(PayloadType.COMPRESSABLE)
.SetResponseSize(314159)
.SetPayload(CreateZerosPayload(271828))
.Build();
var response = client.UnaryCall(request);
Assert.AreEqual(PayloadType.COMPRESSABLE, response.Payload.Type);
Assert.AreEqual(314159, response.Payload.Body.Length);
Console.WriteLine("Passed!");
}
public static void RunClientStreaming(TestService.ITestServiceClient client)
{
Task.Run(async () =>
{
Console.WriteLine("running client_streaming");
var bodySizes = new List<int> { 27182, 8, 1828, 45904 }.ConvertAll((size) => StreamingInputCallRequest.CreateBuilder().SetPayload(CreateZerosPayload(size)).Build());
using (var call = client.StreamingInputCall())
{
await call.RequestStream.WriteAll(bodySizes);
var response = await call.ResponseAsync;
Assert.AreEqual(74922, response.AggregatedPayloadSize);
}
Console.WriteLine("Passed!");
}).Wait();
}
public static void RunServerStreaming(TestService.ITestServiceClient client)
{
Task.Run(async () =>
{
Console.WriteLine("running server_streaming");
var bodySizes = new List<int> { 31415, 9, 2653, 58979 };
var request = StreamingOutputCallRequest.CreateBuilder()
.SetResponseType(PayloadType.COMPRESSABLE)
.AddRangeResponseParameters(bodySizes.ConvertAll(
(size) => ResponseParameters.CreateBuilder().SetSize(size).Build()))
.Build();
using (var call = client.StreamingOutputCall(request))
{
var responseList = await call.ResponseStream.ToList();
foreach (var res in responseList)
{
Assert.AreEqual(PayloadType.COMPRESSABLE, res.Payload.Type);
}
CollectionAssert.AreEqual(bodySizes, responseList.ConvertAll((item) => item.Payload.Body.Length));
}
Console.WriteLine("Passed!");
}).Wait();
}
public static void RunPingPong(TestService.ITestServiceClient client)
{
Task.Run(async () =>
{
Console.WriteLine("running ping_pong");
using (var call = client.FullDuplexCall())
{
await call.RequestStream.WriteAsync(StreamingOutputCallRequest.CreateBuilder()
.SetResponseType(PayloadType.COMPRESSABLE)
.AddResponseParameters(ResponseParameters.CreateBuilder().SetSize(31415))
.SetPayload(CreateZerosPayload(27182)).Build());
Assert.IsTrue(await call.ResponseStream.MoveNext());
Assert.AreEqual(PayloadType.COMPRESSABLE, call.ResponseStream.Current.Payload.Type);
Assert.AreEqual(31415, call.ResponseStream.Current.Payload.Body.Length);
await call.RequestStream.WriteAsync(StreamingOutputCallRequest.CreateBuilder()
.SetResponseType(PayloadType.COMPRESSABLE)
.AddResponseParameters(ResponseParameters.CreateBuilder().SetSize(9))
.SetPayload(CreateZerosPayload(8)).Build());
Assert.IsTrue(await call.ResponseStream.MoveNext());
Assert.AreEqual(PayloadType.COMPRESSABLE, call.ResponseStream.Current.Payload.Type);
Assert.AreEqual(9, call.ResponseStream.Current.Payload.Body.Length);
await call.RequestStream.WriteAsync(StreamingOutputCallRequest.CreateBuilder()
.SetResponseType(PayloadType.COMPRESSABLE)
.AddResponseParameters(ResponseParameters.CreateBuilder().SetSize(2653))
.SetPayload(CreateZerosPayload(1828)).Build());
Assert.IsTrue(await call.ResponseStream.MoveNext());
Assert.AreEqual(PayloadType.COMPRESSABLE, call.ResponseStream.Current.Payload.Type);
Assert.AreEqual(2653, call.ResponseStream.Current.Payload.Body.Length);
await call.RequestStream.WriteAsync(StreamingOutputCallRequest.CreateBuilder()
.SetResponseType(PayloadType.COMPRESSABLE)
.AddResponseParameters(ResponseParameters.CreateBuilder().SetSize(58979))
.SetPayload(CreateZerosPayload(45904)).Build());
Assert.IsTrue(await call.ResponseStream.MoveNext());
Assert.AreEqual(PayloadType.COMPRESSABLE, call.ResponseStream.Current.Payload.Type);
Assert.AreEqual(58979, call.ResponseStream.Current.Payload.Body.Length);
await call.RequestStream.CompleteAsync();
Assert.IsFalse(await call.ResponseStream.MoveNext());
}
Console.WriteLine("Passed!");
}).Wait();
}
public static void RunEmptyStream(TestService.ITestServiceClient client)
{
Task.Run(async () =>
{
Console.WriteLine("running empty_stream");
using (var call = client.FullDuplexCall())
{
await call.RequestStream.CompleteAsync();
var responseList = await call.ResponseStream.ToList();
Assert.AreEqual(0, responseList.Count);
}
Console.WriteLine("Passed!");
}).Wait();
}
public static void RunServiceAccountCreds(TestService.ITestServiceClient client)
{
Console.WriteLine("running service_account_creds");
var request = SimpleRequest.CreateBuilder()
.SetResponseType(PayloadType.COMPRESSABLE)
.SetResponseSize(314159)
.SetPayload(CreateZerosPayload(271828))
.SetFillUsername(true)
.SetFillOauthScope(true)
.Build();
var response = client.UnaryCall(request);
Assert.AreEqual(PayloadType.COMPRESSABLE, response.Payload.Type);
Assert.AreEqual(314159, response.Payload.Body.Length);
Assert.AreEqual(AuthScopeResponse, response.OauthScope);
Assert.AreEqual(ServiceAccountUser, response.Username);
Console.WriteLine("Passed!");
}
public static void RunComputeEngineCreds(TestService.ITestServiceClient client)
{
Console.WriteLine("running compute_engine_creds");
var request = SimpleRequest.CreateBuilder()
.SetResponseType(PayloadType.COMPRESSABLE)
.SetResponseSize(314159)
.SetPayload(CreateZerosPayload(271828))
.SetFillUsername(true)
.SetFillOauthScope(true)
.Build();
var response = client.UnaryCall(request);
Assert.AreEqual(PayloadType.COMPRESSABLE, response.Payload.Type);
Assert.AreEqual(314159, response.Payload.Body.Length);
Assert.AreEqual(AuthScopeResponse, response.OauthScope);
Assert.AreEqual(ComputeEngineUser, response.Username);
Console.WriteLine("Passed!");
}
public static void RunOAuth2AuthToken(TestService.TestServiceClient client)
{
Console.WriteLine("running oauth2_auth_token");
var credential = GoogleCredential.GetApplicationDefault().CreateScoped(new[] { AuthScope });
Assert.IsTrue(credential.RequestAccessTokenAsync(CancellationToken.None).Result);
string oauth2Token = credential.Token.AccessToken;
// Intercept calls with an OAuth2 token obtained out-of-band.
client.HeaderInterceptor = new MetadataInterceptorDelegate((metadata) =>
{
metadata.Add(new Metadata.Entry("Authorization", "Bearer " + oauth2Token));
});
var request = SimpleRequest.CreateBuilder()
.SetFillUsername(true)
.SetFillOauthScope(true)
.Build();
var response = client.UnaryCall(request);
Assert.AreEqual(AuthScopeResponse, response.OauthScope);
Assert.AreEqual(ServiceAccountUser, response.Username);
Console.WriteLine("Passed!");
}
public static void RunPerRpcCreds(TestService.TestServiceClient client)
{
Console.WriteLine("running per_rpc_creds");
var credential = GoogleCredential.GetApplicationDefault().CreateScoped(new[] { AuthScope });
Assert.IsTrue(credential.RequestAccessTokenAsync(CancellationToken.None).Result);
string oauth2Token = credential.Token.AccessToken;
var request = SimpleRequest.CreateBuilder()
.SetFillUsername(true)
.SetFillOauthScope(true)
.Build();
var response = client.UnaryCall(request, headers: new Metadata { new Metadata.Entry("Authorization", "Bearer " + oauth2Token) });
Assert.AreEqual(AuthScopeResponse, response.OauthScope);
Assert.AreEqual(ServiceAccountUser, response.Username);
Console.WriteLine("Passed!");
}
public static void RunCancelAfterBegin(TestService.ITestServiceClient client)
{
Task.Run(async () =>
{
Console.WriteLine("running cancel_after_begin");
var cts = new CancellationTokenSource();
using (var call = client.StreamingInputCall(cancellationToken: cts.Token))
{
// TODO(jtattermusch): we need this to ensure call has been initiated once we cancel it.
await Task.Delay(1000);
cts.Cancel();
try
{
var response = await call.ResponseAsync;
Assert.Fail();
}
catch (RpcException e)
{
Assert.AreEqual(StatusCode.Cancelled, e.Status.StatusCode);
}
}
Console.WriteLine("Passed!");
}).Wait();
}
public static void RunCancelAfterFirstResponse(TestService.ITestServiceClient client)
{
Task.Run(async () =>
{
Console.WriteLine("running cancel_after_first_response");
var cts = new CancellationTokenSource();
using (var call = client.FullDuplexCall(cancellationToken: cts.Token))
{
await call.RequestStream.WriteAsync(StreamingOutputCallRequest.CreateBuilder()
.SetResponseType(PayloadType.COMPRESSABLE)
.AddResponseParameters(ResponseParameters.CreateBuilder().SetSize(31415))
.SetPayload(CreateZerosPayload(27182)).Build());
Assert.IsTrue(await call.ResponseStream.MoveNext());
Assert.AreEqual(PayloadType.COMPRESSABLE, call.ResponseStream.Current.Payload.Type);
Assert.AreEqual(31415, call.ResponseStream.Current.Payload.Body.Length);
cts.Cancel();
try
{
await call.ResponseStream.MoveNext();
Assert.Fail();
}
catch (RpcException e)
{
Assert.AreEqual(StatusCode.Cancelled, e.Status.StatusCode);
}
}
Console.WriteLine("Passed!");
}).Wait();
}
// This is not an official interop test, but it's useful.
public static void RunBenchmarkEmptyUnary(TestService.ITestServiceClient client)
{
BenchmarkUtil.RunBenchmark(10000, 10000,
() => { client.EmptyCall(Empty.DefaultInstance); });
}
private static Payload CreateZerosPayload(int size)
{
return Payload.CreateBuilder().SetBody(ByteString.CopyFrom(new byte[size])).Build();
}
private static ClientOptions ParseArguments(string[] args)
{
var options = new ClientOptions();
foreach (string arg in args)
{
ParseArgument(arg, options);
if (options.help)
{
break;
}
}
return options;
}
private static void ParseArgument(string arg, ClientOptions options)
{
Match match;
match = Regex.Match(arg, "--server_host=(.*)");
if (match.Success)
{
options.serverHost = match.Groups[1].Value.Trim();
return;
}
match = Regex.Match(arg, "--server_host_override=(.*)");
if (match.Success)
{
options.serverHostOverride = match.Groups[1].Value.Trim();
return;
}
match = Regex.Match(arg, "--server_port=(.*)");
if (match.Success)
{
options.serverPort = int.Parse(match.Groups[1].Value.Trim());
return;
}
match = Regex.Match(arg, "--test_case=(.*)");
if (match.Success)
{
options.testCase = match.Groups[1].Value.Trim();
return;
}
match = Regex.Match(arg, "--use_tls=(.*)");
if (match.Success)
{
options.useTls = bool.Parse(match.Groups[1].Value.Trim());
return;
}
match = Regex.Match(arg, "--use_test_ca=(.*)");
if (match.Success)
{
options.useTestCa = bool.Parse(match.Groups[1].Value.Trim());
return;
}
Console.WriteLine(string.Format("Unrecognized argument \"{0}\"", arg));
options.help = true;
}
}
}
| |
using Orleans.Serialization.Serializers;
using Orleans.Serialization.Utilities;
using Microsoft.Extensions.ObjectPool;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using System.Threading;
namespace Orleans.Serialization.Cloning
{
public interface IDeepCopierProvider
{
IDeepCopier<T> GetDeepCopier<T>();
IDeepCopier<T> TryGetDeepCopier<T>();
IDeepCopier<object> GetDeepCopier(Type type);
IDeepCopier<object> TryGetDeepCopier(Type type);
IBaseCopier<T> GetBaseCopier<T>() where T : class;
}
public interface IDeepCopier { }
public interface IDeepCopier<T> : IDeepCopier
{
T DeepCopy(T input, CopyContext context);
}
public interface IBaseCopier
{
}
public interface IBaseCopier<T> : IBaseCopier where T : class
{
void DeepCopy(T input, T output, CopyContext context);
}
/// <summary>
/// Indicates that an IDeepCopier implementation generalizes over all sub-types.
/// </summary>
public interface IDerivedTypeCopier
{
}
public interface IGeneralizedCopier : IDeepCopier<object>
{
bool IsSupportedType(Type type);
}
public interface ISpecializableCopier
{
bool IsSupportedType(Type type);
IDeepCopier GetSpecializedCodec(Type type);
}
public sealed class CopyContext : IDisposable
{
private readonly Dictionary<object, object> _copies = new(ReferenceEqualsComparer.Default);
private readonly CodecProvider _copierProvider;
private readonly Action<CopyContext> _onDisposed;
public CopyContext(CodecProvider codecProvider, Action<CopyContext> onDisposed)
{
_copierProvider = codecProvider;
_onDisposed = onDisposed;
}
public bool TryGetCopy<T>(object original, out T result) where T : class
{
if (original is null)
{
result = null;
return true;
}
if (_copies.TryGetValue(original, out var existing))
{
result = existing as T;
return true;
}
result = null;
return false;
}
public void RecordCopy(object original, object copy)
{
_copies[original] = copy;
}
public void Reset() => _copies.Clear();
public T Copy<T>(T value)
{
var copier = _copierProvider.GetDeepCopier(value.GetType());
return (T)copier.DeepCopy(value, this);
}
public void Dispose() => _onDisposed?.Invoke(this);
}
internal static class ShallowCopyableTypes
{
private static readonly ConcurrentDictionary<Type, bool> Types = new()
{
[typeof(decimal)] = true,
[typeof(DateTime)] = true,
[typeof(DateTimeOffset)] = true,
[typeof(TimeSpan)] = true,
[typeof(IPAddress)] = true,
[typeof(IPEndPoint)] = true,
[typeof(string)] = true,
[typeof(CancellationToken)] = true,
[typeof(Guid)] = true,
};
public static bool Contains(Type type)
{
if (Types.TryGetValue(type, out var result))
{
return result;
}
return Types.GetOrAdd(type, IsShallowCopyableInternal(type));
}
private static bool IsShallowCopyableInternal(Type type)
{
if (type.IsPrimitive || type.IsEnum)
{
return true;
}
if (type.IsDefined(typeof(ImmutableAttribute), false))
{
return true;
}
if (type.IsConstructedGenericType)
{
var def = type.GetGenericTypeDefinition();
if (def == typeof(Nullable<>)
|| def == typeof(Tuple<>)
|| def == typeof(Tuple<,>)
|| def == typeof(Tuple<,,>)
|| def == typeof(Tuple<,,,>)
|| def == typeof(Tuple<,,,,>)
|| def == typeof(Tuple<,,,,,>)
|| def == typeof(Tuple<,,,,,,>)
|| def == typeof(Tuple<,,,,,,,>))
{
return Array.TrueForAll(type.GenericTypeArguments, a => Contains(a));
}
}
if (type.IsValueType && !type.IsGenericTypeDefinition)
{
return Array.TrueForAll(type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic), f => Contains(f.FieldType));
}
if (typeof(Exception).IsAssignableFrom(type))
{
return true;
}
return false;
}
}
/// <summary>throw new NotImplementedException();
/// Methods for adapting typed and untyped copiers.
/// </summary>
internal static class CopierAdapter
{
/// <summary>
/// Converts a strongly-typed copier into an untyped copier.
/// </summary>
public static IDeepCopier<object> CreateUntypedFromTyped<T, TCopier>(TCopier typedCodec) where TCopier : IDeepCopier<T> => new TypedCopierWrapper<T, TCopier>(typedCodec);
/// <summary>
/// Converts an untyped codec into a strongly-typed codec.
/// </summary>
public static IDeepCopier<T> CreateTypedFromUntyped<T>(IDeepCopier<object> untypedCodec) => new UntypedCopierWrapper<T>(untypedCodec);
private sealed class TypedCopierWrapper<T, TCopier> : IDeepCopier<object>, IWrappedCodec where TCopier : IDeepCopier<T>
{
private readonly TCopier _copier;
public TypedCopierWrapper(TCopier codec)
{
_copier = codec;
}
object IDeepCopier<object>.DeepCopy(object original, CopyContext context) => _copier.DeepCopy((T)original, context);
public object Inner => _copier;
}
private sealed class UntypedCopierWrapper<T> : IWrappedCodec, IDeepCopier<T>
{
private readonly IDeepCopier<object> _codec;
public UntypedCopierWrapper(IDeepCopier<object> codec)
{
_codec = codec;
}
public object Inner => _codec;
T IDeepCopier<T>.DeepCopy(T original, CopyContext context) => (T)_codec.DeepCopy(original, context);
}
}
public sealed class ShallowCopyableTypeCopier<T> : IDeepCopier<T>
{
public T DeepCopy(T input, CopyContext context) => input;
}
public sealed class CopyContextPool
{
private readonly ObjectPool<CopyContext> _pool;
public CopyContextPool(CodecProvider codecProvider)
{
var sessionPoolPolicy = new PoolPolicy(codecProvider, Return);
_pool = new DefaultObjectPool<CopyContext>(sessionPoolPolicy);
}
public CopyContext GetContext() => _pool.Get();
private void Return(CopyContext session) => _pool.Return(session);
private class PoolPolicy : IPooledObjectPolicy<CopyContext>
{
private readonly CodecProvider _codecProvider;
private readonly Action<CopyContext> _onDisposed;
public PoolPolicy(CodecProvider codecProvider, Action<CopyContext> onDisposed)
{
_codecProvider = codecProvider;
_onDisposed = onDisposed;
}
public CopyContext Create() => new(_codecProvider, _onDisposed);
public bool Return(CopyContext obj)
{
obj.Reset();
return true;
}
}
}
}
| |
// 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.IO.Pipelines;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http.Connections.Internal;
using Microsoft.AspNetCore.SignalR.Tests;
using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Xunit;
namespace Microsoft.AspNetCore.Http.Connections.Tests
{
public class HttpConnectionManagerTests : VerifiableLoggedTest
{
[Fact]
public void HttpConnectionDispatcherOptionsDefaults()
{
var options = new HttpConnectionDispatcherOptions();
Assert.Equal(TimeSpan.FromSeconds(10), options.TransportSendTimeout);
Assert.Equal(65536, options.TransportMaxBufferSize);
Assert.Equal(65536, options.ApplicationMaxBufferSize);
Assert.Equal(HttpTransports.All, options.Transports);
Assert.False(options.CloseOnAuthenticationExpiration);
}
[Fact]
public void HttpConnectionDispatcherOptionsNegativeBufferSizeThrows()
{
var httpOptions = new HttpConnectionDispatcherOptions();
Assert.Throws<ArgumentOutOfRangeException>(() => httpOptions.TransportMaxBufferSize = -1);
Assert.Throws<ArgumentOutOfRangeException>(() => httpOptions.ApplicationMaxBufferSize = -1);
}
[Fact]
public void NewConnectionsHaveConnectionId()
{
using (StartVerifiableLog())
{
var connectionManager = CreateConnectionManager(LoggerFactory);
var connection = connectionManager.CreateConnection();
Assert.NotNull(connection.ConnectionId);
Assert.Equal(HttpConnectionStatus.Inactive, connection.Status);
Assert.Null(connection.ApplicationTask);
Assert.Null(connection.TransportTask);
Assert.Null(connection.Cancellation);
Assert.NotEqual(default, connection.LastSeenTicks);
Assert.NotNull(connection.Transport);
Assert.NotNull(connection.Application);
}
}
[Theory]
[InlineData(ConnectionStates.ClosedUngracefully | ConnectionStates.ApplicationNotFaulted | ConnectionStates.TransportNotFaulted)]
[InlineData(ConnectionStates.ClosedUngracefully | ConnectionStates.ApplicationNotFaulted | ConnectionStates.TransportFaulted)]
[InlineData(ConnectionStates.ClosedUngracefully | ConnectionStates.ApplicationFaulted | ConnectionStates.TransportFaulted)]
[InlineData(ConnectionStates.ClosedUngracefully | ConnectionStates.ApplicationFaulted | ConnectionStates.TransportNotFaulted)]
[InlineData(ConnectionStates.CloseGracefully | ConnectionStates.ApplicationNotFaulted | ConnectionStates.TransportNotFaulted)]
[InlineData(ConnectionStates.CloseGracefully | ConnectionStates.ApplicationNotFaulted | ConnectionStates.TransportFaulted)]
[InlineData(ConnectionStates.CloseGracefully | ConnectionStates.ApplicationFaulted | ConnectionStates.TransportFaulted)]
[InlineData(ConnectionStates.CloseGracefully | ConnectionStates.ApplicationFaulted | ConnectionStates.TransportNotFaulted)]
public async Task DisposingConnectionsClosesBothSidesOfThePipe(ConnectionStates states)
{
using (StartVerifiableLog())
{
var closeGracefully = (states & ConnectionStates.CloseGracefully) != 0;
var applicationFaulted = (states & ConnectionStates.ApplicationFaulted) != 0;
var transportFaulted = (states & ConnectionStates.TransportFaulted) != 0;
var connectionManager = CreateConnectionManager(LoggerFactory);
var connection = connectionManager.CreateConnection();
if (applicationFaulted)
{
// If the application is faulted then we want to make sure the transport task only completes after
// the application completes
connection.ApplicationTask = Task.FromException(new Exception("Application failed"));
connection.TransportTask = Task.Run(async () =>
{
// Wait for the application to end
var result = await connection.Application.Input.ReadAsync();
connection.Application.Input.AdvanceTo(result.Buffer.End);
if (transportFaulted)
{
throw new Exception("Transport failed");
}
});
}
else if (transportFaulted)
{
// If the transport is faulted then we want to make sure the transport task only completes after
// the application completes
connection.TransportTask = Task.FromException(new Exception("Application failed"));
connection.ApplicationTask = Task.Run(async () =>
{
// Wait for the application to end
var result = await connection.Transport.Input.ReadAsync();
connection.Transport.Input.AdvanceTo(result.Buffer.End);
});
}
else
{
connection.ApplicationTask = Task.CompletedTask;
connection.TransportTask = Task.CompletedTask;
}
try
{
await connection.DisposeAsync(closeGracefully).DefaultTimeout();
}
catch (Exception ex) when (!(ex is TimeoutException))
{
// Ignore the exception that bubbles out of the failing task
}
var result = await connection.Transport.Output.FlushAsync();
Assert.True(result.IsCompleted);
result = await connection.Application.Output.FlushAsync();
Assert.True(result.IsCompleted);
var exception = await Assert.ThrowsAsync<InvalidOperationException>(async () => await connection.Transport.Input.ReadAsync());
Assert.Equal("Reading is not allowed after reader was completed.", exception.Message);
exception = await Assert.ThrowsAsync<InvalidOperationException>(async () => await connection.Application.Input.ReadAsync());
Assert.Equal("Reading is not allowed after reader was completed.", exception.Message);
}
}
[Fact]
public void NewConnectionsCanBeRetrieved()
{
using (StartVerifiableLog())
{
var connectionManager = CreateConnectionManager(LoggerFactory);
var connection = connectionManager.CreateConnection();
Assert.NotNull(connection.ConnectionId);
Assert.True(connectionManager.TryGetConnection(connection.ConnectionToken, out var newConnection));
Assert.Same(newConnection, connection);
}
}
[Fact]
public void AddNewConnection()
{
using (StartVerifiableLog())
{
var connectionManager = CreateConnectionManager(LoggerFactory);
var connection = connectionManager.CreateConnection();
var transport = connection.Transport;
Assert.NotNull(connection.ConnectionId);
Assert.NotNull(connection.ConnectionToken);
Assert.NotNull(transport);
Assert.True(connectionManager.TryGetConnection(connection.ConnectionToken, out var newConnection));
Assert.Same(newConnection, connection);
Assert.Same(transport, newConnection.Transport);
}
}
[Fact]
public void RemoveConnection()
{
using (StartVerifiableLog())
{
var connectionManager = CreateConnectionManager(LoggerFactory);
var connection = connectionManager.CreateConnection();
var transport = connection.Transport;
Assert.NotNull(connection.ConnectionId);
Assert.NotNull(transport);
Assert.True(connectionManager.TryGetConnection(connection.ConnectionToken, out var newConnection));
Assert.Same(newConnection, connection);
Assert.Same(transport, newConnection.Transport);
connectionManager.RemoveConnection(connection.ConnectionToken);
Assert.False(connectionManager.TryGetConnection(connection.ConnectionToken, out newConnection));
}
}
[Fact]
public void ConnectionIdAndConnectionTokenAreTheSameForNegotiateVersionZero()
{
using (StartVerifiableLog())
{
var connectionManager = CreateConnectionManager(LoggerFactory);
var connection = connectionManager.CreateConnection(new(), negotiateVersion: 0);
var transport = connection.Transport;
Assert.NotNull(connection.ConnectionId);
Assert.NotNull(transport);
Assert.True(connectionManager.TryGetConnection(connection.ConnectionToken, out var newConnection));
Assert.Same(newConnection, connection);
Assert.Same(transport, newConnection.Transport);
Assert.Equal(connection.ConnectionId, connection.ConnectionToken);
}
}
[Fact]
public void ConnectionIdAndConnectionTokenAreDifferentForNegotiateVersionOne()
{
using (StartVerifiableLog())
{
var connectionManager = CreateConnectionManager(LoggerFactory);
var connection = connectionManager.CreateConnection(new(), negotiateVersion: 1);
var transport = connection.Transport;
Assert.NotNull(connection.ConnectionId);
Assert.NotNull(transport);
Assert.True(connectionManager.TryGetConnection(connection.ConnectionToken, out var newConnection));
Assert.False(connectionManager.TryGetConnection(connection.ConnectionId, out var _));
Assert.Same(newConnection, connection);
Assert.Same(transport, newConnection.Transport);
Assert.NotEqual(connection.ConnectionId, connection.ConnectionToken);
}
}
[Fact]
public async Task CloseConnectionsEndsAllPendingConnections()
{
using (StartVerifiableLog())
{
var connectionManager = CreateConnectionManager(LoggerFactory);
var connection = connectionManager.CreateConnection();
connection.ApplicationTask = Task.Run(async () =>
{
var result = await connection.Transport.Input.ReadAsync();
try
{
Assert.True(result.IsCompleted);
}
finally
{
connection.Transport.Input.AdvanceTo(result.Buffer.End);
}
});
connection.TransportTask = Task.Run(async () =>
{
var result = await connection.Application.Input.ReadAsync();
try
{
Assert.True(result.IsCanceled);
}
finally
{
connection.Application.Input.AdvanceTo(result.Buffer.End);
}
});
connectionManager.CloseConnections();
await connection.DisposeAsync();
}
}
[Fact]
public async Task DisposingConnectionMultipleTimesWaitsOnConnectionClose()
{
using (StartVerifiableLog())
{
var connectionManager = CreateConnectionManager(LoggerFactory);
var connection = connectionManager.CreateConnection();
var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
connection.ApplicationTask = tcs.Task;
connection.TransportTask = tcs.Task;
var firstTask = connection.DisposeAsync();
var secondTask = connection.DisposeAsync();
Assert.False(firstTask.IsCompleted);
Assert.False(secondTask.IsCompleted);
tcs.TrySetResult();
await Task.WhenAll(firstTask, secondTask).DefaultTimeout();
}
}
[Fact]
public async Task DisposingConnectionMultipleGetsExceptionFromTransportOrApp()
{
using (StartVerifiableLog())
{
var connectionManager = CreateConnectionManager(LoggerFactory);
var connection = connectionManager.CreateConnection();
var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
connection.ApplicationTask = tcs.Task;
connection.TransportTask = tcs.Task;
var firstTask = connection.DisposeAsync();
var secondTask = connection.DisposeAsync();
Assert.False(firstTask.IsCompleted);
Assert.False(secondTask.IsCompleted);
tcs.TrySetException(new InvalidOperationException("Error"));
var exception = await Assert.ThrowsAsync<InvalidOperationException>(async () => await firstTask.DefaultTimeout());
Assert.Equal("Error", exception.Message);
exception = await Assert.ThrowsAsync<InvalidOperationException>(async () => await secondTask.DefaultTimeout());
Assert.Equal("Error", exception.Message);
}
}
[Fact]
public async Task DisposingConnectionMultipleGetsCancellation()
{
using (StartVerifiableLog())
{
var connectionManager = CreateConnectionManager(LoggerFactory);
var connection = connectionManager.CreateConnection();
var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
connection.ApplicationTask = tcs.Task;
connection.TransportTask = tcs.Task;
var firstTask = connection.DisposeAsync();
var secondTask = connection.DisposeAsync();
Assert.False(firstTask.IsCompleted);
Assert.False(secondTask.IsCompleted);
tcs.TrySetCanceled();
await Assert.ThrowsAsync<TaskCanceledException>(async () => await firstTask.DefaultTimeout());
await Assert.ThrowsAsync<TaskCanceledException>(async () => await secondTask.DefaultTimeout());
}
}
[Fact]
public async Task DisposeInactiveConnection()
{
using (StartVerifiableLog())
{
var connectionManager = CreateConnectionManager(LoggerFactory);
var connection = connectionManager.CreateConnection();
Assert.NotNull(connection.ConnectionId);
Assert.NotNull(connection.Transport);
await connection.DisposeAsync();
Assert.Equal(HttpConnectionStatus.Disposed, connection.Status);
}
}
[Fact]
public async Task DisposeInactiveConnectionWithNoPipes()
{
using (StartVerifiableLog())
{
var connectionManager = CreateConnectionManager(LoggerFactory);
var connection = connectionManager.CreateConnection();
Assert.NotNull(connection.ConnectionId);
Assert.NotNull(connection.Transport);
Assert.NotNull(connection.Application);
await connection.DisposeAsync();
Assert.Equal(HttpConnectionStatus.Disposed, connection.Status);
}
}
[Fact]
public async Task ApplicationLifetimeIsHookedUp()
{
using (StartVerifiableLog())
{
var appLifetime = new TestApplicationLifetime();
var connectionManager = CreateConnectionManager(LoggerFactory, appLifetime);
appLifetime.Start();
var connection = connectionManager.CreateConnection();
appLifetime.StopApplication();
var result = await connection.Application.Output.FlushAsync();
Assert.True(result.IsCompleted);
}
}
[Fact]
public async Task ApplicationLifetimeCanStartBeforeHttpConnectionManagerInitialized()
{
using (StartVerifiableLog())
{
var appLifetime = new TestApplicationLifetime();
appLifetime.Start();
var connectionManager = CreateConnectionManager(LoggerFactory, appLifetime);
var connection = connectionManager.CreateConnection();
appLifetime.StopApplication();
var result = await connection.Application.Output.FlushAsync();
Assert.True(result.IsCompleted);
}
}
private static HttpConnectionManager CreateConnectionManager(ILoggerFactory loggerFactory, IHostApplicationLifetime lifetime = null)
{
lifetime = lifetime ?? new EmptyApplicationLifetime();
return new HttpConnectionManager(loggerFactory, lifetime, Options.Create(new ConnectionOptions()));
}
[Flags]
public enum ConnectionStates
{
ClosedUngracefully = 1,
ApplicationNotFaulted = 2,
TransportNotFaulted = 4,
ApplicationFaulted = 8,
TransportFaulted = 16,
CloseGracefully = 32
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace DotNetty.Handlers.Tls
{
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.IO;
using System.Net.Security;
using System.Runtime.ExceptionServices;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using DotNetty.Buffers;
using DotNetty.Codecs;
using DotNetty.Common.Utilities;
using DotNetty.Transport.Channels;
public sealed class TlsHandler : ByteToMessageDecoder
{
const int ReadBufferSize = 4 * 1024; // todo: research perfect size
static readonly Exception ChannelClosedException = new IOException("Channel is closed");
static readonly Action<Task, object> AuthenticationCompletionCallback = new Action<Task, object>(HandleAuthenticationCompleted);
static readonly AsyncCallback SslStreamReadCallback = new AsyncCallback(HandleSslStreamRead);
static readonly AsyncCallback SslStreamWriteCallback = new AsyncCallback(HandleSslStreamWrite);
static readonly Action<object> WriteFromQueueAction = state => ((TlsHandler)state).WriteFromQueue();
readonly SslStream sslStream;
State state;
readonly MediationStream mediationStream;
IByteBuffer sslStreamReadBuffer;
IChannelHandlerContext capturedContext;
readonly Queue<TaskCompletionSource<int>> sslStreamWriteQueue;
readonly bool isServer;
readonly X509Certificate2 certificate;
readonly string targetHost;
TlsHandler(bool isServer, X509Certificate2 certificate, string targetHost, RemoteCertificateValidationCallback certificateValidationCallback)
{
Contract.Requires(!isServer || certificate != null);
Contract.Requires(isServer || !string.IsNullOrEmpty(targetHost));
this.sslStreamWriteQueue = new Queue<TaskCompletionSource<int>>();
this.isServer = isServer;
this.certificate = certificate;
this.targetHost = targetHost;
this.mediationStream = new MediationStream(this);
this.sslStream = new SslStream(this.mediationStream, true, certificateValidationCallback);
}
public static TlsHandler Client(string targetHost)
{
return new TlsHandler(false, null, targetHost, null);
}
public static TlsHandler Client(string targetHost, X509Certificate2 certificate)
{
return new TlsHandler(false, certificate, targetHost, null);
}
public static TlsHandler Client(string targetHost, X509Certificate2 certificate, RemoteCertificateValidationCallback certificateValidationCallback)
{
return new TlsHandler(false, certificate, targetHost, certificateValidationCallback);
}
public static TlsHandler Server(X509Certificate2 certificate)
{
return new TlsHandler(true, certificate, null, null);
}
public X509Certificate LocalCertificate
{
get { return this.sslStream.LocalCertificate; }
}
public X509Certificate RemoteCertificate
{
get { return this.sslStream.RemoteCertificate; }
}
public void Dispose()
{
if (this.sslStream != null)
{
this.sslStream.Dispose();
}
}
public override void ChannelActive(IChannelHandlerContext context)
{
base.ChannelActive(context);
if (!this.isServer)
{
this.EnsureAuthenticated();
}
}
public override void ChannelInactive(IChannelHandlerContext context)
{
// Make sure to release SSLEngine,
// and notify the handshake future if the connection has been closed during handshake.
this.HandleFailure(ChannelClosedException);
base.ChannelInactive(context);
}
static void HandleAuthenticationCompleted(Task task, object state)
{
var self = (TlsHandler)state;
switch (task.Status)
{
case TaskStatus.RanToCompletion:
{
State oldState = self.state;
if ((oldState & State.AuthenticationCompleted) == 0)
{
self.state = (oldState | State.Authenticated) & ~State.Authenticating;
self.capturedContext.FireUserEventTriggered(TlsHandshakeCompletionEvent.Success);
if ((oldState & State.ReadRequestedBeforeAuthenticated) == State.ReadRequestedBeforeAuthenticated
&& !self.capturedContext.Channel.Configuration.AutoRead)
{
self.capturedContext.Read();
}
// kick off any pending writes happening before handshake completion
self.WriteFromQueue();
}
break;
}
case TaskStatus.Canceled:
case TaskStatus.Faulted:
{
// ReSharper disable once AssignNullToNotNullAttribute -- task.Exception will be present as task is faulted
State oldState = self.state;
if ((oldState & State.AuthenticationCompleted) == 0)
{
self.state = (oldState | State.FailedAuthentication) & ~State.Authenticating;
}
self.HandleFailure(task.Exception);
break;
}
default:
throw new ArgumentOutOfRangeException("task", "Unexpected task status: " + task.Status);
}
}
public override void HandlerAdded(IChannelHandlerContext context)
{
base.HandlerAdded(context);
this.capturedContext = context;
if (context.Channel.Active && !this.isServer)
{
// todo: support delayed initialization on an existing/active channel if in client mode
this.EnsureAuthenticated();
}
}
protected override void HandlerRemovedInternal(IChannelHandlerContext context)
{
this.FailPendingWrites(new ChannelException("Write has failed due to TlsHandler being removed from channel pipeline."));
}
protected override void Decode(IChannelHandlerContext context, IByteBuffer input, List<object> output)
{
// pass bytes to SslStream through input -> trigger HandleSslStreamRead. After this call sslStreamReadBuffer may or may not have bytes to read
this.mediationStream.AcceptBytes(input);
if (!this.EnsureAuthenticated())
{
return;
}
IByteBuffer readBuffer = this.sslStreamReadBuffer;
if (readBuffer == null)
{
this.sslStreamReadBuffer = readBuffer = context.Channel.Allocator.Buffer(ReadBufferSize);
this.ScheduleSslStreamRead();
}
if (readBuffer.IsReadable())
{
// SslStream parsed at least one full frame and completed read request
// Pass the buffer to a next handler in pipeline
output.Add(readBuffer);
this.sslStreamReadBuffer = null;
}
}
public override void Read(IChannelHandlerContext context)
{
State oldState = this.state;
if ((oldState & State.AuthenticationCompleted) == 0)
{
this.state = oldState | State.ReadRequestedBeforeAuthenticated;
}
context.Read();
}
bool EnsureAuthenticated()
{
State oldState = this.state;
if ((oldState & State.AuthenticationStarted) == 0)
{
this.state = oldState | State.Authenticating;
if (this.isServer)
{
this.sslStream.AuthenticateAsServerAsync(this.certificate) // todo: change to begin/end
.ContinueWith(AuthenticationCompletionCallback, this, TaskContinuationOptions.ExecuteSynchronously);
}
else
{
var certificateCollection = new X509Certificate2Collection();
if (this.certificate != null)
{
certificateCollection.Add(this.certificate);
}
this.sslStream.AuthenticateAsClientAsync(this.targetHost, certificateCollection, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12, false) // todo: change to begin/end
.ContinueWith(AuthenticationCompletionCallback, this, TaskContinuationOptions.ExecuteSynchronously);
}
return false;
}
return (oldState & State.Authenticated) == State.Authenticated;
}
void ScheduleSslStreamRead()
{
try
{
IByteBuffer buf = this.sslStreamReadBuffer;
this.sslStream.BeginRead(buf.Array, buf.ArrayOffset + buf.WriterIndex, buf.WritableBytes, SslStreamReadCallback, this);
}
catch (Exception ex)
{
this.HandleFailure(ex);
throw;
}
}
static void HandleSslStreamRead(IAsyncResult ar)
{
var self = (TlsHandler)ar.AsyncState;
int length = self.sslStream.EndRead(ar);
self.sslStreamReadBuffer.SetWriterIndex(self.sslStreamReadBuffer.ReaderIndex + length); // adjust byte buffer's writer index to reflect read progress
}
public override Task WriteAsync(IChannelHandlerContext context, object message)
{
var buf = message as IByteBuffer;
if (buf != null)
{
var tcs = new TaskCompletionSource<int>(buf);
this.sslStreamWriteQueue.Enqueue(tcs);
State oldState = this.state;
if ((oldState & (State.WriteInProgress | State.Authenticated)) == State.Authenticated) // authenticated but not writing already
{
this.state = oldState | State.WriteInProgress;
this.ScheduleWriteToSslStream(buf);
}
return tcs.Task;
}
else
{
// it's not IByteBuffer - passthrough
// todo: non-leaking termination policy?
return context.WriteAsync(message);
}
}
void ScheduleWriteToSslStream(IByteBuffer buffer)
{
this.sslStream.BeginWrite(buffer.Array, buffer.ArrayOffset + buffer.ReaderIndex, buffer.ReadableBytes, SslStreamWriteCallback, this);
}
void WriteFromQueue()
{
if (this.sslStreamWriteQueue.Count > 0)
{
TaskCompletionSource<int> tcs = this.sslStreamWriteQueue.Peek();
var buf = (IByteBuffer)tcs.Task.AsyncState;
this.ScheduleWriteToSslStream(buf);
}
}
static void HandleSslStreamWrite(IAsyncResult result)
{
var self = (TlsHandler)result.AsyncState;
TaskCompletionSource<int> tcs = self.sslStreamWriteQueue.Dequeue();
try
{
self.sslStream.EndWrite(result);
tcs.TrySetResult(0);
}
catch (Exception ex)
{
tcs.TrySetException(ex);
}
finally
{
ReferenceCountUtil.SafeRelease(tcs.Task.AsyncState); // releasing buffer
if (self.sslStreamWriteQueue.Count == 0)
{
self.state &= ~State.WriteInProgress;
}
else
{
// post to executor to break the stack (avoiding stack overflow)
self.capturedContext.Channel.EventLoop.Execute(WriteFromQueueAction, self);
// todo: evaluate if separate path for sync completion makes sense
}
}
}
public override Task CloseAsync(IChannelHandlerContext context)
{
this.sslStream.Close();
return base.CloseAsync(context);
}
void HandleFailure(Exception cause)
{
// Release all resources such as internal buffers that SSLEngine
// is managing.
try
{
this.sslStream.Close();
}
catch (Exception ex)
{
// todo: evaluate following:
// only log in debug mode as it most likely harmless and latest chrome still trigger
// this all the time.
//
// See https://github.com/netty/netty/issues/1340
//string msg = ex.Message;
//if (msg == null || !msg.contains("possible truncation attack"))
//{
// logger.debug("{} SSLEngine.closeInbound() raised an exception.", ctx.channel(), e);
//}
}
this.NotifyHandshakeFailure(cause);
this.FailPendingWrites(cause);
}
void NotifyHandshakeFailure(Exception cause)
{
if ((this.state & State.AuthenticationCompleted) == 0)
{
// handshake was not completed yet => TlsHandler react to failure by closing the channel
this.state = (this.state | State.FailedAuthentication) & ~State.Authenticating;
this.capturedContext.FireUserEventTriggered(new TlsHandshakeCompletionEvent(cause));
this.capturedContext.CloseAsync();
}
}
void FailPendingWrites(Exception cause)
{
foreach (TaskCompletionSource<int> pendingWrite in this.sslStreamWriteQueue)
{
pendingWrite.TrySetException(cause);
}
}
[Flags]
enum State
{
Authenticating = 1,
Authenticated = 2,
FailedAuthentication = 4,
ReadRequestedBeforeAuthenticated = 8,
WriteInProgress = 16,
AuthenticationStarted = Authenticating | Authenticated | FailedAuthentication,
AuthenticationCompleted = Authenticated | FailedAuthentication
}
sealed class MediationStream : Stream
{
readonly TlsHandler owner;
IByteBuffer pendingReadBuffer;
readonly SynchronousReadAsyncResult syncReadResult;
TaskCompletionSource<int> readCompletionSource;
AsyncCallback readCallback;
ArraySegment<byte> sslOwnedBuffer;
TaskCompletionSource<int> writeCompletion;
AsyncCallback writeCallback;
static readonly Action<Task, object> WriteCompleteCallback = HandleChannelWriteComplete;
public MediationStream(TlsHandler owner)
{
this.syncReadResult = new SynchronousReadAsyncResult();
this.owner = owner;
}
public void AcceptBytes(IByteBuffer input)
{
TaskCompletionSource<int> tcs = this.readCompletionSource;
if (tcs == null)
{
// there is no pending read operation - keep for future
this.pendingReadBuffer = input;
return;
}
ArraySegment<byte> sslBuffer = this.sslOwnedBuffer;
Contract.Assert(sslBuffer.Array != null);
int readableBytes = input.ReadableBytes;
int length = Math.Min(sslBuffer.Count, readableBytes);
input.ReadBytes(sslBuffer.Array, sslBuffer.Offset, length);
tcs.TrySetResult(length);
if (length < readableBytes)
{
// set buffer for consecutive read to use
this.pendingReadBuffer = input;
}
AsyncCallback callback = this.readCallback;
if (callback != null)
{
callback(tcs.Task);
}
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
IByteBuffer pendingBuf = this.pendingReadBuffer;
if (pendingBuf != null)
{
// we have the bytes available upfront - write out synchronously
int readableBytes = pendingBuf.ReadableBytes;
int length = Math.Min(count, readableBytes);
pendingBuf.ReadBytes(buffer, offset, length);
if (length == readableBytes)
{
// buffer has been read out to the end
this.pendingReadBuffer = null;
}
return this.PrepareSyncReadResult(length, state);
}
// take note of buffer - we will pass bytes in here
this.sslOwnedBuffer = new ArraySegment<byte>(buffer, offset, count);
this.readCompletionSource = new TaskCompletionSource<int>(state);
this.readCallback = callback;
return this.readCompletionSource.Task;
}
public override int EndRead(IAsyncResult asyncResult)
{
SynchronousReadAsyncResult syncResult = this.syncReadResult;
if (ReferenceEquals(asyncResult, syncResult))
{
return syncResult.BytesRead;
}
Contract.Assert(!((Task<int>)asyncResult).IsCanceled);
try
{
return ((Task<int>)asyncResult).Result;
}
catch (AggregateException ex)
{
ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
throw; // unreachable
}
finally
{
this.readCompletionSource = null;
this.readCallback = null;
this.sslOwnedBuffer = default(ArraySegment<byte>);
}
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
var tcs = new TaskCompletionSource<int>(state);
this.writeCompletion = tcs;
this.writeCallback = callback;
this.owner.capturedContext.WriteAndFlushAsync(Unpooled.WrappedBuffer(buffer, offset, count)) // todo: port PendingWriteQueue to align flushing
.ContinueWith(WriteCompleteCallback, this, TaskContinuationOptions.ExecuteSynchronously);
return tcs.Task;
}
static void HandleChannelWriteComplete(Task completionTask, object state)
{
var self = (MediationStream)state;
switch (completionTask.Status)
{
case TaskStatus.RanToCompletion:
self.writeCompletion.TrySetResult(0);
break;
case TaskStatus.Canceled:
self.writeCompletion.TrySetCanceled();
break;
case TaskStatus.Faulted:
// ReSharper disable once AssignNullToNotNullAttribute -- Exception property cannot be null when task is in Faulted state
self.writeCompletion.TrySetException(completionTask.Exception);
break;
default:
throw new ArgumentOutOfRangeException("Unexpected task status: " + completionTask.Status);
}
if (self.writeCallback != null)
{
self.writeCallback(self.writeCompletion.Task);
}
}
public override void EndWrite(IAsyncResult asyncResult)
{
try
{
((Task<int>)asyncResult).Wait();
}
catch (AggregateException ex)
{
ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
throw;
}
finally
{
this.writeCompletion = null;
this.writeCallback = null;
}
}
IAsyncResult PrepareSyncReadResult(int readBytes, object state)
{
// it is safe to reuse sync result object as it can't lead to leak (no way to attach to it via handle)
SynchronousReadAsyncResult result = this.syncReadResult;
result.BytesRead = readBytes;
result.AsyncState = state;
return result;
}
public override void Flush()
{
// NOOP: called on SslStream.Close
}
#region plumbing
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
public override void SetLength(long value)
{
throw new NotSupportedException();
}
public override int Read(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
public override bool CanRead
{
get { return true; }
}
public override bool CanSeek
{
get { return false; }
}
public override bool CanWrite
{
get { return true; }
}
public override long Length
{
get { throw new NotSupportedException(); }
}
public override long Position
{
get { throw new NotSupportedException(); }
set { throw new NotSupportedException(); }
}
#endregion
#region sync result
sealed class SynchronousReadAsyncResult : IAsyncResult
{
public int BytesRead { get; set; }
public bool IsCompleted
{
get { return true; }
}
public WaitHandle AsyncWaitHandle
{
get { throw new InvalidOperationException("Cannot wait on a synchronous result."); }
}
public object AsyncState { get; set; }
public bool CompletedSynchronously
{
get { return true; }
}
}
#endregion
}
}
}
| |
/***************************************************************************************************************************************
* Copyright (C) 2001-2012 LearnLift USA *
* Contact: Learnlift USA, 12 Greenway Plaza, Suite 1510, Houston, Texas 77046, [email protected] *
* *
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License *
* as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty *
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License along with this library; if not, *
* write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
***************************************************************************************************************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using MLifter.DAL.Interfaces;
namespace MLifter.Controls
{
public partial class LearnModes : UserControl
{
public LearnModes()
{
InitializeComponent();
UpdateCaptions();
numericUpDownNumberOfChoices_ValueChanged(numericUpDownNumberOfChoices, new EventArgs());
}
/// <summary>
/// Gets or sets a value indicating whether [multiple directions] should be possible.
/// </summary>
/// <value><c>true</c> if [multiple directions]; otherwise, <c>false</c>.</value>
/// <remarks>Documented by Dev02, 2008-01-09</remarks>
public bool MultipleDirections
{
get
{
return RBDirectionQuestionAnswer.Appearance == RadioCheckbox.RadioCheckBoxAppearance.Checkbox;
}
set
{
RBDirectionAnswerQuestion.Appearance = RBDirectionMixed.Appearance = RBDirectionQuestionAnswer.Appearance =
(value ? RadioCheckbox.RadioCheckBoxAppearance.Checkbox : RadioCheckbox.RadioCheckBoxAppearance.Radiobutton);
}
}
/// <summary>
/// Gets or sets a value indicating whether [editable controls enabled].
/// </summary>
/// <remarks>Documented by Dev08, 2009-04-28</remarks>
[Browsable(false)]
public bool EditableControlsEnabled
{
get
{
return RBDirectionQuestionAnswer.Enabled;
}
set
{
RBDirectionQuestionAnswer.Enabled = value;
RBDirectionAnswerQuestion.Enabled = value;
RBDirectionMixed.Enabled = value;
LModeStandard.Enabled = value;
LModeSentences.Enabled = value;
LModeMultipleChoice.Enabled = value;
LModeListeningComprehension.Enabled = value;
LModeImageRecognition.Enabled = value;
}
}
#region Question/Answer captions
private string questionCaption = Properties.Resources.NEWDIC_QUESTION;
private string answerCaption = Properties.Resources.NEWDIC_ANSWER;
/// <summary>
/// Gets or sets the question caption.
/// </summary>
/// <value>The question caption.</value>
/// <remarks>Documented by Dev02, 2008-01-09</remarks>
public string QuestionCaption
{
get { return questionCaption; }
set { questionCaption = value; UpdateCaptions(); }
}
/// <summary>
/// Gets or sets the answer caption.
/// </summary>
/// <value>The answer caption.</value>
/// <remarks>Documented by Dev02, 2008-01-09</remarks>
public string AnswerCaption
{
get { return answerCaption; }
set { answerCaption = value; UpdateCaptions(); }
}
/// <summary>
/// Updates the captions.
/// </summary>
/// <remarks>Documented by Dev02, 2008-01-09</remarks>
private void UpdateCaptions()
{
if (string.IsNullOrEmpty(answerCaption) || string.IsNullOrEmpty(questionCaption))
return;
RBDirectionQuestionAnswer.Text = string.Format(Properties.Resources.LEARN_OPTIONS_DIRECTION_FORMAT, questionCaption, answerCaption);
RBDirectionAnswerQuestion.Text = string.Format(Properties.Resources.LEARN_OPTIONS_DIRECTION_FORMAT, answerCaption, questionCaption);
}
#endregion
#region QueryTypes
/// <summary>
/// Sets the type of the query.
/// </summary>
/// <param name="queryType">Type of the query.</param>
/// <remarks>Documented by Dev02, 2008-01-09</remarks>
public void SetQueryTypes(IQueryType queryType)
{
if (LModeStandard.Enabled)
LModeStandard.Checked = queryType.Word.GetValueOrDefault();
if (LModeMultipleChoice.Enabled)
LModeMultipleChoice.Checked = queryType.MultipleChoice.GetValueOrDefault();
if (LModeSentences.Enabled)
LModeSentences.Checked = queryType.Sentence.GetValueOrDefault();
if (LModeListeningComprehension.Enabled)
LModeListeningComprehension.Checked = queryType.ListeningComprehension.GetValueOrDefault();
if (LModeImageRecognition.Enabled)
LModeImageRecognition.Checked = queryType.ImageRecognition.GetValueOrDefault();
}
/// <summary>
/// Gets the type of the query.
/// </summary>
/// <param name="queryType">Type of the query.</param>
/// <remarks>Documented by Dev02, 2008-01-09</remarks>
public void GetQueryTypes(ref IQueryType queryType)
{
queryType.Word = LModeStandard.Checked;
queryType.MultipleChoice = LModeMultipleChoice.Checked;
queryType.Sentence = LModeSentences.Checked;
queryType.ListeningComprehension = LModeListeningComprehension.Checked;
queryType.ImageRecognition = LModeImageRecognition.Checked;
}
/// <summary>
/// Sets the allowed query types.
/// </summary>
/// <param name="queryType">Type of the query.</param>
/// <remarks>Documented by Dev02, 2008-01-09</remarks>
public void SetAllowedQueryTypes(IQueryType queryType)
{
if (!(LModeStandard.Enabled = queryType.Word.Value))
LModeStandard.Checked = false;
if (!(LModeMultipleChoice.Enabled = queryType.MultipleChoice.Value))
LModeMultipleChoice.Checked = false;
if (!(LModeSentences.Enabled = queryType.Sentence.Value))
LModeSentences.Checked = false;
if (!(LModeListeningComprehension.Enabled = queryType.ListeningComprehension.Value))
LModeListeningComprehension.Checked = false;
if (!(LModeImageRecognition.Enabled = queryType.ImageRecognition.Value))
LModeImageRecognition.Checked = false;
}
#endregion
#region QueryDirections
/// <summary>
/// Sets the query directions.
/// </summary>
/// <param name="queryDirections">The query directions.</param>
/// <remarks>Documented by Dev02, 2008-01-09</remarks>
public void SetQueryDirections(IQueryDirections queryDirections)
{
if (RBDirectionQuestionAnswer.Enabled)
RBDirectionQuestionAnswer.Checked = queryDirections.Question2Answer.GetValueOrDefault();
if (RBDirectionAnswerQuestion.Enabled)
RBDirectionAnswerQuestion.Checked = queryDirections.Answer2Question.GetValueOrDefault();
if (RBDirectionMixed.Enabled)
RBDirectionMixed.Checked = queryDirections.Mixed.GetValueOrDefault();
}
/// <summary>
/// Sets the allowed query directions.
/// </summary>
/// <param name="queryDirections">The query directions.</param>
/// <remarks>Documented by Dev02, 2008-01-09</remarks>
public void SetAllowedQueryDirections(IQueryDirections queryDirections)
{
if (!(RBDirectionQuestionAnswer.Enabled = queryDirections.Question2Answer.GetValueOrDefault()))
RBDirectionQuestionAnswer.Checked = false;
if (!(RBDirectionAnswerQuestion.Enabled = queryDirections.Answer2Question.GetValueOrDefault()))
RBDirectionAnswerQuestion.Checked = false;
if (!(RBDirectionMixed.Enabled = queryDirections.Mixed.GetValueOrDefault()))
RBDirectionMixed.Checked = false;
}
/// <summary>
/// Gets the query directions.
/// </summary>
/// <param name="queryDirections">The query directions.</param>
/// <remarks>Documented by Dev02, 2008-01-09</remarks>
public void GetQueryDirections(ref IQueryDirections queryDirections)
{
queryDirections.Question2Answer = RBDirectionQuestionAnswer.Checked;
queryDirections.Answer2Question = RBDirectionAnswerQuestion.Checked;
queryDirections.Mixed = RBDirectionMixed.Checked;
}
///// <summary>
///// Handles the CheckedChanged event of the RBDirection control.
///// </summary>
///// <param name="sender">The source of the event.</param>
///// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
///// <remarks>Documented by Dev02, 2008-01-09</remarks>
//private void RBDirection_CheckedChanged(object sender, EventArgs e)
//{
// if (!multipleDirections && sender is CheckBox)
// {
// //set multipleDirections so that the event handler does not call itself again
// multipleDirections = true;
// RBDirectionQuestionAnswer.Checked = false;
// RBDirectionAnswerQuestion.Checked = false;
// RBDirectionMixed.Checked = false;
// if ((sender as CheckBox).Enabled)
// (sender as CheckBox).Checked = true;
// multipleDirections = false;
// }
//}
/// <summary>
/// Gets or sets the query direction.
/// </summary>
/// <value>The query direction.</value>
/// <remarks>Documented by Dev02, 2008-01-09</remarks>
public EQueryDirection QueryDirection
{
get
{
if (RBDirectionQuestionAnswer.Checked)
return EQueryDirection.Question2Answer;
if (RBDirectionAnswerQuestion.Checked)
return EQueryDirection.Answer2Question;
if (RBDirectionMixed.Checked)
return EQueryDirection.Mixed;
return EQueryDirection.Question2Answer;
}
set
{
switch (value)
{
case EQueryDirection.Question2Answer:
RBDirectionQuestionAnswer.Checked = true;
break;
case EQueryDirection.Answer2Question:
RBDirectionAnswerQuestion.Checked = true;
break;
case EQueryDirection.Mixed:
RBDirectionMixed.Checked = true;
break;
default:
break;
}
}
}
#endregion
#region QueryMultipleChoice
/// <summary>
/// Sets the query multiple choice options.
/// </summary>
/// <param name="multipleChoiceOptions">The multiple choice options.</param>
/// <remarks>Documented by Dev02, 2008-01-11</remarks>
public void SetQueryMultipleChoiceOptions(IQueryMultipleChoiceOptions multipleChoiceOptions)
{
if (checkBoxAllowRandomDistractors.Enabled)
checkBoxAllowRandomDistractors.Checked = multipleChoiceOptions.AllowRandomDistractors.GetValueOrDefault();
if (checkBoxAllowMultipleCorrectAnswers.Enabled)
checkBoxAllowMultipleCorrectAnswers.Checked = multipleChoiceOptions.AllowMultipleCorrectAnswers.GetValueOrDefault();
if (numericUpDownNumberOfChoices.Enabled && multipleChoiceOptions.NumberOfChoices > 0)
numericUpDownNumberOfChoices.Value = multipleChoiceOptions.NumberOfChoices.GetValueOrDefault();
if (numericUpDownMaxNumberOfCorrectAnswers.Enabled && multipleChoiceOptions.MaxNumberOfCorrectAnswers > 0)
numericUpDownMaxNumberOfCorrectAnswers.Value = multipleChoiceOptions.MaxNumberOfCorrectAnswers.GetValueOrDefault();
}
/// <summary>
/// Gets the query multiple choice options.
/// </summary>
/// <param name="multipleChoiceOptions">The multiple choice options.</param>
/// <remarks>Documented by Dev02, 2008-01-11</remarks>
public void GetQueryMultipleChoiceOptions(ref IQueryMultipleChoiceOptions multipleChoiceOptions)
{
multipleChoiceOptions.AllowRandomDistractors = checkBoxAllowRandomDistractors.Checked;
multipleChoiceOptions.AllowMultipleCorrectAnswers = checkBoxAllowMultipleCorrectAnswers.Checked;
multipleChoiceOptions.NumberOfChoices = Convert.ToInt32(numericUpDownNumberOfChoices.Value);
multipleChoiceOptions.MaxNumberOfCorrectAnswers = Convert.ToInt32(numericUpDownMaxNumberOfCorrectAnswers.Value);
}
/// <summary>
/// Gets or sets a value indicating whether [multiple choice options visible].
/// </summary>
/// <value>
/// <c>true</c> if [multiple choice options visible]; otherwise, <c>false</c>.
/// </value>
/// <remarks>Documented by Dev02, 2008-01-11</remarks>
public bool MultipleChoiceOptionsVisible
{
get { return groupBoxMultipleChoice.Visible; }
set { groupBoxMultipleChoice.Visible = value; }
}
/// <summary>
/// Handles the ValueChanged event of the numericUpDownNumberOfChoices control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
/// <remarks>Documented by Dev02, 2008-01-11</remarks>
private void numericUpDownNumberOfChoices_ValueChanged(object sender, EventArgs e)
{
numericUpDownMaxNumberOfCorrectAnswers.Value = Math.Min(numericUpDownMaxNumberOfCorrectAnswers.Value, numericUpDownNumberOfChoices.Value);
numericUpDownMaxNumberOfCorrectAnswers.Maximum = numericUpDownNumberOfChoices.Value;
}
#endregion
/// <summary>
/// Validates the input and displays a messagebox if invalid.
/// </summary>
/// <returns>True, when input is valid, else false.</returns>
/// <remarks>Documented by Dev02, 2008-01-09</remarks>
public bool ValidateInput()
{
if ((!LModeStandard.Checked && !LModeMultipleChoice.Checked && !LModeSentences.Checked && !LModeListeningComprehension.Checked && !LModeImageRecognition.Checked)
|| (!RBDirectionQuestionAnswer.Checked && !RBDirectionAnswerQuestion.Checked && !RBDirectionMixed.Checked))
{
MessageBox.Show(MLifter.Controls.Properties.Resources.LEARN_OPTIONS_NO_MODE_TEXT, MLifter.Controls.Properties.Resources.LEARN_OPTIONS_NO_MODE_CAPTION,
MessageBoxButtons.OK, MessageBoxIcon.Warning);
return false;
}
return true;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using GitVersion.Extensions;
using GitVersion.Logging;
using GitVersion.Model;
using GitVersion.Model.Configuration;
using GitVersion.OutputVariables;
namespace GitVersion
{
public class ArgumentParser : IArgumentParser
{
private readonly IEnvironment environment;
private readonly ICurrentBuildAgent buildAgent;
private readonly IConsole console;
private readonly IGlobbingResolver globbingResolver;
private const string defaultOutputFileName = "GitVersion.json";
public ArgumentParser(IEnvironment environment, ICurrentBuildAgent buildAgent, IConsole console, IGlobbingResolver globbingResolver)
{
this.environment = environment ?? throw new ArgumentNullException(nameof(environment));
this.console = console ?? throw new ArgumentNullException(nameof(console));
this.globbingResolver = globbingResolver ?? throw new ArgumentNullException(nameof(globbingResolver));
this.buildAgent = buildAgent;
}
public Arguments ParseArguments(string commandLineArguments)
{
var arguments = commandLineArguments
.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.ToArray();
return ParseArguments(arguments);
}
public Arguments ParseArguments(string[] commandLineArguments)
{
if (commandLineArguments.Length == 0)
{
var args = new Arguments
{
TargetPath = System.Environment.CurrentDirectory,
};
args.Output.Add(OutputType.Json);
return args;
}
var firstArgument = commandLineArguments.First();
if (firstArgument.IsInit())
{
return new Arguments
{
TargetPath = System.Environment.CurrentDirectory,
Init = true,
};
}
if (firstArgument.IsHelp())
{
return new Arguments
{
IsHelp = true,
};
}
if (firstArgument.IsSwitch("version"))
{
return new Arguments
{
IsVersion = true,
};
}
var arguments = new Arguments();
AddAuthentication(arguments);
var switchesAndValues = CollectSwitchesAndValuesFromArguments(commandLineArguments, out var firstArgumentIsSwitch);
for (var i = 0; i < switchesAndValues.AllKeys.Length; i++)
{
ParseSwitchArguments(arguments, switchesAndValues, i);
}
if (arguments.Output.Count == 0)
{
arguments.Output.Add(OutputType.Json);
}
if (arguments.Output.Contains(OutputType.File) && arguments.OutputFile == null)
{
arguments.OutputFile = defaultOutputFileName;
}
// If the first argument is a switch, it should already have been consumed in the above loop,
// or else a WarningException should have been thrown and we wouldn't end up here.
arguments.TargetPath ??= firstArgumentIsSwitch
? System.Environment.CurrentDirectory
: firstArgument;
arguments.TargetPath = arguments.TargetPath.TrimEnd('/', '\\');
arguments.UpdateAssemblyInfoFileName = ResolveFiles(arguments.TargetPath, arguments.UpdateAssemblyInfoFileName).ToHashSet();
arguments.NoFetch = arguments.NoFetch || buildAgent != null && buildAgent.PreventFetch();
return arguments;
}
private void ParseSwitchArguments(Arguments arguments, NameValueCollection switchesAndValues, int i)
{
var name = switchesAndValues.AllKeys[i];
var values = switchesAndValues.GetValues(name);
var value = values?.FirstOrDefault();
if (ParseSwitches(arguments, name, values, value)) return;
ParseTargetPath(arguments, name, values, value, i == 0);
}
private void AddAuthentication(Arguments arguments)
{
var username = environment.GetEnvironmentVariable("GITVERSION_REMOTE_USERNAME");
if (!string.IsNullOrWhiteSpace(username))
{
arguments.Authentication.Username = username;
}
var password = environment.GetEnvironmentVariable("GITVERSION_REMOTE_PASSWORD");
if (!string.IsNullOrWhiteSpace(password))
{
arguments.Authentication.Username = password;
}
}
private IEnumerable<string> ResolveFiles(string workingDirectory, ISet<string> assemblyInfoFiles)
{
if (assemblyInfoFiles == null) yield break;
foreach (var file in assemblyInfoFiles)
{
var paths = globbingResolver.Resolve(workingDirectory, file);
foreach (var path in paths)
{
yield return Path.GetFullPath(Path.Combine(workingDirectory, path));
}
}
}
private void ParseTargetPath(Arguments arguments, string name, string[] values, string value, bool parseEnded)
{
if (name.IsSwitch("targetpath"))
{
EnsureArgumentValueCount(values);
arguments.TargetPath = value;
if (!Directory.Exists(value))
{
console.WriteLine($"The working directory '{value}' does not exist.");
}
return;
}
var couldNotParseMessage = $"Could not parse command line parameter '{name}'.";
// If we've reached through all argument switches without a match, we can relatively safely assume that the first argument isn't a switch, but the target path.
if (parseEnded)
{
if (name.StartsWith("/"))
{
if (Path.DirectorySeparatorChar == '/' && name.IsValidPath())
{
arguments.TargetPath = name;
return;
}
}
else if (!name.IsSwitchArgument())
{
arguments.TargetPath = name;
return;
}
couldNotParseMessage += " If it is the target path, make sure it exists.";
}
throw new WarningException(couldNotParseMessage);
}
private static bool ParseSwitches(Arguments arguments, string name, string[] values, string value)
{
if (name.IsSwitch("l"))
{
EnsureArgumentValueCount(values);
arguments.LogFilePath = value;
return true;
}
if (ParseConfigArguments(arguments, name, values, value)) return true;
if (ParseRemoteArguments(arguments, name, values, value)) return true;
if (ParseExecArguments(arguments, name, values, value)) return true;
if (name.IsSwitch("updateAssemblyInfo"))
{
ParseUpdateAssemblyInfo(arguments, value, values);
return true;
}
if (name.IsSwitch("ensureassemblyinfo"))
{
ParseEnsureAssemblyInfo(arguments, value);
return true;
}
if (name.IsSwitch("v") || name.IsSwitch("showvariable"))
{
ParseShowVariable(arguments, value, name);
return true;
}
if (name.IsSwitch("output"))
{
ParseOutput(arguments, values);
return true;
}
if (name.IsSwitch("outputfile"))
{
EnsureArgumentValueCount(values);
arguments.OutputFile = value;
return true;
}
if (name.IsSwitch("nofetch"))
{
arguments.NoFetch = true;
return true;
}
if (name.IsSwitch("nonormalize"))
{
arguments.NoNormalize = true;
return true;
}
if (name.IsSwitch("nocache"))
{
arguments.NoCache = true;
return true;
}
if (name.IsSwitch("verbosity"))
{
ParseVerbosity(arguments, value);
return true;
}
if (name.IsSwitch("updatewixversionfile"))
{
arguments.UpdateWixVersionFile = true;
return true;
}
return false;
}
private static bool ParseConfigArguments(Arguments arguments, string name, string[] values, string value)
{
if (name.IsSwitch("config"))
{
EnsureArgumentValueCount(values);
arguments.ConfigFile = value;
return true;
}
if (name.IsSwitch("overrideconfig"))
{
ParseOverrideConfig(arguments, value);
return true;
}
if (name.IsSwitch("showConfig"))
{
arguments.ShowConfig = value.IsTrue() || !value.IsFalse();
return true;
}
return false;
}
private static bool ParseExecArguments(Arguments arguments, string name, string[] values, string value)
{
if (name.IsSwitch("exec"))
{
EnsureArgumentValueCount(values);
#pragma warning disable CS0612 // Type or member is obsolete
arguments.Exec = value;
#pragma warning restore CS0612 // Type or member is obsolete
return true;
}
if (name.IsSwitch("execargs"))
{
EnsureArgumentValueCount(values);
#pragma warning disable CS0612 // Type or member is obsolete
arguments.ExecArgs = value;
#pragma warning restore CS0612 // Type or member is obsolete
return true;
}
if (name.IsSwitch("proj"))
{
EnsureArgumentValueCount(values);
#pragma warning disable CS0612 // Type or member is obsolete
arguments.Proj = value;
#pragma warning restore CS0612 // Type or member is obsolete
return true;
}
if (name.IsSwitch("projargs"))
{
EnsureArgumentValueCount(values);
#pragma warning disable CS0612 // Type or member is obsolete
arguments.ProjArgs = value;
#pragma warning restore CS0612 // Type or member is obsolete
return true;
}
if (name.IsSwitch("diag"))
{
if (value == null || value.IsTrue())
{
arguments.Diag = true;
}
return true;
}
return false;
}
private static bool ParseRemoteArguments(Arguments arguments, string name, string[] values, string value)
{
if (name.IsSwitch("dynamicRepoLocation"))
{
EnsureArgumentValueCount(values);
arguments.DynamicRepositoryClonePath = value;
return true;
}
if (name.IsSwitch("url"))
{
EnsureArgumentValueCount(values);
arguments.TargetUrl = value;
return true;
}
if (name.IsSwitch("u"))
{
EnsureArgumentValueCount(values);
arguments.Authentication.Username = value;
return true;
}
if (name.IsSwitch("p"))
{
EnsureArgumentValueCount(values);
arguments.Authentication.Password = value;
return true;
}
if (name.IsSwitch("c"))
{
EnsureArgumentValueCount(values);
arguments.CommitId = value;
return true;
}
if (name.IsSwitch("b"))
{
EnsureArgumentValueCount(values);
arguments.TargetBranch = value;
return true;
}
return false;
}
private static void ParseShowVariable(Arguments arguments, string value, string name)
{
string versionVariable = null;
if (!string.IsNullOrWhiteSpace(value))
{
versionVariable = VersionVariables.AvailableVariables.SingleOrDefault(av => av.Equals(value.Replace("'", ""), StringComparison.CurrentCultureIgnoreCase));
}
if (versionVariable == null)
{
var message = $"{name} requires a valid version variable. Available variables are:{System.Environment.NewLine}" +
string.Join(", ", VersionVariables.AvailableVariables.Select(x => string.Concat("'", x, "'")));
throw new WarningException(message);
}
arguments.ShowVariable = versionVariable;
}
private static void ParseEnsureAssemblyInfo(Arguments arguments, string value)
{
arguments.EnsureAssemblyInfo = true;
if (value.IsFalse())
{
arguments.EnsureAssemblyInfo = false;
}
if (arguments.UpdateAssemblyInfoFileName.Count > 1 && arguments.EnsureAssemblyInfo)
{
throw new WarningException("Can't specify multiple assembly info files when using /ensureassemblyinfo switch, either use a single assembly info file or do not specify /ensureassemblyinfo and create assembly info files manually");
}
}
private static void ParseOutput(Arguments arguments, string[] values)
{
foreach (var v in values)
{
if (!Enum.TryParse(v, true, out OutputType outputType))
{
throw new WarningException($"Value '{v}' cannot be parsed as output type, please use 'json', 'file' or 'buildserver'");
}
arguments.Output.Add(outputType);
}
}
private static void ParseVerbosity(Arguments arguments, string value)
{
// first try the old version, this check will be removed in version 6.0.0, making it a breaking change
if (Enum.TryParse(value, true, out LogLevel logLevel))
{
arguments.Verbosity = LogExtensions.GetVerbosityForLevel(logLevel);
}
else if (!Enum.TryParse(value, true, out arguments.Verbosity))
{
throw new WarningException($"Could not parse Verbosity value '{value}'");
}
}
private static void ParseOverrideConfig(Arguments arguments, string value)
{
var keyValueOptions = (value ?? "").Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
if (keyValueOptions.Length == 0)
{
return;
}
arguments.OverrideConfig = new Config();
if (keyValueOptions.Length > 1)
{
throw new WarningException("Can't specify multiple /overrideconfig options: currently supported only 'tag-prefix' option");
}
// key=value
foreach (var keyValueOption in keyValueOptions)
{
var keyAndValue = keyValueOption.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
if (keyAndValue.Length != 2)
{
throw new WarningException($"Could not parse /overrideconfig option: {keyValueOption}. Ensure it is in format 'key=value'");
}
var optionKey = keyAndValue[0].ToLowerInvariant();
arguments.OverrideConfig.TagPrefix = optionKey switch
{
"tag-prefix" => keyAndValue[1],
_ => throw new WarningException($"Could not parse /overrideconfig option: {optionKey}. Currently supported only 'tag-prefix' option")
};
}
}
private static void ParseUpdateAssemblyInfo(Arguments arguments, string value, string[] values)
{
if (value.IsTrue())
{
arguments.UpdateAssemblyInfo = true;
}
else if (value.IsFalse())
{
arguments.UpdateAssemblyInfo = false;
}
else if (values != null && values.Length > 1)
{
arguments.UpdateAssemblyInfo = true;
foreach (var v in values)
{
arguments.UpdateAssemblyInfoFileName.Add(v);
}
}
else if (!value.IsSwitchArgument())
{
arguments.UpdateAssemblyInfo = true;
if (value != null)
{
arguments.UpdateAssemblyInfoFileName.Add(value);
}
}
else
{
arguments.UpdateAssemblyInfo = true;
}
if (arguments.UpdateAssemblyInfoFileName.Count > 1 && arguments.EnsureAssemblyInfo)
{
throw new WarningException("Can't specify multiple assembly info files when using -ensureassemblyinfo switch, either use a single assembly info file or do not specify -ensureassemblyinfo and create assembly info files manually");
}
}
private static void EnsureArgumentValueCount(IReadOnlyList<string> values)
{
if (values != null && values.Count > 1)
{
throw new WarningException($"Could not parse command line parameter '{values[1]}'.");
}
}
private static NameValueCollection CollectSwitchesAndValuesFromArguments(IList<string> namedArguments, out bool firstArgumentIsSwitch)
{
firstArgumentIsSwitch = true;
var switchesAndValues = new NameValueCollection();
string currentKey = null;
var argumentRequiresValue = false;
for (var i = 0; i < namedArguments.Count; i += 1)
{
var arg = namedArguments[i];
// If the current (previous) argument doesn't require a value parameter and this is a switch, create new name/value entry for it, with a null value.
if (!argumentRequiresValue && arg.IsSwitchArgument())
{
currentKey = arg;
argumentRequiresValue = arg.ArgumentRequiresValue(i);
switchesAndValues.Add(currentKey, null);
}
// If this is a value (not a switch)
else if (currentKey != null)
{
// And if the current switch does not have a value yet and the value is not itself a switch, set its value to this argument.
if (string.IsNullOrEmpty(switchesAndValues[currentKey]))
{
switchesAndValues[currentKey] = arg;
}
// Otherwise add the value under the same switch.
else
{
switchesAndValues.Add(currentKey, arg);
}
// Reset the boolean argument flag so the next argument won't be ignored.
argumentRequiresValue = false;
}
else if (i == 0)
{
firstArgumentIsSwitch = false;
}
}
return switchesAndValues;
}
}
}
| |
/*
* DocuSign REST API
*
* The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
*
* OpenAPI spec version: v2
* Contact: [email protected]
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
namespace DocuSign.eSign.Model
{
/// <summary>
/// Contact
/// </summary>
[DataContract]
public partial class Contact : IEquatable<Contact>, IValidatableObject
{
public Contact()
{
// Empty Constructor
}
/// <summary>
/// Initializes a new instance of the <see cref="Contact" /> class.
/// </summary>
/// <param name="ContactId">.</param>
/// <param name="ContactPhoneNumbers">.</param>
/// <param name="ContactUri">.</param>
/// <param name="Emails">.</param>
/// <param name="ErrorDetails">ErrorDetails.</param>
/// <param name="Name">.</param>
/// <param name="Organization">.</param>
/// <param name="Shared">When set to **true**, this custom tab is shared..</param>
/// <param name="SigningGroup">.</param>
/// <param name="SigningGroupName">The display name for the signing group. Maximum Length: 100 characters. .</param>
public Contact(string ContactId = default(string), List<ContactPhoneNumber> ContactPhoneNumbers = default(List<ContactPhoneNumber>), string ContactUri = default(string), List<string> Emails = default(List<string>), ErrorDetails ErrorDetails = default(ErrorDetails), string Name = default(string), string Organization = default(string), string Shared = default(string), string SigningGroup = default(string), string SigningGroupName = default(string))
{
this.ContactId = ContactId;
this.ContactPhoneNumbers = ContactPhoneNumbers;
this.ContactUri = ContactUri;
this.Emails = Emails;
this.ErrorDetails = ErrorDetails;
this.Name = Name;
this.Organization = Organization;
this.Shared = Shared;
this.SigningGroup = SigningGroup;
this.SigningGroupName = SigningGroupName;
}
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="contactId", EmitDefaultValue=false)]
public string ContactId { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="contactPhoneNumbers", EmitDefaultValue=false)]
public List<ContactPhoneNumber> ContactPhoneNumbers { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="contactUri", EmitDefaultValue=false)]
public string ContactUri { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="emails", EmitDefaultValue=false)]
public List<string> Emails { get; set; }
/// <summary>
/// Gets or Sets ErrorDetails
/// </summary>
[DataMember(Name="errorDetails", EmitDefaultValue=false)]
public ErrorDetails ErrorDetails { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="name", EmitDefaultValue=false)]
public string Name { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="organization", EmitDefaultValue=false)]
public string Organization { get; set; }
/// <summary>
/// When set to **true**, this custom tab is shared.
/// </summary>
/// <value>When set to **true**, this custom tab is shared.</value>
[DataMember(Name="shared", EmitDefaultValue=false)]
public string Shared { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="signingGroup", EmitDefaultValue=false)]
public string SigningGroup { get; set; }
/// <summary>
/// The display name for the signing group. Maximum Length: 100 characters.
/// </summary>
/// <value>The display name for the signing group. Maximum Length: 100 characters. </value>
[DataMember(Name="signingGroupName", EmitDefaultValue=false)]
public string SigningGroupName { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class Contact {\n");
sb.Append(" ContactId: ").Append(ContactId).Append("\n");
sb.Append(" ContactPhoneNumbers: ").Append(ContactPhoneNumbers).Append("\n");
sb.Append(" ContactUri: ").Append(ContactUri).Append("\n");
sb.Append(" Emails: ").Append(Emails).Append("\n");
sb.Append(" ErrorDetails: ").Append(ErrorDetails).Append("\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" Organization: ").Append(Organization).Append("\n");
sb.Append(" Shared: ").Append(Shared).Append("\n");
sb.Append(" SigningGroup: ").Append(SigningGroup).Append("\n");
sb.Append(" SigningGroupName: ").Append(SigningGroupName).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as Contact);
}
/// <summary>
/// Returns true if Contact instances are equal
/// </summary>
/// <param name="other">Instance of Contact to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(Contact other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.ContactId == other.ContactId ||
this.ContactId != null &&
this.ContactId.Equals(other.ContactId)
) &&
(
this.ContactPhoneNumbers == other.ContactPhoneNumbers ||
this.ContactPhoneNumbers != null &&
this.ContactPhoneNumbers.SequenceEqual(other.ContactPhoneNumbers)
) &&
(
this.ContactUri == other.ContactUri ||
this.ContactUri != null &&
this.ContactUri.Equals(other.ContactUri)
) &&
(
this.Emails == other.Emails ||
this.Emails != null &&
this.Emails.SequenceEqual(other.Emails)
) &&
(
this.ErrorDetails == other.ErrorDetails ||
this.ErrorDetails != null &&
this.ErrorDetails.Equals(other.ErrorDetails)
) &&
(
this.Name == other.Name ||
this.Name != null &&
this.Name.Equals(other.Name)
) &&
(
this.Organization == other.Organization ||
this.Organization != null &&
this.Organization.Equals(other.Organization)
) &&
(
this.Shared == other.Shared ||
this.Shared != null &&
this.Shared.Equals(other.Shared)
) &&
(
this.SigningGroup == other.SigningGroup ||
this.SigningGroup != null &&
this.SigningGroup.Equals(other.SigningGroup)
) &&
(
this.SigningGroupName == other.SigningGroupName ||
this.SigningGroupName != null &&
this.SigningGroupName.Equals(other.SigningGroupName)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.ContactId != null)
hash = hash * 59 + this.ContactId.GetHashCode();
if (this.ContactPhoneNumbers != null)
hash = hash * 59 + this.ContactPhoneNumbers.GetHashCode();
if (this.ContactUri != null)
hash = hash * 59 + this.ContactUri.GetHashCode();
if (this.Emails != null)
hash = hash * 59 + this.Emails.GetHashCode();
if (this.ErrorDetails != null)
hash = hash * 59 + this.ErrorDetails.GetHashCode();
if (this.Name != null)
hash = hash * 59 + this.Name.GetHashCode();
if (this.Organization != null)
hash = hash * 59 + this.Organization.GetHashCode();
if (this.Shared != null)
hash = hash * 59 + this.Shared.GetHashCode();
if (this.SigningGroup != null)
hash = hash * 59 + this.SigningGroup.GetHashCode();
if (this.SigningGroupName != null)
hash = hash * 59 + this.SigningGroupName.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
// Copyright (c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy
// of the License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
namespace Microsoft.WindowsAzure.Management.HDInsight.Tests.ClientAbstractionTests
{
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Hadoop.Client;
using Microsoft.Hadoop.Client.Storage;
using Microsoft.Hadoop.Client.WebHCatRest;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.WindowsAzure.Management.Configuration;
using Microsoft.WindowsAzure.Management.HDInsight.ClusterProvisioning;
using Microsoft.WindowsAzure.Management.HDInsight.ClusterProvisioning.AzureManagementClient;
using Microsoft.WindowsAzure.Management.HDInsight.ClusterProvisioning.PocoClient;
using Microsoft.WindowsAzure.Management.HDInsight.Framework;
using Microsoft.WindowsAzure.Management.HDInsight.Framework.Core.Library;
using Microsoft.WindowsAzure.Management.HDInsight.Framework.Core.Library.WebRequest;
using Microsoft.WindowsAzure.Management.HDInsight.Framework.Core.Retries;
using Microsoft.WindowsAzure.Management.HDInsight.Framework.Logging;
using Microsoft.WindowsAzure.Management.HDInsight.Framework.ServiceLocation;
using Microsoft.WindowsAzure.Management.HDInsight;
using Microsoft.WindowsAzure.Management.HDInsight.JobSubmission;
using Microsoft.WindowsAzure.Management.HDInsight.TestUtilities;
using Configuration = Management.Configuration.Data;
[TestClass]
public class PocoClientTests : IntegrationTestBase
{
[TestInitialize]
public override void Initialize()
{
base.Initialize();
}
[TestCleanup]
public override void TestCleanup()
{
base.TestCleanup();
}
internal IRetryPolicy GetRetryPolicy()
{
return RetryPolicyFactory.CreateExponentialRetryPolicy(TimeSpan.FromSeconds(0), TimeSpan.FromSeconds(1), TimeSpan.FromMilliseconds(100), 3, 0.2);
}
[TestMethod]
[TestCategory("Integration")]
[TestCategory("CheckIn")]
[TestCategory("PocoClient")]
public async Task ICanPerformA_ListNonExistingContainer_Using_PocoClientAbstraction()
{
IHDInsightCertificateCredential credentials = IntegrationTestBase.GetValidCredentials();
using (var client = ServiceLocator.Instance.Locate<IHDInsightManagementPocoClientFactory>().Create(credentials, GetAbstractionContext(), false))
{
var result = await client.ListContainer(GetRandomClusterName());
Assert.IsNull(result);
}
}
[TestMethod]
[TestCategory("Integration")]
[TestCategory("CheckIn")]
[TestCategory("PocoClient")]
[ExpectedException(typeof(HDInsightClusterDoesNotExistException))]
public async Task ICanPerformA_DeleteNonExistingContainer_Using_PocoClientAbstraction()
{
IHDInsightCertificateCredential credentials = IntegrationTestBase.GetValidCredentials();
await ServiceLocator.Instance.Locate<IHDInsightManagementPocoClientFactory>()
.Create(credentials, GetAbstractionContext(), false)
.DeleteContainer(GetRandomClusterName());
}
[TestMethod]
[TestCategory("Integration")]
[TestCategory("CheckIn")]
[TestCategory("PocoClient")]
[ExpectedException(typeof(HttpLayerException))]
public async Task ICanPerformA_DeleteNonExistingContainerInternal_Using_PocoClientAbstraction()
{
IHDInsightCertificateCredential credentials = IntegrationTestBase.GetValidCredentials();
await ServiceLocator.Instance.Locate<IHDInsightManagementPocoClientFactory>()
.Create(credentials, GetAbstractionContext(), false)
.DeleteContainer(GetRandomClusterName(), "East US");
}
[TestMethod]
[TestCategory("Integration")]
[TestCategory("CheckIn")]
[TestCategory("PocoClient")]
[ExpectedException(typeof(HttpLayerException))]
public async Task ICanPerformA_DeleteContainerInvalidLocationInternal_Using_PocoClientAbstraction()
{
IHDInsightCertificateCredential credentials = IntegrationTestBase.GetValidCredentials();
await ServiceLocator.Instance.Locate<IHDInsightManagementPocoClientFactory>()
.Create(credentials, GetAbstractionContext(), false)
.DeleteContainer(TestCredentials.WellKnownCluster.DnsName, "Nowhere");
}
[TestMethod]
[TestCategory("Integration")]
[TestCategory("NegativeTest")]
[TestCategory("CheckIn")]
[TestCategory("PocoClient")]
[Timeout(5 * 60 * 1000)] // ms
public async Task ICanNotPerformA_DeleteContainer_WithAnInvalidCertificate_PocoClientAbstraction()
{
var creds = GetInvalidCertificateCredentials();
var clusterName = TestCredentials.WellKnownCluster.DnsName;
try
{
using (var client = ServiceLocator.Instance.Locate<IHDInsightManagementPocoClientFactory>().Create(creds, GetAbstractionContext(), false))
{
await client.DeleteContainer(clusterName);
}
Assert.Fail("This call was expected to receive a failure, but did not.");
}
catch (HttpLayerException ex)
{
Assert.IsTrue(ex.RequestStatusCode == HttpStatusCode.Forbidden);
}
}
[TestMethod]
[TestCategory("Integration")]
[TestCategory("NegativeTest")]
[TestCategory("CheckIn")]
[TestCategory("PocoClient")]
[Timeout(5 * 60 * 1000)] // ms
public async Task ICanNotPerformA_GetContainer_WithAnInvalidCertificate_PocoClientAbstraction()
{
var creds = GetInvalidCertificateCredentials();
var clusterName = TestCredentials.WellKnownCluster.DnsName;
try
{
using (var client = ServiceLocator.Instance.Locate<IHDInsightManagementPocoClientFactory>().Create(creds, GetAbstractionContext(), false))
{
await client.ListContainer(clusterName);
}
Assert.Fail("This call was expected to receive a failure, but did not.");
}
catch (HttpLayerException ex)
{
Assert.IsTrue(ex.RequestStatusCode == HttpStatusCode.Forbidden);
}
}
[TestMethod]
[TestCategory("Integration")]
[TestCategory("NegativeTest")]
[TestCategory("CheckIn")]
[TestCategory("PocoClient")]
[Timeout(5*60*1000)] // ms
public async Task ICanNotPerformA_CreateCreateContainer_WithAnInvalidCertificate_PocoClientAbstraction()
{
var creds = GetInvalidCertificateCredentials();
var cluster = GetRandomCluster();
try
{
using (
var client = ServiceLocator.Instance.Locate<IHDInsightManagementPocoClientFactory>()
.Create(creds, GetAbstractionContext(), false))
{
await client.CreateContainer(cluster);
}
Assert.Fail("This call was expected to receive a failure, but did not.");
}
catch (HttpLayerException ex)
{
Assert.IsTrue(ex.RequestStatusCode == HttpStatusCode.Forbidden);
}
}
[TestMethod]
[TestCategory("Integration")]
[TestCategory("NegativeTest")]
[TestCategory("CheckIn")]
[TestCategory("PocoClient")]
[Timeout(5 * 60 * 1000)] // ms
public async Task ICanNotPerformA_DeleteContainer_WithAnInvalidSubscriptionId_PocoClientAbstraction()
{
var creds = GetInvalidSubscriptionIdCredentials();
var clusterName = TestCredentials.WellKnownCluster.DnsName;
try
{
using (var client = ServiceLocator.Instance.Locate<IHDInsightManagementPocoClientFactory>().Create(creds, GetAbstractionContext(), false))
{
await client.DeleteContainer(clusterName);
}
Assert.Fail("This call was expected to receive a failure, but did not.");
}
catch (HttpLayerException ex)
{
Assert.IsTrue(ex.RequestStatusCode == HttpStatusCode.Forbidden);
}
}
[TestMethod]
[TestCategory("Integration")]
[TestCategory("NegativeTest")]
[TestCategory("CheckIn")]
[TestCategory("PocoClient")]
[Timeout(5 * 60 * 1000)] // ms
public async Task ICanNotPerformA_GetContainer_WithAnInvalidSubscriptionId_PocoClientAbstraction()
{
var creds = GetInvalidSubscriptionIdCredentials();
var clusterName = TestCredentials.WellKnownCluster.DnsName;
try
{
using (var client = ServiceLocator.Instance.Locate<IHDInsightManagementPocoClientFactory>().Create(creds, GetAbstractionContext(), false))
{
await client.ListContainer(clusterName);
}
Assert.Fail("This call was expected to receive a failure, but did not.");
}
catch (HttpLayerException ex)
{
Assert.IsTrue(ex.RequestStatusCode == HttpStatusCode.Forbidden);
}
}
[TestMethod]
[TestCategory("Integration")]
[TestCategory("NegativeTest")]
[TestCategory("CheckIn")]
[TestCategory("PocoClient")]
[Timeout(5 * 60 * 1000)] // ms
public async Task ICanNotPerformA_CreateCreateContainer_WithAnInvalidSubscriptionId_PocoClientAbstraction()
{
var creds = GetInvalidSubscriptionIdCredentials();
var cluster = GetRandomCluster();
try
{
using (var client = ServiceLocator.Instance.Locate<IHDInsightManagementPocoClientFactory>().Create(creds, GetAbstractionContext(), false))
{
await client.CreateContainer(cluster);
}
Assert.Fail("This call was expected to receive a failure, but did not.");
}
catch (HttpLayerException ex)
{
Assert.IsTrue(ex.RequestStatusCode == HttpStatusCode.Forbidden);
}
}
[TestMethod]
[TestCategory("Integration")]
[TestCategory("CheckIn")]
[TestCategory("PocoClient")]
[Timeout(5 * 60 * 1000)] // ms
public async Task ICanPerformA_BasicCreateDeleteContainers_Using_PocoClientAbstraction()
{
var cluster = GetRandomCluster();
await ValidateCreateClusterSucceeds(cluster);
}
[TestMethod]
[TestCategory("Integration")]
[TestCategory("CheckIn")]
[TestCategory("PocoClient")]
[TestCategory("RestAsvClient")]
[Timeout(5 * 60 * 1000)] // ms
public async Task ICanPerformA_BasicCreateDeleteContainersOnUnregisteredLocation_Using_PocoClient()
{
// ADD SUBSCRIPTION VALIDATOR
IHDInsightCertificateCredential credentials = IntegrationTestBase.GetValidCredentials();
// Unregisters subscription (just in case)
var location = "North Europe";
var registrationClient = ServiceLocator.Instance.Locate<ISubscriptionRegistrationClientFactory>().Create(credentials, GetAbstractionContext(), false);
if (await registrationClient.ValidateSubscriptionLocation(location))
{
await registrationClient.UnregisterSubscriptionLocation(location);
}
var storageAccountsInLocation = from creationDetails in IntegrationTestBase.TestCredentials.Environments
where creationDetails.Location == location
select creationDetails;
var storageAccount = storageAccountsInLocation.FirstOrDefault();
Assert.IsNotNull(storageAccount, "could not find any storage accounts in location {0}", location);
var cluster = GetRandomCluster();
cluster.Location = location;
cluster.DefaultStorageAccountName = storageAccount.DefaultStorageAccount.Name;
cluster.DefaultStorageAccountKey = storageAccount.DefaultStorageAccount.Key;
cluster.DefaultStorageContainer = storageAccount.DefaultStorageAccount.Container;
await ValidateCreateClusterSucceeds(cluster);
}
[TestMethod]
[TestCategory("Integration")]
[TestCategory("CheckIn")]
[TestCategory("PocoClient")]
[Timeout(5 * 60 * 1000)] // ms
public async Task ICanPerformA_AdvancedCreateDeleteContainers_Using_PocoClient()
{
var cluster = GetRandomCluster();
cluster.AdditionalStorageAccounts.Add(new WabStorageAccountConfiguration(TestCredentials.Environments[0].AdditionalStorageAccounts[0].Name,
TestCredentials.Environments[0].AdditionalStorageAccounts[0].Key));
cluster.OozieMetastore = new Metastore(TestCredentials.Environments[0].OozieStores[0].SqlServer,
TestCredentials.Environments[0].OozieStores[0].Database,
TestCredentials.AzureUserName,
TestCredentials.AzurePassword);
cluster.HiveMetastore = new Metastore(TestCredentials.Environments[0].HiveStores[0].SqlServer,
TestCredentials.Environments[0].HiveStores[0].Database,
TestCredentials.AzureUserName,
TestCredentials.AzurePassword);
cluster.Location = cluster.Location.ToUpperInvariant();
await ValidateCreateClusterSucceeds(cluster);
}
[TestMethod]
[TestCategory("Integration")]
[TestCategory("CheckIn")]
[TestCategory("PocoClient")]
[Timeout(5 * 60 * 1000)] // ms
public async Task ICannotCreateACluster_WithNonOverridableConfigurationOptions()
{
var cluster = GetRandomCluster();
cluster.CoreConfiguration.Add(new KeyValuePair<string, string>("fs.default.name", Constants.WabsProtocolSchemeName + "nonexistantaccount"));
cluster.Location = cluster.Location.ToUpperInvariant();
await this.ValidateCreateClusterFailsWithError(cluster);
}
[TestMethod]
[TestCategory("Integration")]
[TestCategory("CheckIn")]
[TestCategory("PocoClient")]
[Timeout(5 * 60 * 1000)] // ms
public async Task ICanCreateACluster_WithCoreConfigurationOptions()
{
var cluster = GetRandomCluster();
cluster.CoreConfiguration.Add(new KeyValuePair<string, string>("hadoop.filelogs.size", ""));
cluster.Location = cluster.Location.ToUpperInvariant();
Action<ClusterDetails> validateConfigOptions = (testCluster) =>
{
ValidateClusterConfiguration(testCluster, cluster);
};
await ValidateCreateClusterSucceeds(cluster, validateConfigOptions);
}
[TestMethod]
[TestCategory("Integration")]
[TestCategory("CheckIn")]
[TestCategory("PocoClient")]
[Timeout(5 * 60 * 1000)] // ms
public async Task ICanCreateACluster_WithHdfsConfigurationOptions()
{
var cluster = GetRandomCluster();
cluster.HdfsConfiguration.Add(new KeyValuePair<string, string>("hadoop.filelogs.size", ""));
cluster.Location = cluster.Location.ToUpperInvariant();
Action<ClusterDetails> validateConfigOptions = (testCluster) =>
{
ValidateClusterConfiguration(testCluster, cluster);
};
await ValidateCreateClusterSucceeds(cluster, validateConfigOptions);
}
[TestMethod]
[TestCategory("Integration")]
[TestCategory("CheckIn")]
[TestCategory("PocoClient")]
[Timeout(5 * 60 * 1000)] // ms
public async Task ICanCreateACluster_WithMapReduceConfigurationOptions()
{
var cluster = GetRandomCluster();
cluster.MapReduceConfiguration.ConfigurationCollection.Add(new KeyValuePair<string, string>("hadoop.filelogs.size", ""));
cluster.Location = cluster.Location.ToUpperInvariant();
Action<ClusterDetails> validateConfigOptions = (testCluster) =>
{
ValidateClusterConfiguration(testCluster, cluster);
};
await ValidateCreateClusterSucceeds(cluster, validateConfigOptions);
}
[TestMethod]
[TestCategory("Integration")]
[TestCategory("CheckIn")]
[TestCategory("PocoClient")]
[Timeout(5 * 60 * 1000)] // ms
public async Task ICanCreateACluster_WithHiveConfigurationOptions()
{
var cluster = GetRandomCluster();
cluster.HiveConfiguration.ConfigurationCollection.Add(new KeyValuePair<string, string>("hadoop.filelogs.size", ""));
cluster.Location = cluster.Location.ToUpperInvariant();
Action<ClusterDetails> validateConfigOptions = (testCluster) =>
{
ValidateClusterConfiguration(testCluster, cluster);
};
await ValidateCreateClusterSucceeds(cluster, validateConfigOptions);
}
[TestMethod]
[TestCategory("Integration")]
[TestCategory("CheckIn")]
[TestCategory("PocoClient")]
[Timeout(5 * 60 * 1000)] // ms
public async Task ICanCreateACluster_WithOozieConfigurationOptions()
{
var cluster = GetRandomCluster();
cluster.OozieConfiguration.ConfigurationCollection.Add(new KeyValuePair<string, string>("hadoop.filelogs.size", ""));
cluster.Location = cluster.Location.ToUpperInvariant();
Action<ClusterDetails> validateConfigOptions = (testCluster) =>
{
ValidateClusterConfiguration(testCluster, cluster);
};
await ValidateCreateClusterSucceeds(cluster, validateConfigOptions);
}
[TestMethod]
[TestCategory("Integration")]
[TestCategory("CheckIn")]
[TestCategory("PocoClient")]
[Timeout(5 * 60 * 1000)] // ms
public async Task ICanCreateACluster_WithHBaseConfigurationOptions()
{
var cluster = GetRandomCluster();
cluster.HBaseConfiguration.ConfigurationCollection.Add(new KeyValuePair<string, string>("zookeeper.session.timeout", "120"));
cluster.Location = cluster.Location.ToUpperInvariant();
Action<ClusterDetails> validateConfigOptions = (testCluster) =>
{
ValidateClusterConfiguration(testCluster, cluster);
};
await ValidateCreateClusterSucceeds(cluster, validateConfigOptions);
}
[TestMethod]
[TestCategory("Integration")]
[TestCategory("CheckIn")]
[TestCategory("PocoClient")]
[Timeout(5 * 60 * 1000)] // ms
public async Task ICanCreateACluster_WithStormConfigurationOptions()
{
var cluster = GetRandomCluster();
cluster.StormConfiguration.Add(new KeyValuePair<string, string>("storm.messaging.netty.max_retries", "11"));
cluster.Location = cluster.Location.ToUpperInvariant();
Action<ClusterDetails> validateConfigOptions = (testCluster) =>
{
ValidateClusterConfiguration(testCluster, cluster);
};
await ValidateCreateClusterSucceeds(cluster, validateConfigOptions);
}
[TestMethod]
[TestCategory("Integration")]
[TestCategory("CheckIn")]
[TestCategory("PocoClient")]
[TestCategory("Defect")]
public void ICanResolveProductionStorageAccountsWithName()
{
var resolvedAcccountName = AsvValidationHelper.GetFullyQualifiedStorageAccountName("storageaccountaname");
Assert.AreEqual("storageaccountaname.blob.core.windows.net", resolvedAcccountName);
}
[TestMethod]
[TestCategory("Integration")]
[TestCategory("CheckIn")]
[TestCategory("PocoClient")]
[TestCategory("Defect")]
public void ICanResolveStagingStorageAccountsWithFQDN()
{
var internalAccountName = "storageaccountaname.blob.core.windows-cint.net";
var resolvedAcccountName = AsvValidationHelper.GetFullyQualifiedStorageAccountName(internalAccountName);
Assert.AreEqual(internalAccountName, resolvedAcccountName);
}
[TestMethod]
[TestCategory("Integration")]
[TestCategory("CheckIn")]
[TestCategory("PocoClient")]
[TestCategory("Defect")]
public void ICanStopPollingWhenErrorIsDetected()
{
IHDInsightCertificateCredential credentials = IntegrationTestBase.GetValidCredentials();
using (var client = ServiceLocator.Instance.Locate<IHDInsightManagementPocoClientFactory>().Create(credentials, GetAbstractionContext(), false))
{
var test = new ClusterDetails("TestCluster", ClusterState.Unknown.ToString());
test.Error = new ClusterErrorStatus(400, "Hit an error", "Create");
var result = client.PollSignal(test, ClusterState.Operational, ClusterState.Running);
Assert.AreEqual(result, IHDInsightManagementPocoClientExtensions.PollResult.Stop);
test.State = ClusterState.ClusterStorageProvisioned;
result = client.PollSignal(test, ClusterState.Operational, ClusterState.Running);
Assert.AreEqual(result, IHDInsightManagementPocoClientExtensions.PollResult.Stop);
}
}
[TestMethod]
[TestCategory("Integration")]
[TestCategory("CheckIn")]
[TestCategory("PocoClient")]
[TestCategory("Defect")]
public void ICanPossibleErrorPollingWhenClusterStateIsUnknown()
{
IHDInsightCertificateCredential credentials = IntegrationTestBase.GetValidCredentials();
using (var client = ServiceLocator.Instance.Locate<IHDInsightManagementPocoClientFactory>().Create(credentials, GetAbstractionContext(), false))
{
var result = client.PollSignal(null, ClusterState.Operational, ClusterState.Running);
Assert.AreEqual(result, IHDInsightManagementPocoClientExtensions.PollResult.Null);
var test = new ClusterDetails("TestCluster", ClusterState.Unknown.ToString());
result = client.PollSignal(test, ClusterState.Operational, ClusterState.Running);
Assert.AreEqual(result, IHDInsightManagementPocoClientExtensions.PollResult.Unknown);
}
}
[TestMethod]
[TestCategory("Integration")]
[TestCategory("CheckIn")]
[TestCategory("PocoClient")]
[TestCategory("Defect")]
public void ICanContinuePollingWhenClusterStateIsValid()
{
IHDInsightCertificateCredential credentials = IntegrationTestBase.GetValidCredentials();
using (var client = ServiceLocator.Instance.Locate<IHDInsightManagementPocoClientFactory>().Create(credentials, GetAbstractionContext(), false))
{
var test = new ClusterDetails("TestCluster", ClusterState.ReadyForDeployment.ToString());
var result = client.PollSignal(test, ClusterState.Operational, ClusterState.Running);
Assert.AreEqual(result, IHDInsightManagementPocoClientExtensions.PollResult.Continue);
}
}
internal static void ValidateClusterConfiguration(ClusterDetails testCluster, ClusterCreateParameters cluster)
{
var remoteCreds = new BasicAuthCredential()
{
Server = GatewayUriResolver.GetGatewayUri(new Uri(testCluster.ConnectionUrl).Host),
UserName = testCluster.HttpUserName,
Password = testCluster.HttpPassword
};
var configurationAccessor =
ServiceLocator.Instance.Locate<IAzureHDInsightClusterConfigurationAccessorFactory>().Create(remoteCreds);
var coreConfiguration = configurationAccessor.GetCoreServiceConfiguration().WaitForResult();
ValidateConfiguration(cluster.CoreConfiguration, coreConfiguration);
var hdfsConfiguration = configurationAccessor.GetHdfsServiceConfiguration().WaitForResult();
ValidateConfiguration(cluster.HdfsConfiguration, hdfsConfiguration);
var mapReduceConfiguration = configurationAccessor.GetMapReduceServiceConfiguration().WaitForResult();
ValidateConfiguration(cluster.MapReduceConfiguration.ConfigurationCollection, mapReduceConfiguration);
var hiveConfiguration = configurationAccessor.GetHiveServiceConfiguration().WaitForResult();
ValidateConfiguration(cluster.HiveConfiguration.ConfigurationCollection, hiveConfiguration);
var oozieConfiguration = configurationAccessor.GetOozieServiceConfiguration().WaitForResult();
ValidateConfiguration(cluster.OozieConfiguration.ConfigurationCollection, oozieConfiguration);
}
private static void ValidateConfiguration(IEnumerable<KeyValuePair<string, string>> expected, Configuration.ConfigurationPropertyCollection actual)
{
foreach (var coreConfig in expected)
{
var configUnderTest = actual.FirstOrDefault(c => c.Key == coreConfig.Key);
Assert.IsNotNull(configUnderTest, "Unable to find config option with name '{0}'", coreConfig.Key);
Assert.AreEqual(coreConfig.Value, configUnderTest.Value, "value doesn't match for config option with name '{0}'", coreConfig.Key);
}
}
private async Task ValidateCreateClusterSucceeds(ClusterCreateParameters cluster)
{
await ValidateCreateClusterSucceeds(cluster, null);
}
private async Task ValidateCreateClusterSucceeds(ClusterCreateParameters cluster, Action<ClusterDetails> postCreateValidation)
{
IHDInsightCertificateCredential credentials = IntegrationTestBase.GetValidCredentials();
using (var client = ServiceLocator.Instance.Locate<IHDInsightManagementPocoClientFactory>().Create(credentials, GetAbstractionContext(), false))
{
client.CreateContainer(cluster).Wait();
await client.WaitForClusterInConditionOrError(null, cluster.Name, cluster.Location, TimeSpan.FromMinutes(30), HDInsightClient.DefaultPollingInterval, GetAbstractionContext(), this.CreatingStates);
var task = client.ListContainer(cluster.Name);
task.WaitForResult();
var container = task.Result;
Assert.IsNotNull(container);
if (container.Error.IsNotNull())
{
Assert.Fail("The Container was not expected to return an error but returned ({0}) ({1})", container.Error.HttpCode, container.Error.Message);
}
if (postCreateValidation != null)
{
postCreateValidation(container);
}
await client.DeleteContainer(cluster.Name);
await client.WaitForClusterNullOrError(cluster.Name, cluster.Location, TimeSpan.FromMinutes(10), IntegrationTestBase.GetAbstractionContext().CancellationToken);
Assert.IsNull(container.Error);
Assert.IsNull(client.ListContainer(cluster.Name).WaitForResult());
}
}
private readonly ClusterState[] CreatingStates = new ClusterState
[]
{
ClusterState.AzureVMConfiguration,
ClusterState.ClusterStorageProvisioned,
ClusterState.HDInsightConfiguration,
ClusterState.Operational,
ClusterState.Running,
};
[TestMethod]
[TestCategory("Integration")]
[TestCategory("CheckIn")]
[TestCategory("PocoClient")]
public async Task NegativeTest_InvalidAsvConfig_Using_PocoClientAbstraction()
{
var cluster = GetRandomCluster();
IHDInsightCertificateCredential credentials = IntegrationTestBase.GetValidCredentials();
cluster.DefaultStorageAccountKey = "invalid";
try
{
await ServiceLocator.Instance.Locate<IHDInsightManagementPocoClientFactory>().Create(credentials, GetAbstractionContext(), false).CreateContainer(cluster);
}
catch (ConfigurationErrorsException e)
{
// NEIN: This needs to validate at least one parameter of the exception.
Console.WriteLine("THIS TEST SUCCEDED because the expected negative result was found");
Console.WriteLine("ASV Validation failed. Details: {0}", e.ToString());
return;
}
catch (Exception e)
{
Assert.Fail("Expected exception 'ConfigurationErrorsException'; found '{0}'. Message:{1}", e.GetType(), e.Message);
}
Assert.Fail("ASV Validation should have failed.");
}
[TestMethod]
[TestCategory("Integration")]
[TestCategory("CheckIn")]
[TestCategory("PocoClient")]
public async Task NegativeTest_InvalidLocation_Using_PocoClient()
{
var cluster = GetRandomCluster();
IHDInsightCertificateCredential credentials = IntegrationTestBase.GetValidCredentials();
cluster.Location = "nowhere";
try
{
await ServiceLocator.Instance.Locate<IHDInsightManagementPocoClientFactory>().Create(credentials, GetAbstractionContext(), false).CreateContainer(cluster);
Assert.Fail("Location Validation should have failed.");
}
catch (InvalidOperationException)
{
Console.WriteLine("THIS TEST SUCCEDED because the expected negative result was found");
}
catch (Exception e)
{
Assert.Fail("Expected exception 'InvalidOperationException'; found '{0}'. Message:{1}", e.GetType(), e.Message);
}
}
[TestMethod]
[TestCategory("Integration")]
[TestCategory("CheckIn")]
[TestCategory("PocoClient")]
public async Task NegativeTest_RepeatedAsvConfig_Using_PocoClientAbstraction()
{
IHDInsightCertificateCredential credentials = IntegrationTestBase.GetValidCredentials();
var cluster = GetRandomCluster();
cluster.AdditionalStorageAccounts.Add(new WabStorageAccountConfiguration(cluster.DefaultStorageAccountName, cluster.DefaultStorageAccountKey));
try
{
await ServiceLocator.Instance.Locate<IHDInsightManagementPocoClientFactory>().Create(credentials, GetAbstractionContext(), false).CreateContainer(cluster);
}
catch (InvalidOperationException e)
{
Console.WriteLine("THIS TEST SUCCEDED because the expected negative result was found");
Console.WriteLine("ASV Validation failed. Details: {0}", e.ToString());
return;
}
catch (Exception e)
{
Assert.Fail("Expected exception 'InvalidOperationException'; found '{0}'. Message:{1}", e.GetType(), e.Message);
}
Assert.Fail("ASV Validation should have failed.");
}
[TestMethod]
[TestCategory("Integration")]
[TestCategory("CheckIn")]
[TestCategory("PocoClient")]
[ExpectedException(typeof(ConfigurationErrorsException))]
public async Task NegativeTest_InvalidAsv_Using_PocoClient()
{
IHDInsightCertificateCredential credentials = IntegrationTestBase.GetValidCredentials();
var cluster = GetRandomCluster();
cluster.AdditionalStorageAccounts.Add(new WabStorageAccountConfiguration(IntegrationTestBase.TestCredentials.Environments[0].AdditionalStorageAccounts[0].Name, IntegrationTestBase.TestCredentials.Environments[0].DefaultStorageAccount.Key));
await ServiceLocator.Instance.Locate<IHDInsightManagementPocoClientFactory>().Create(credentials, GetAbstractionContext(), false).CreateContainer(cluster);
}
[TestMethod]
[TestCategory("Integration")]
[TestCategory("CheckIn")]
[TestCategory("PocoClient")]
public async Task NegativeTest_ExistingCluster_Using_PocoClient()
{
IHDInsightCertificateCredential credentials = IntegrationTestBase.GetValidCredentials();
var cluster = GetRandomCluster();
cluster.Name = TestCredentials.WellKnownCluster.DnsName;
try
{
await ServiceLocator.Instance.Locate<IHDInsightManagementPocoClientFactory>().Create(credentials, GetAbstractionContext(), false).CreateContainer(cluster);
}
catch (HttpLayerException e)
{
Assert.IsTrue(e.RequestContent.Contains(HDInsightClient.ClusterAlreadyExistsError));
Assert.AreEqual(e.RequestStatusCode, HttpStatusCode.BadRequest);
}
}
private async Task ValidateCreateClusterFailsWithError(ClusterCreateParameters cluster)
{
IHDInsightCertificateCredential credentials = IntegrationTestBase.GetValidCredentials();
var client = ServiceLocator.Instance.Locate<IHDInsightManagementPocoClientFactory>().Create(credentials, GetAbstractionContext(), false);
await client.CreateContainer(cluster);
await client.WaitForClusterNotNull(cluster.Name, cluster.Location, TimeSpan.FromMinutes(10), GetAbstractionContext().CancellationToken);
var result = await client.ListContainer(cluster.Name);
Assert.IsNotNull(result);
Assert.IsNotNull(result.Error);
await client.DeleteContainer(cluster.Name);
await client.WaitForClusterNull(cluster.Name, cluster.Location, TimeSpan.FromMinutes(10), GetAbstractionContext().CancellationToken);
}
[TestMethod]
[TestCategory("Integration")]
[TestCategory("CheckIn")]
[TestCategory("PocoClient")]
public async Task NegativeTest_InvalidMetastore_Using_PocoClient()
{
var cluster = GetRandomCluster();
cluster.OozieMetastore = new Metastore(TestCredentials.Environments[0].OozieStores[0].SqlServer,
TestCredentials.Environments[0].OozieStores[0].Database,
TestCredentials.AzureUserName,
TestCredentials.AzurePassword);
cluster.HiveMetastore = new Metastore(TestCredentials.Environments[0].HiveStores[0].SqlServer,
TestCredentials.Environments[0].HiveStores[0].Database,
TestCredentials.AzureUserName,
"NOT-THE-REAL-PASSWORD");
await ValidateCreateClusterFailsWithError(cluster);
}
[TestMethod]
[TestCategory("Integration")]
[TestCategory("CheckIn")]
[TestCategory("PocoClient")]
public async Task PositiveTest_OnlyOneMetastore_Using_PocoClient()
{
var cluster = GetRandomCluster();
cluster.OozieMetastore = new Metastore(TestCredentials.Environments[0].OozieStores[0].SqlServer,
TestCredentials.Environments[0].OozieStores[0].Database,
TestCredentials.AzureUserName,
TestCredentials.AzurePassword);
await this.ValidateCreateClusterSucceeds(cluster);
}
private string FormatHeaders(IHttpResponseHeadersAbstraction httpResponseHeadersAbstraction)
{
StringBuilder sbLog = new StringBuilder();
foreach (var header in httpResponseHeadersAbstraction)
{
if (header.Value is IEnumerable<string>)
{
sbLog.Append(header.Key + " ");
sbLog.Append(string.Join(",", header.Value as IEnumerable<string>));
}
else
{
sbLog.Append(header.Key + " " + header.Value);
}
sbLog.Append(Environment.NewLine);
}
return sbLog.ToString();
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvr = Google.Ads.GoogleAds.V9.Resources;
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Ads.GoogleAds.V9.Services
{
/// <summary>Settings for <see cref="CustomerServiceClient"/> instances.</summary>
public sealed partial class CustomerServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="CustomerServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="CustomerServiceSettings"/>.</returns>
public static CustomerServiceSettings GetDefault() => new CustomerServiceSettings();
/// <summary>Constructs a new <see cref="CustomerServiceSettings"/> object with default settings.</summary>
public CustomerServiceSettings()
{
}
private CustomerServiceSettings(CustomerServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetCustomerSettings = existing.GetCustomerSettings;
MutateCustomerSettings = existing.MutateCustomerSettings;
ListAccessibleCustomersSettings = existing.ListAccessibleCustomersSettings;
CreateCustomerClientSettings = existing.CreateCustomerClientSettings;
OnCopy(existing);
}
partial void OnCopy(CustomerServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>CustomerServiceClient.GetCustomer</c> and <c>CustomerServiceClient.GetCustomerAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetCustomerSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>CustomerServiceClient.MutateCustomer</c> and <c>CustomerServiceClient.MutateCustomerAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings MutateCustomerSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>CustomerServiceClient.ListAccessibleCustomers</c> and
/// <c>CustomerServiceClient.ListAccessibleCustomersAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings ListAccessibleCustomersSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>CustomerServiceClient.CreateCustomerClient</c> and <c>CustomerServiceClient.CreateCustomerClientAsync</c>
/// .
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings CreateCustomerClientSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="CustomerServiceSettings"/> object.</returns>
public CustomerServiceSettings Clone() => new CustomerServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="CustomerServiceClient"/> to provide simple configuration of credentials, endpoint
/// etc.
/// </summary>
internal sealed partial class CustomerServiceClientBuilder : gaxgrpc::ClientBuilderBase<CustomerServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public CustomerServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public CustomerServiceClientBuilder()
{
UseJwtAccessWithScopes = CustomerServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref CustomerServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<CustomerServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override CustomerServiceClient Build()
{
CustomerServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<CustomerServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<CustomerServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private CustomerServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return CustomerServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<CustomerServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return CustomerServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => CustomerServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => CustomerServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => CustomerServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>CustomerService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to manage customers.
/// </remarks>
public abstract partial class CustomerServiceClient
{
/// <summary>
/// The default endpoint for the CustomerService service, which is a host of "googleads.googleapis.com" and a
/// port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443";
/// <summary>The default CustomerService scopes.</summary>
/// <remarks>
/// The default CustomerService scopes are:
/// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/adwords",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="CustomerServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="CustomerServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="CustomerServiceClient"/>.</returns>
public static stt::Task<CustomerServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new CustomerServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="CustomerServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="CustomerServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="CustomerServiceClient"/>.</returns>
public static CustomerServiceClient Create() => new CustomerServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="CustomerServiceClient"/> which uses the specified call invoker for remote operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="CustomerServiceSettings"/>.</param>
/// <returns>The created <see cref="CustomerServiceClient"/>.</returns>
internal static CustomerServiceClient Create(grpccore::CallInvoker callInvoker, CustomerServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
CustomerService.CustomerServiceClient grpcClient = new CustomerService.CustomerServiceClient(callInvoker);
return new CustomerServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC CustomerService client</summary>
public virtual CustomerService.CustomerServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested customer in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::Customer GetCustomer(GetCustomerRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested customer in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::Customer> GetCustomerAsync(GetCustomerRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested customer in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::Customer> GetCustomerAsync(GetCustomerRequest request, st::CancellationToken cancellationToken) =>
GetCustomerAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested customer in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the customer to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::Customer GetCustomer(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetCustomer(new GetCustomerRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested customer in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the customer to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::Customer> GetCustomerAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetCustomerAsync(new GetCustomerRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested customer in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the customer to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::Customer> GetCustomerAsync(string resourceName, st::CancellationToken cancellationToken) =>
GetCustomerAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested customer in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the customer to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::Customer GetCustomer(gagvr::CustomerName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetCustomer(new GetCustomerRequest
{
ResourceNameAsCustomerName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested customer in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the customer to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::Customer> GetCustomerAsync(gagvr::CustomerName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetCustomerAsync(new GetCustomerRequest
{
ResourceNameAsCustomerName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested customer in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the customer to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::Customer> GetCustomerAsync(gagvr::CustomerName resourceName, st::CancellationToken cancellationToken) =>
GetCustomerAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Updates a customer. Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// [UrlFieldError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateCustomerResponse MutateCustomer(MutateCustomerRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Updates a customer. Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// [UrlFieldError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateCustomerResponse> MutateCustomerAsync(MutateCustomerRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Updates a customer. Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// [UrlFieldError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateCustomerResponse> MutateCustomerAsync(MutateCustomerRequest request, st::CancellationToken cancellationToken) =>
MutateCustomerAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Updates a customer. Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// [UrlFieldError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer being modified.
/// </param>
/// <param name="operation">
/// Required. The operation to perform on the customer
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateCustomerResponse MutateCustomer(string customerId, CustomerOperation operation, gaxgrpc::CallSettings callSettings = null) =>
MutateCustomer(new MutateCustomerRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operation = gax::GaxPreconditions.CheckNotNull(operation, nameof(operation)),
}, callSettings);
/// <summary>
/// Updates a customer. Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// [UrlFieldError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer being modified.
/// </param>
/// <param name="operation">
/// Required. The operation to perform on the customer
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateCustomerResponse> MutateCustomerAsync(string customerId, CustomerOperation operation, gaxgrpc::CallSettings callSettings = null) =>
MutateCustomerAsync(new MutateCustomerRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operation = gax::GaxPreconditions.CheckNotNull(operation, nameof(operation)),
}, callSettings);
/// <summary>
/// Updates a customer. Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// [UrlFieldError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer being modified.
/// </param>
/// <param name="operation">
/// Required. The operation to perform on the customer
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateCustomerResponse> MutateCustomerAsync(string customerId, CustomerOperation operation, st::CancellationToken cancellationToken) =>
MutateCustomerAsync(customerId, operation, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns resource names of customers directly accessible by the
/// user authenticating the call.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual ListAccessibleCustomersResponse ListAccessibleCustomers(ListAccessibleCustomersRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns resource names of customers directly accessible by the
/// user authenticating the call.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ListAccessibleCustomersResponse> ListAccessibleCustomersAsync(ListAccessibleCustomersRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns resource names of customers directly accessible by the
/// user authenticating the call.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ListAccessibleCustomersResponse> ListAccessibleCustomersAsync(ListAccessibleCustomersRequest request, st::CancellationToken cancellationToken) =>
ListAccessibleCustomersAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates a new client under manager. The new client customer is returned.
///
/// List of thrown errors:
/// [AccessInvitationError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CurrencyCodeError]()
/// [HeaderError]()
/// [InternalError]()
/// [ManagerLinkError]()
/// [QuotaError]()
/// [RequestError]()
/// [StringLengthError]()
/// [TimeZoneError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual CreateCustomerClientResponse CreateCustomerClient(CreateCustomerClientRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates a new client under manager. The new client customer is returned.
///
/// List of thrown errors:
/// [AccessInvitationError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CurrencyCodeError]()
/// [HeaderError]()
/// [InternalError]()
/// [ManagerLinkError]()
/// [QuotaError]()
/// [RequestError]()
/// [StringLengthError]()
/// [TimeZoneError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<CreateCustomerClientResponse> CreateCustomerClientAsync(CreateCustomerClientRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates a new client under manager. The new client customer is returned.
///
/// List of thrown errors:
/// [AccessInvitationError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CurrencyCodeError]()
/// [HeaderError]()
/// [InternalError]()
/// [ManagerLinkError]()
/// [QuotaError]()
/// [RequestError]()
/// [StringLengthError]()
/// [TimeZoneError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<CreateCustomerClientResponse> CreateCustomerClientAsync(CreateCustomerClientRequest request, st::CancellationToken cancellationToken) =>
CreateCustomerClientAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates a new client under manager. The new client customer is returned.
///
/// List of thrown errors:
/// [AccessInvitationError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CurrencyCodeError]()
/// [HeaderError]()
/// [InternalError]()
/// [ManagerLinkError]()
/// [QuotaError]()
/// [RequestError]()
/// [StringLengthError]()
/// [TimeZoneError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the Manager under whom client customer is being created.
/// </param>
/// <param name="customerClient">
/// Required. The new client customer to create. The resource name on this customer
/// will be ignored.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual CreateCustomerClientResponse CreateCustomerClient(string customerId, gagvr::Customer customerClient, gaxgrpc::CallSettings callSettings = null) =>
CreateCustomerClient(new CreateCustomerClientRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
CustomerClient = gax::GaxPreconditions.CheckNotNull(customerClient, nameof(customerClient)),
}, callSettings);
/// <summary>
/// Creates a new client under manager. The new client customer is returned.
///
/// List of thrown errors:
/// [AccessInvitationError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CurrencyCodeError]()
/// [HeaderError]()
/// [InternalError]()
/// [ManagerLinkError]()
/// [QuotaError]()
/// [RequestError]()
/// [StringLengthError]()
/// [TimeZoneError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the Manager under whom client customer is being created.
/// </param>
/// <param name="customerClient">
/// Required. The new client customer to create. The resource name on this customer
/// will be ignored.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<CreateCustomerClientResponse> CreateCustomerClientAsync(string customerId, gagvr::Customer customerClient, gaxgrpc::CallSettings callSettings = null) =>
CreateCustomerClientAsync(new CreateCustomerClientRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
CustomerClient = gax::GaxPreconditions.CheckNotNull(customerClient, nameof(customerClient)),
}, callSettings);
/// <summary>
/// Creates a new client under manager. The new client customer is returned.
///
/// List of thrown errors:
/// [AccessInvitationError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CurrencyCodeError]()
/// [HeaderError]()
/// [InternalError]()
/// [ManagerLinkError]()
/// [QuotaError]()
/// [RequestError]()
/// [StringLengthError]()
/// [TimeZoneError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the Manager under whom client customer is being created.
/// </param>
/// <param name="customerClient">
/// Required. The new client customer to create. The resource name on this customer
/// will be ignored.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<CreateCustomerClientResponse> CreateCustomerClientAsync(string customerId, gagvr::Customer customerClient, st::CancellationToken cancellationToken) =>
CreateCustomerClientAsync(customerId, customerClient, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>CustomerService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to manage customers.
/// </remarks>
public sealed partial class CustomerServiceClientImpl : CustomerServiceClient
{
private readonly gaxgrpc::ApiCall<GetCustomerRequest, gagvr::Customer> _callGetCustomer;
private readonly gaxgrpc::ApiCall<MutateCustomerRequest, MutateCustomerResponse> _callMutateCustomer;
private readonly gaxgrpc::ApiCall<ListAccessibleCustomersRequest, ListAccessibleCustomersResponse> _callListAccessibleCustomers;
private readonly gaxgrpc::ApiCall<CreateCustomerClientRequest, CreateCustomerClientResponse> _callCreateCustomerClient;
/// <summary>
/// Constructs a client wrapper for the CustomerService service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="CustomerServiceSettings"/> used within this client.</param>
public CustomerServiceClientImpl(CustomerService.CustomerServiceClient grpcClient, CustomerServiceSettings settings)
{
GrpcClient = grpcClient;
CustomerServiceSettings effectiveSettings = settings ?? CustomerServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetCustomer = clientHelper.BuildApiCall<GetCustomerRequest, gagvr::Customer>(grpcClient.GetCustomerAsync, grpcClient.GetCustomer, effectiveSettings.GetCustomerSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName);
Modify_ApiCall(ref _callGetCustomer);
Modify_GetCustomerApiCall(ref _callGetCustomer);
_callMutateCustomer = clientHelper.BuildApiCall<MutateCustomerRequest, MutateCustomerResponse>(grpcClient.MutateCustomerAsync, grpcClient.MutateCustomer, effectiveSettings.MutateCustomerSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId);
Modify_ApiCall(ref _callMutateCustomer);
Modify_MutateCustomerApiCall(ref _callMutateCustomer);
_callListAccessibleCustomers = clientHelper.BuildApiCall<ListAccessibleCustomersRequest, ListAccessibleCustomersResponse>(grpcClient.ListAccessibleCustomersAsync, grpcClient.ListAccessibleCustomers, effectiveSettings.ListAccessibleCustomersSettings);
Modify_ApiCall(ref _callListAccessibleCustomers);
Modify_ListAccessibleCustomersApiCall(ref _callListAccessibleCustomers);
_callCreateCustomerClient = clientHelper.BuildApiCall<CreateCustomerClientRequest, CreateCustomerClientResponse>(grpcClient.CreateCustomerClientAsync, grpcClient.CreateCustomerClient, effectiveSettings.CreateCustomerClientSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId);
Modify_ApiCall(ref _callCreateCustomerClient);
Modify_CreateCustomerClientApiCall(ref _callCreateCustomerClient);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_GetCustomerApiCall(ref gaxgrpc::ApiCall<GetCustomerRequest, gagvr::Customer> call);
partial void Modify_MutateCustomerApiCall(ref gaxgrpc::ApiCall<MutateCustomerRequest, MutateCustomerResponse> call);
partial void Modify_ListAccessibleCustomersApiCall(ref gaxgrpc::ApiCall<ListAccessibleCustomersRequest, ListAccessibleCustomersResponse> call);
partial void Modify_CreateCustomerClientApiCall(ref gaxgrpc::ApiCall<CreateCustomerClientRequest, CreateCustomerClientResponse> call);
partial void OnConstruction(CustomerService.CustomerServiceClient grpcClient, CustomerServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC CustomerService client</summary>
public override CustomerService.CustomerServiceClient GrpcClient { get; }
partial void Modify_GetCustomerRequest(ref GetCustomerRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_MutateCustomerRequest(ref MutateCustomerRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_ListAccessibleCustomersRequest(ref ListAccessibleCustomersRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_CreateCustomerClientRequest(ref CreateCustomerClientRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Returns the requested customer in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override gagvr::Customer GetCustomer(GetCustomerRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetCustomerRequest(ref request, ref callSettings);
return _callGetCustomer.Sync(request, callSettings);
}
/// <summary>
/// Returns the requested customer in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<gagvr::Customer> GetCustomerAsync(GetCustomerRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetCustomerRequest(ref request, ref callSettings);
return _callGetCustomer.Async(request, callSettings);
}
/// <summary>
/// Updates a customer. Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// [UrlFieldError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override MutateCustomerResponse MutateCustomer(MutateCustomerRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateCustomerRequest(ref request, ref callSettings);
return _callMutateCustomer.Sync(request, callSettings);
}
/// <summary>
/// Updates a customer. Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// [UrlFieldError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<MutateCustomerResponse> MutateCustomerAsync(MutateCustomerRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateCustomerRequest(ref request, ref callSettings);
return _callMutateCustomer.Async(request, callSettings);
}
/// <summary>
/// Returns resource names of customers directly accessible by the
/// user authenticating the call.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override ListAccessibleCustomersResponse ListAccessibleCustomers(ListAccessibleCustomersRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListAccessibleCustomersRequest(ref request, ref callSettings);
return _callListAccessibleCustomers.Sync(request, callSettings);
}
/// <summary>
/// Returns resource names of customers directly accessible by the
/// user authenticating the call.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<ListAccessibleCustomersResponse> ListAccessibleCustomersAsync(ListAccessibleCustomersRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListAccessibleCustomersRequest(ref request, ref callSettings);
return _callListAccessibleCustomers.Async(request, callSettings);
}
/// <summary>
/// Creates a new client under manager. The new client customer is returned.
///
/// List of thrown errors:
/// [AccessInvitationError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CurrencyCodeError]()
/// [HeaderError]()
/// [InternalError]()
/// [ManagerLinkError]()
/// [QuotaError]()
/// [RequestError]()
/// [StringLengthError]()
/// [TimeZoneError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override CreateCustomerClientResponse CreateCustomerClient(CreateCustomerClientRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_CreateCustomerClientRequest(ref request, ref callSettings);
return _callCreateCustomerClient.Sync(request, callSettings);
}
/// <summary>
/// Creates a new client under manager. The new client customer is returned.
///
/// List of thrown errors:
/// [AccessInvitationError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CurrencyCodeError]()
/// [HeaderError]()
/// [InternalError]()
/// [ManagerLinkError]()
/// [QuotaError]()
/// [RequestError]()
/// [StringLengthError]()
/// [TimeZoneError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<CreateCustomerClientResponse> CreateCustomerClientAsync(CreateCustomerClientRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_CreateCustomerClientRequest(ref request, ref callSettings);
return _callCreateCustomerClient.Async(request, callSettings);
}
}
}
| |
/*
* Copyright (c) 2014 Tenebrous
*
* 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.
*
* Latest version: http://hg.tenebrous.co.uk/unityeditorenhancements/wiki/Home
*/
#if UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_5
#define UNITY_4_PLUS
#endif
using System.IO;
using UnityEngine;
using UnityEditor;
namespace Tenebrous.EditorEnhancements
{
public static class Common
{
private static string _lastBackgroundColourString;
private static Color _lastBackgroundColour;
private static string _basePath;
private static GUIStyle _colorLabel;
private static GUIStyle _colorMiniLabel;
public static GUIStyle ColorLabel( Color pColor )
{
if( _colorLabel == null )
_colorLabel = new GUIStyle( EditorStyles.label );
_colorLabel.normal.textColor = pColor;
return ( _colorLabel );
}
public static GUIStyle ColorMiniLabel( Color pColor )
{
if( _colorMiniLabel == null )
_colorMiniLabel = new GUIStyle( EditorStyles.miniLabel );
_colorMiniLabel.normal.textColor = pColor;
return ( _colorMiniLabel );
}
public static string BasePath
{
get
{
if( _basePath == null )
_basePath = Application.dataPath.Replace( Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar );
return ( _basePath );
}
}
public static string ProjectPath
{
get
{
string basePath = BasePath;
return ( basePath.Substring(0, basePath.Length-7) );
}
}
// public static bool UnityVersionAbove( string sVersion )
// {
//
// }
public static string TempRecompilationList
{
get
{
return ProjectPath
+ Path.DirectorySeparatorChar
+ "Temp"
+ Path.DirectorySeparatorChar
+ "tene_recompile.txt";
}
}
public static Color DefaultBackgroundColor
{
get
{
if (!EditorGUIUtility.isProSkin)
return (new Color(0.75f, 0.75f, 0.75f, 1.0f));
string value = EditorPrefs.GetString("Windows/Background");
Color c;
if (value == _lastBackgroundColourString)
return (_lastBackgroundColour);
string[] elements = value.Split(';');
if (elements.Length == 5)
if (elements[0] == "Windows/Background")
{
if (float.TryParse(elements[1], out c.r)
&& float.TryParse(elements[2], out c.g)
&& float.TryParse(elements[3], out c.b)
&& float.TryParse(elements[4], out c.a))
{
c.a = 1;
_lastBackgroundColour = c;
_lastBackgroundColourString = value;
return (c);
}
}
return (Color.black);
}
}
public static Color StringToColor(string pString)
{
Color c = Color.grey;
string[] elements = pString.Split(',');
if (elements.Length == 4)
if (float.TryParse(elements[0], out c.r)
&& float.TryParse(elements[1], out c.g)
&& float.TryParse(elements[2], out c.b)
&& float.TryParse(elements[3], out c.a))
return (c);
return (Color.grey);
}
public static string ColorToString(Color pColor)
{
return (pColor.r.ToString("0.00")
+ ","
+ pColor.g.ToString("0.00")
+ ","
+ pColor.b.ToString("0.00")
+ ","
+ pColor.a.ToString("0.00")
);
}
public static string GetLongPref(string pName)
{
string result = "";
int index = 0;
while (EditorPrefs.HasKey(pName + index))
result += EditorPrefs.GetString(pName + index++);
return (result);
}
public static void SetLongPref(string pName, string pValue)
{
string value = "";
int index = 0;
while (pValue.Length > 1000)
{
value = pValue.Substring(0, 1000);
EditorPrefs.SetString(pName + index++, value);
pValue = pValue.Substring(1000);
}
EditorPrefs.SetString(pName + index++, pValue);
while (EditorPrefs.HasKey(pName + index))
EditorPrefs.DeleteKey(pName + index++);
}
public static string FullPath( string pAssetPath )
{
return BasePath
+ pAssetPath.Substring( 6 ).Replace( Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar );
}
public static long UnityVersion(string pVersion = "")
{
long value = 0;
long valuePart = 0;
if( pVersion == "" )
pVersion = Application.unityVersion;
pVersion = pVersion.ToLower() + ".";
foreach( char c in pVersion )
{
if( c >= '0' && c <= '9' )
valuePart = valuePart * 10 + ( c - '0' );
else if( c >= 'a' && c <= 'z' )
{
value = value * 1000 + ( c - 'a' );
valuePart = 0;
}
else if( c == '.' )
{
value = value * 1000 + valuePart;
valuePart = 0;
}
}
return value;
}
public static bool Modifier(bool pEnabled, bool pRequireShift, bool pRequireCtrl, bool pRequireAlt)
{
return pEnabled
&& ( !pRequireShift || ( Event.current.modifiers & EventModifiers.Shift ) != 0 )
&& ( !pRequireCtrl || ( Event.current.modifiers & EventModifiers.Control ) != 0 )
&& ( !pRequireAlt || ( Event.current.modifiers & EventModifiers.Alt ) != 0 );
}
public static Texture GetMiniThumbnail( UnityEngine.Object obj )
{
#if UNITY_4_PLUS
return ( AssetPreview.GetMiniThumbnail( obj ) );
#else
return ( EditorUtility.GetMiniThumbnail( obj ) );
#endif
}
public static Texture2D GetAssetPreview( UnityEngine.Object obj )
{
#if UNITY_4_PLUS
return ( AssetPreview.GetAssetPreview( obj ) );
#else
return ( EditorUtility.GetAssetPreview( obj ) );
#endif
}
public static EditorWindow GetWindowByName( string pName )
{
UnityEngine.Object[] objectList = Resources.FindObjectsOfTypeAll( typeof( EditorWindow ) );
foreach( UnityEngine.Object obj in objectList )
{
if( obj.GetType().ToString() == pName )
return ( (EditorWindow)obj );
}
return ( null );
}
private static EditorWindow _projectWindow = null;
public static EditorWindow ProjectWindow
{
get
{
_projectWindow = _projectWindow
?? GetWindowByName("UnityEditor.ProjectWindow")
?? GetWindowByName("UnityEditor.ObjectBrowser")
?? GetWindowByName("UnityEditor.ProjectBrowser");
return ( _projectWindow );
}
}
private static EditorWindow _hierarchyWindow = null;
public static EditorWindow HierarchyWindow
{
get
{
_hierarchyWindow = _hierarchyWindow
?? GetWindowByName( "UnityEditor.HierarchyWindow" )
?? GetWindowByName( "UnityEditor.SceneHierarchyWindow" );
return ( _hierarchyWindow );
}
}
}
}
| |
using System;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
using UnityStandardAssets.Utility;
using Random = UnityEngine.Random;
namespace UnityStandardAssets.Characters.FirstPerson
{
[RequireComponent(typeof (CharacterController))]
[RequireComponent(typeof (GvrAudioSource))]
public class FirstPersonController : MonoBehaviour
{
[SerializeField] private bool m_IsWalking;
[SerializeField] private float m_WalkSpeed;
[SerializeField] private float m_RunSpeed;
[SerializeField] [Range(0f, 1f)] private float m_RunstepLenghten;
[SerializeField] private float m_JumpSpeed;
[SerializeField] private float m_StickToGroundForce;
[SerializeField] private float m_GravityMultiplier;
[SerializeField] private MouseLook m_MouseLook;
[SerializeField] private bool m_UseFovKick;
[SerializeField] private FOVKick m_FovKick = new FOVKick();
[SerializeField] private bool m_UseHeadBob;
[SerializeField] private CurveControlledBob m_HeadBob = new CurveControlledBob();
[SerializeField] private LerpControlledBob m_JumpBob = new LerpControlledBob();
[SerializeField] private float m_StepInterval;
[SerializeField] private AudioClip[] m_FootstepSounds; // an array of footstep sounds that will be randomly selected from.
[SerializeField] private AudioClip m_JumpSound; // the sound played when character leaves the ground.
[SerializeField] private AudioClip m_LandSound; // the sound played when character touches back on ground.
private Camera m_Camera;
private bool m_Jump;
private float m_YRotation;
private Vector2 m_Input;
private Vector3 m_MoveDir = Vector3.zero;
private CharacterController m_CharacterController;
private CollisionFlags m_CollisionFlags;
private bool m_PreviouslyGrounded;
private Vector3 m_OriginalCameraPosition;
private float m_StepCycle;
private float m_NextStep;
private bool m_Jumping;
private GvrAudioSource m_AudioSource;
// Use this for initialization
private void Start()
{
m_CharacterController = GetComponent<CharacterController>();
m_Camera = Camera.main;
m_OriginalCameraPosition = m_Camera.transform.localPosition;
m_FovKick.Setup(m_Camera);
m_HeadBob.Setup(m_Camera, m_StepInterval);
m_StepCycle = 0f;
m_NextStep = m_StepCycle/2f;
m_Jumping = false;
m_AudioSource = GetComponent<GvrAudioSource>();
m_MouseLook.Init(transform , m_Camera.transform);
}
// Update is called once per frame
private void Update()
{
RotateView();
// the jump state needs to read here to make sure it is not missed
if (!m_Jump)
{
m_Jump = CrossPlatformInputManager.GetButtonDown("Jump");
}
if (!m_PreviouslyGrounded && m_CharacterController.isGrounded)
{
StartCoroutine(m_JumpBob.DoBobCycle());
PlayLandingSound();
m_MoveDir.y = 0f;
m_Jumping = false;
}
if (!m_CharacterController.isGrounded && !m_Jumping && m_PreviouslyGrounded)
{
m_MoveDir.y = 0f;
}
m_PreviouslyGrounded = m_CharacterController.isGrounded;
}
private void PlayLandingSound()
{
m_AudioSource.clip = m_LandSound;
m_AudioSource.Play();
m_NextStep = m_StepCycle + .5f;
}
private void FixedUpdate()
{
float speed;
GetInput(out speed);
// always move along the camera forward as it is the direction that it being aimed at
Vector3 desiredMove = transform.forward*m_Input.y + transform.right*m_Input.x;
// get a normal for the surface that is being touched to move along it
RaycastHit hitInfo;
Physics.SphereCast(transform.position, m_CharacterController.radius, Vector3.down, out hitInfo,
m_CharacterController.height/2f, Physics.AllLayers, QueryTriggerInteraction.Ignore);
desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized;
m_MoveDir.x = desiredMove.x*speed;
m_MoveDir.z = desiredMove.z*speed;
if (m_CharacterController.isGrounded)
{
m_MoveDir.y = -m_StickToGroundForce;
if (m_Jump)
{
m_MoveDir.y = m_JumpSpeed;
PlayJumpSound();
m_Jump = false;
m_Jumping = true;
}
}
else
{
m_MoveDir += Physics.gravity*m_GravityMultiplier*Time.fixedDeltaTime;
}
m_CollisionFlags = m_CharacterController.Move(m_MoveDir*Time.fixedDeltaTime);
ProgressStepCycle(speed);
UpdateCameraPosition(speed);
m_MouseLook.UpdateCursorLock();
}
private void PlayJumpSound()
{
m_AudioSource.clip = m_JumpSound;
m_AudioSource.Play();
}
private void ProgressStepCycle(float speed)
{
if (m_CharacterController.velocity.sqrMagnitude > 0 && (m_Input.x != 0 || m_Input.y != 0))
{
m_StepCycle += (m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten)))*
Time.fixedDeltaTime;
}
if (!(m_StepCycle > m_NextStep))
{
return;
}
m_NextStep = m_StepCycle + m_StepInterval;
PlayFootStepAudio();
}
private void PlayFootStepAudio()
{
if (!m_CharacterController.isGrounded)
{
return;
}
// pick & play a random footstep sound from the array,
// excluding sound at index 0
int n = Random.Range(1, m_FootstepSounds.Length);
m_AudioSource.clip = m_FootstepSounds[n];
m_AudioSource.PlayOneShot(m_AudioSource.clip);
// move picked sound to index 0 so it's not picked next time
m_FootstepSounds[n] = m_FootstepSounds[0];
m_FootstepSounds[0] = m_AudioSource.clip;
}
private void UpdateCameraPosition(float speed)
{
Vector3 newCameraPosition;
if (!m_UseHeadBob)
{
return;
}
if (m_CharacterController.velocity.magnitude > 0 && m_CharacterController.isGrounded)
{
m_Camera.transform.localPosition =
m_HeadBob.DoHeadBob(m_CharacterController.velocity.magnitude +
(speed*(m_IsWalking ? 1f : m_RunstepLenghten)));
newCameraPosition = m_Camera.transform.localPosition;
newCameraPosition.y = m_Camera.transform.localPosition.y - m_JumpBob.Offset();
}
else
{
newCameraPosition = m_Camera.transform.localPosition;
newCameraPosition.y = m_OriginalCameraPosition.y - m_JumpBob.Offset();
}
m_Camera.transform.localPosition = newCameraPosition;
}
private void GetInput(out float speed)
{
// Read input
float horizontal = CrossPlatformInputManager.GetAxis("Horizontal");
float vertical = CrossPlatformInputManager.GetAxis("Vertical");
bool waswalking = m_IsWalking;
#if !MOBILE_INPUT
// On standalone builds, walk/run speed is modified by a key press.
// keep track of whether or not the character is walking or running
m_IsWalking = !Input.GetKey(KeyCode.LeftShift);
#endif
// set the desired speed to be walking or running
speed = m_IsWalking ? m_WalkSpeed : m_RunSpeed;
m_Input = new Vector2(horizontal, vertical);
// normalize input if it exceeds 1 in combined length:
if (m_Input.sqrMagnitude > 1)
{
m_Input.Normalize();
}
// handle speed change to give an fov kick
// only if the player is going to a run, is running and the fovkick is to be used
if (m_IsWalking != waswalking && m_UseFovKick && m_CharacterController.velocity.sqrMagnitude > 0)
{
StopAllCoroutines();
StartCoroutine(!m_IsWalking ? m_FovKick.FOVKickUp() : m_FovKick.FOVKickDown());
}
}
private void RotateView()
{
m_MouseLook.LookRotation (transform, m_Camera.transform);
}
private void OnControllerColliderHit(ControllerColliderHit hit)
{
Rigidbody body = hit.collider.attachedRigidbody;
//dont move the rigidbody if the character is on top of it
if (m_CollisionFlags == CollisionFlags.Below)
{
return;
}
if (body == null || body.isKinematic)
{
return;
}
body.AddForceAtPosition(m_CharacterController.velocity*0.1f, hit.point, ForceMode.Impulse);
}
}
}
| |
// Copyright 2015, 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.
// Author: [email protected] (Anash P. Oommen)
// Author: Chris Seeley (https://github.com/Narwalter)
using Google.Api.Ads.Common.Util;
using Google.Api.Ads.Dfp.v201505;
using System;
using System.Collections.Generic;
using System.Text;
using DateTime = Google.Api.Ads.Dfp.v201505.DateTime;
namespace Google.Api.Ads.Dfp.Util.v201505 {
/// <summary>
/// A utility class that allows for statements to be constructed in parts.
/// Typical usage is:
/// <code>
/// StatementBuilder statementBuilder = new StatementBuilder()
/// .Where("lastModifiedTime > :yesterday AND type = :type")
/// .OrderBy("name DESC")
/// .Limit(200)
/// .Offset(20)
/// .AddValue("yesterday",
/// DateTimeUtilities.FromDateTime(System.DateTime.Now.AddDays(-1)))
/// .AddValue("type", "Type");
/// Statement statement = statementBuilder.ToStatement();
/// // ...
/// statementBuilder.increaseOffsetBy(20);
/// statement = statementBuilder.ToStatement();
/// </code>
/// </summary>
public class StatementBuilder {
public const int SUGGESTED_PAGE_LIMIT = 500;
private const string SELECT = "SELECT";
private const string FROM = "FROM";
private const string WHERE = "WHERE";
private const string LIMIT = "LIMIT";
private const string OFFSET = "OFFSET";
private const string ORDER_BY = "ORDER BY";
protected string select;
protected string from;
protected string where;
protected int? limit = null;
protected int? offset = null;
protected string orderBy;
/// <summary>
/// The list of query parameters.
/// </summary>
private List<String_ValueMapEntry> valueEntries;
/// <summary>
/// Constructs a statement builder for partial query building.
/// </summary>
public StatementBuilder() {
valueEntries = new List<String_ValueMapEntry>();
}
/// <summary>
/// Removes a keyword from the start of a clause, if it exists.
/// </summary>
/// <param name="clause">The clause to remove the keyword from</param>
/// <param name="keyword">The keyword to remove</param>
/// <returns>The clause with the keyword removed</returns>
private static string RemoveKeyword(string clause, string keyword) {
string formattedKeyword = keyword.Trim() + " ";
return clause.StartsWith(formattedKeyword, true, null)
? clause.Substring(formattedKeyword.Length) : clause;
}
/// <summary>
/// Sets the statement SELECT clause in the form of "a,b".
/// Only necessary for statements being sent to the
/// <see cref="PublisherQueryLanguageService"/>.
/// The "SELECT " keyword will be ignored.
/// </summary>
/// <param name="columns">
/// The statement serlect clause without "SELECT".
/// </param>
/// <returns>The statement builder, for chaining method calls.</returns>
public StatementBuilder Select(String columns) {
PreconditionUtilities.CheckArgumentNotNull(columns, "columns");
this.select = RemoveKeyword(columns, SELECT);
return this;
}
/// <summary>
/// Sets the statement FROM clause in the form of "table".
/// Only necessary for statements being sent to the
/// <see cref="PublisherQueryLanguageService"/>.
/// The "FROM " keyword will be ignored.
/// </summary>
/// <param name="table">The statement from clause without "FROM"</param>
/// <returns>The statement builder, for chaining method calls.</returns>
public StatementBuilder From(String table) {
PreconditionUtilities.CheckArgumentNotNull(table, "table");
this.from = RemoveKeyword(table, FROM);
return this;
}
/// <summary>
/// Sets the statement WHERE clause in the form of
/// <code>
/// "WHERE <condition> {[AND | OR] <condition> ...}"
/// </code>
/// e.g. "a = b OR b = c". The "WHERE " keyword will be ignored.
/// </summary>
/// <param name="conditions">The statement query without "WHERE"</param>
/// <returns>The statement builder, for chaining method calls.</returns>
public StatementBuilder Where(String conditions) {
PreconditionUtilities.CheckArgumentNotNull(conditions, "conditions");
this.where = RemoveKeyword(conditions, WHERE);
return this;
}
/// <summary>
/// Sets the statement LIMIT clause in the form of
/// <code>"LIMIT <count>"</code>
/// </summary>
/// <param name="count">the statement limit</param>
/// <returns>The statement builder, for chaining method calls.</returns>
public StatementBuilder Limit(Int32 count) {
this.limit = count;
return this;
}
/// <summary>
/// Sets the statement OFFSET clause in the form of
/// <code>"OFFSET <count>"</code>
/// </summary>
/// <param name="count">the statement offset</param>
/// <returns>The statement builder, for chaining method calls.</returns>
public StatementBuilder Offset(Int32 count) {
this.offset = count;
return this;
}
/// <summary>
/// Increases the offset by the given amount.
/// </summary>
/// <param name="amount">the amount to increase the offset</param>
/// <returns>The statement builder, for chaining method calls.</returns>
public StatementBuilder IncreaseOffsetBy(Int32 amount) {
if (this.offset == null) {
this.offset = 0;
}
this.offset += amount;
return this;
}
/// <summary>
/// Gets the curent offset
/// </summary>
/// <returns>The current offset</returns>
public int? GetOffset() {
return this.offset;
}
/// <summary>
/// Removes the limit and offset from the query.
/// </summary>
/// <returns>The statement builder, for chaining method calls.</returns>
public StatementBuilder RemoveLimitAndOffset() {
this.offset = null;
this.limit = null;
return this;
}
/// <summary>
/// Sets the statement ORDER BY clause in the form of
/// <code>"ORDER BY <property> [ASC | DESC]"</code>
/// e.g. "type ASC, lastModifiedDateTime DESC".
/// The "ORDER BY " keyword will be ignored.
/// </summary>
/// <param name="orderBy">the statement order by without "ORDER BY"</param>
/// <returns>The statement builder, for chaining method calls.</returns>
public StatementBuilder OrderBy(String orderBy) {
PreconditionUtilities.CheckArgumentNotNull(orderBy, "orderBy");
this.orderBy = RemoveKeyword(orderBy, ORDER_BY);
return this;
}
/// <summary>
/// Adds a new string value to the list of query parameters.
/// </summary>
/// <param name="key">The parameter name.</param>
/// <param name="value">The parameter value.</param>
/// <returns>The statement builder, for chaining method calls.</returns>
public StatementBuilder AddValue(string key, string value) {
TextValue queryValue = new TextValue();
queryValue.value = value;
return AddValue(key, queryValue);
}
/// <summary>
/// Adds a new boolean value to the list of query parameters.
/// </summary>
/// <param name="key">The parameter name.</param>
/// <param name="value">The parameter value.</param>
/// <returns>The statement builder, for chaining method calls.</returns>
public StatementBuilder AddValue(string key, bool value) {
BooleanValue queryValue = new BooleanValue();
queryValue.value = value;
return AddValue(key, queryValue);
}
/// <summary>
/// Adds a new decimal value to the list of query parameters.
/// </summary>
/// <param name="key">The parameter name.</param>
/// <param name="value">The parameter value.</param>
/// <returns>The statement builder, for chaining method calls.</returns>
public StatementBuilder AddValue(string key, decimal value) {
NumberValue queryValue = new NumberValue();
queryValue.value = value.ToString();
return AddValue(key, queryValue);
}
/// <summary>
/// Adds a new DateTime value to the list of query parameters.
/// </summary>
/// <param name="key">The parameter name.</param>
/// <param name="value">The parameter value.</param>
/// <returns>The statement builder, for chaining method calls.</returns>
public StatementBuilder AddValue(string key, DateTime value) {
DateTimeValue queryValue = new DateTimeValue();
queryValue.value = value;
return AddValue(key, queryValue);
}
/// <summary>
/// Adds a new Date value to the list of query parameters.
/// </summary>
/// <param name="key">The parameter name.</param>
/// <param name="value">The parameter value.</param>
/// <returns>The statement builder, for chaining method calls.</returns>
public StatementBuilder AddValue(string key, Date value) {
DateValue queryValue = new DateValue();
queryValue.value = value;
return AddValue(key, queryValue);
}
/// <summary>
/// Adds a new value to the list of query parameters.
/// </summary>
/// <param name="key">The parameter name.</param>
/// <param name="value">The parameter value.</param>
/// <returns>The statement builder, for chaining method calls.</returns>
private StatementBuilder AddValue(string key, Value value) {
String_ValueMapEntry queryValue = new String_ValueMapEntry();
queryValue.key = key;
queryValue.value = value;
valueEntries.Add(queryValue);
return this;
}
private void ValidateQuery() {
if (limit == null && offset != null) {
throw new InvalidOperationException(
DfpErrorMessages.InvalidOffsetAndLimit);
}
}
private String BuildQuery() {
ValidateQuery();
StringBuilder stringBuilder = new StringBuilder();
if (!String.IsNullOrEmpty(select)) {
stringBuilder = stringBuilder.Append(SELECT).Append(" ")
.Append(select).Append(" ");
}
if (!String.IsNullOrEmpty(from)) {
stringBuilder = stringBuilder.Append(FROM).Append(" ")
.Append(from).Append(" ");
}
if (!String.IsNullOrEmpty(where)) {
stringBuilder = stringBuilder.Append(WHERE).Append(" ")
.Append(where).Append(" ");
}
if (!String.IsNullOrEmpty(orderBy)) {
stringBuilder = stringBuilder.Append(ORDER_BY).Append(" ")
.Append(orderBy).Append(" ");
}
if (limit != null) {
stringBuilder = stringBuilder.Append(LIMIT).Append(" ")
.Append(limit).Append(" ");
}
if (offset != null) {
stringBuilder = stringBuilder.Append(OFFSET).Append(" ")
.Append(offset).Append(" ");
}
return stringBuilder.ToString().Trim();
}
/// <summary>
/// Gets the <see cref="Statement"/> representing the state of this
/// statement builder.
/// </summary>
/// <returns>The statement.</returns>
public Statement ToStatement() {
Statement statement = new Statement();
statement.query = BuildQuery();
statement.values = valueEntries.ToArray();
return statement;
}
}
}
| |
// Copyright (c) Cragon. All rights reserved.
namespace GameCloud.Unity.Common
{
using System;
using ProtoBuf;
[Serializable]
[ProtoContract]
public struct EbVector3 : IEquatable<EbVector3>
{
//---------------------------------------------------------------------
[ProtoMember(1)]
public float x;// { get; set; }// Gets or sets the X value.
[ProtoMember(2)]
public float y;// { get; set; }// Gets or sets Y value.
[ProtoMember(3)]
public float z;// { get; set; }// Gets or sets Z value.
public float Length { get { return (float)Math.Sqrt((x * x) + (y * y) + (z * z)); } }
public float Length2 { get { return ((x * x) + (y * y) + (z * z)); } }
//---------------------------------------------------------------------
public EbVector3(float x, float y, float z)
: this()
{
this.x = x;
this.y = y;
this.z = z;
}
//---------------------------------------------------------------------
public static EbVector3 Zero
{
get
{
EbVector3 v3;// = new EbVector3();
v3.x = 0.0f;
v3.y = 0.0f;
v3.z = 0.0f;
return v3;
}
}
//---------------------------------------------------------------------
public static EbVector3 UnitX
{
get
{
EbVector3 v3;// = new EbVector3();
v3.x = 1.0f;
v3.y = 0.0f;
v3.z = 0.0f;
return v3;
}
}
//---------------------------------------------------------------------
public static EbVector3 UnitY
{
get
{
EbVector3 v3;// = new EbVector3();
v3.x = 0.0f;
v3.y = 1.0f;
v3.z = 0.0f;
return v3;
}
}
//---------------------------------------------------------------------
public static EbVector3 UnitZ
{
get
{
EbVector3 v3;// = new EbVector3();
v3.x = 0.0f;
v3.y = 0.0f;
v3.z = 1.0f;
return v3;
}
}
//---------------------------------------------------------------------
public static EbVector3 Unit
{
get
{
EbVector3 v3;// = new EbVector3();
v3.x = 1.0f;
v3.y = 1.0f;
v3.z = 1.0f;
return v3;
}
}
//---------------------------------------------------------------------
public bool Equals(EbVector3 other)
{
return this.x.Equals(other.x) && this.y.Equals(other.y) && this.z.Equals(other.z);
}
//---------------------------------------------------------------------
public override bool Equals(object obj)
{
if (obj is EbVector3)
{
var other = (EbVector3)obj;
return this.Equals(other);
}
return false;
}
//---------------------------------------------------------------------
public override int GetHashCode()
{
int result = this.x.GetHashCode();
result ^= this.y.GetHashCode();
result ^= this.z.GetHashCode();
return result;
}
//---------------------------------------------------------------------
public override string ToString()
{
return string.Format("{0}({1},{2},{3})", base.ToString(), this.x, this.y, this.z);
}
//---------------------------------------------------------------------
public static bool operator ==(EbVector3 coordinate1, EbVector3 coordinate2)
{
return coordinate1.Equals(coordinate2);
}
//---------------------------------------------------------------------
public static bool operator !=(EbVector3 coordinate1, EbVector3 coordinate2)
{
return coordinate1.Equals(coordinate2) == false;
}
//---------------------------------------------------------------------
public static EbVector3 operator +(EbVector3 a, EbVector3 b)
{
EbVector3 v;
v.x = a.x + b.x;
v.y = a.y + b.y;
v.z = a.z + b.z;
return v;
//return new EbVector3 { x = a.x + b.x, y = a.y + b.y, z = a.z + b.z };
}
//---------------------------------------------------------------------
public static EbVector3 operator -(EbVector3 a, EbVector3 b)
{
EbVector3 v;
v.x = a.x - b.x;
v.y = a.y - b.y;
v.z = a.z - b.z;
return v;
//return new EbVector3 { x = a.x - b.x, y = a.y - b.y, z = a.z - b.z };
}
//---------------------------------------------------------------------
public static EbVector3 operator -(EbVector3 a)
{
EbVector3 v;
v.x = -a.x;
v.y = -a.y;
v.z = -a.z;
return v;
//return new EbVector3 { x = -a.x, y = -a.y, z = -a.z };
}
//---------------------------------------------------------------------
public static EbVector3 operator *(EbVector3 a, int b)
{
EbVector3 v;
v.x = a.x * b;
v.y = a.y * b;
v.z = a.z * b;
return v;
//return new EbVector3 { x = a.x * b, y = a.y * b, z = a.z * b };
}
//---------------------------------------------------------------------
public static EbVector3 operator *(EbVector3 a, float b)
{
EbVector3 v;
v.x = a.x * b;
v.y = a.y * b;
v.z = a.z * b;
return v;
//return new EbVector3 { x = a.x * b, y = a.y * b, z = a.z * b };
}
//---------------------------------------------------------------------
public static EbVector3 operator /(EbVector3 a, int b)
{
EbVector3 v;
v.x = a.x / b;
v.y = a.y / b;
v.z = a.z / b;
return v;
//return new EbVector3 { x = a.x / b, y = a.y / b, z = a.z / b };
}
//---------------------------------------------------------------------
public static EbVector3 operator /(EbVector3 a, float b)
{
EbVector3 v;
v.x = a.x / b;
v.y = a.y / b;
v.z = a.z / b;
return v;
//return new EbVector3 { x = a.x / b, y = a.y / b, z = a.z / b };
}
//---------------------------------------------------------------------
public static EbVector3 max(EbVector3 value1, EbVector3 value2)
{
EbVector3 v;
v.x = Math.Max(value1.x, value2.x);
v.y = Math.Max(value1.y, value2.y);
v.z = Math.Max(value1.z, value2.z);
return v;
//return new EbVector3 { x = Math.Max(value1.x, value2.x), y = Math.Max(value1.y, value2.y), z = Math.Max(value1.z, value2.z) };
}
//---------------------------------------------------------------------
public static EbVector3 min(EbVector3 value1, EbVector3 value2)
{
EbVector3 v;
v.x = Math.Min(value1.x, value2.x);
v.y = Math.Min(value1.y, value2.y);
v.z = Math.Min(value1.z, value2.z);
return v;
//return new EbVector3 { x = Math.Min(value1.x, value2.x), y = Math.Min(value1.y, value2.y), z = Math.Min(value1.z, value2.z) };
}
//---------------------------------------------------------------------
public static EbVector3 lerp(EbVector3 from, EbVector3 to, float t)
{
EbVector3 v = from;
v += (to - from) * t;
return v;
}
//---------------------------------------------------------------------
public static float dot(EbVector3 lhs, EbVector3 rhs)
{
return (((lhs.x * rhs.x) + (lhs.y * rhs.y)) + (lhs.z * rhs.z));
}
//---------------------------------------------------------------------
public static EbVector3 cross(EbVector3 v1, EbVector3 v2)
{
EbVector3 result;// = new EbVector3();
result.x = (v1.y * v2.z) - (v1.z * v2.y);
result.y = (v1.z * v2.x) - (v1.x * v2.z);
result.z = (v1.x * v2.y) - (v1.y * v2.x);
return result;
}
//---------------------------------------------------------------------
public static EbVector3 project(EbVector3 vector, EbVector3 on_normal)
{
float num = dot(on_normal, on_normal);
if (num < float.Epsilon)
{
return Zero;
}
return (EbVector3)((on_normal * dot(vector, on_normal)) / num);
}
//---------------------------------------------------------------------
public float getDistance(EbVector3 vector)
{
return (float)Math.Sqrt(Math.Pow(vector.x - this.x, 2) + Math.Pow(vector.y - this.y, 2) + Math.Pow(vector.z - this.z, 2));
}
//---------------------------------------------------------------------
public static float magnitude(EbVector3 a)
{
return (float)Math.Sqrt(((a.x * a.x) + (a.y * a.y)) + (a.z * a.z));
}
//---------------------------------------------------------------------
public void normalize()
{
float num = magnitude(this);
if (num > 1E-05f)
{
this = (EbVector3)(this / num);
}
else
{
this = Zero;
}
}
//---------------------------------------------------------------------
public static EbVector3 normalize(EbVector3 value)
{
float num = magnitude(value);
if (num > 1E-05f)
{
return (EbVector3)(value / num);
}
return Zero;
}
//---------------------------------------------------------------------
public EbVector3 normalized
{
get
{
//= new EbVector3(x, y, z);
EbVector3 v;
v.x = x;
v.y = y;
v.z = z;
float num = magnitude(v);
if (num > 1E-05f)
{
return (EbVector3)(v / num);
}
return Zero;
}
}
}
}
| |
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using Google.Api.Gax;
using Google.Api.Gax.Grpc;
using Google.Cloud.Iam.V1;
using Google.Cloud.PubSub.V1;
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
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.Cloud.PubSub.V1.Snippets
{
/// <summary>Generated snippets</summary>
public class GeneratedPublisherServiceApiClientSnippets
{
/// <summary>Snippet for CreateTopicAsync</summary>
public async Task CreateTopicAsync()
{
// Snippet: CreateTopicAsync(TopicName,CallSettings)
// Additional: CreateTopicAsync(TopicName,CancellationToken)
// Create client
PublisherServiceApiClient publisherServiceApiClient = await PublisherServiceApiClient.CreateAsync();
// Initialize request argument(s)
TopicName name = new TopicName("[PROJECT]", "[TOPIC]");
// Make the request
Topic response = await publisherServiceApiClient.CreateTopicAsync(name);
// End snippet
}
/// <summary>Snippet for CreateTopic</summary>
public void CreateTopic()
{
// Snippet: CreateTopic(TopicName,CallSettings)
// Create client
PublisherServiceApiClient publisherServiceApiClient = PublisherServiceApiClient.Create();
// Initialize request argument(s)
TopicName name = new TopicName("[PROJECT]", "[TOPIC]");
// Make the request
Topic response = publisherServiceApiClient.CreateTopic(name);
// End snippet
}
/// <summary>Snippet for CreateTopicAsync</summary>
public async Task CreateTopicAsync_RequestObject()
{
// Snippet: CreateTopicAsync(Topic,CallSettings)
// Create client
PublisherServiceApiClient publisherServiceApiClient = await PublisherServiceApiClient.CreateAsync();
// Initialize request argument(s)
Topic request = new Topic
{
TopicName = new TopicName("[PROJECT]", "[TOPIC]"),
};
// Make the request
Topic response = await publisherServiceApiClient.CreateTopicAsync(request);
// End snippet
}
/// <summary>Snippet for CreateTopic</summary>
public void CreateTopic_RequestObject()
{
// Snippet: CreateTopic(Topic,CallSettings)
// Create client
PublisherServiceApiClient publisherServiceApiClient = PublisherServiceApiClient.Create();
// Initialize request argument(s)
Topic request = new Topic
{
TopicName = new TopicName("[PROJECT]", "[TOPIC]"),
};
// Make the request
Topic response = publisherServiceApiClient.CreateTopic(request);
// End snippet
}
/// <summary>Snippet for UpdateTopicAsync</summary>
public async Task UpdateTopicAsync_RequestObject()
{
// Snippet: UpdateTopicAsync(UpdateTopicRequest,CallSettings)
// Create client
PublisherServiceApiClient publisherServiceApiClient = await PublisherServiceApiClient.CreateAsync();
// Initialize request argument(s)
UpdateTopicRequest request = new UpdateTopicRequest
{
Topic = new Topic(),
UpdateMask = new FieldMask(),
};
// Make the request
Topic response = await publisherServiceApiClient.UpdateTopicAsync(request);
// End snippet
}
/// <summary>Snippet for UpdateTopic</summary>
public void UpdateTopic_RequestObject()
{
// Snippet: UpdateTopic(UpdateTopicRequest,CallSettings)
// Create client
PublisherServiceApiClient publisherServiceApiClient = PublisherServiceApiClient.Create();
// Initialize request argument(s)
UpdateTopicRequest request = new UpdateTopicRequest
{
Topic = new Topic(),
UpdateMask = new FieldMask(),
};
// Make the request
Topic response = publisherServiceApiClient.UpdateTopic(request);
// End snippet
}
/// <summary>Snippet for PublishAsync</summary>
public async Task PublishAsync()
{
// Snippet: PublishAsync(TopicName,IEnumerable<PubsubMessage>,CallSettings)
// Additional: PublishAsync(TopicName,IEnumerable<PubsubMessage>,CancellationToken)
// Create client
PublisherServiceApiClient publisherServiceApiClient = await PublisherServiceApiClient.CreateAsync();
// Initialize request argument(s)
TopicName topic = new TopicName("[PROJECT]", "[TOPIC]");
IEnumerable<PubsubMessage> messages = new[]
{
new PubsubMessage
{
Data = ByteString.CopyFromUtf8(""),
},
};
// Make the request
PublishResponse response = await publisherServiceApiClient.PublishAsync(topic, messages);
// End snippet
}
/// <summary>Snippet for Publish</summary>
public void Publish()
{
// Snippet: Publish(TopicName,IEnumerable<PubsubMessage>,CallSettings)
// Create client
PublisherServiceApiClient publisherServiceApiClient = PublisherServiceApiClient.Create();
// Initialize request argument(s)
TopicName topic = new TopicName("[PROJECT]", "[TOPIC]");
IEnumerable<PubsubMessage> messages = new[]
{
new PubsubMessage
{
Data = ByteString.CopyFromUtf8(""),
},
};
// Make the request
PublishResponse response = publisherServiceApiClient.Publish(topic, messages);
// End snippet
}
/// <summary>Snippet for PublishAsync</summary>
public async Task PublishAsync_RequestObject()
{
// Snippet: PublishAsync(PublishRequest,CallSettings)
// Create client
PublisherServiceApiClient publisherServiceApiClient = await PublisherServiceApiClient.CreateAsync();
// Initialize request argument(s)
PublishRequest request = new PublishRequest
{
TopicAsTopicName = new TopicName("[PROJECT]", "[TOPIC]"),
Messages = {
new PubsubMessage
{
Data = ByteString.CopyFromUtf8(""),
},
},
};
// Make the request
PublishResponse response = await publisherServiceApiClient.PublishAsync(request);
// End snippet
}
/// <summary>Snippet for Publish</summary>
public void Publish_RequestObject()
{
// Snippet: Publish(PublishRequest,CallSettings)
// Create client
PublisherServiceApiClient publisherServiceApiClient = PublisherServiceApiClient.Create();
// Initialize request argument(s)
PublishRequest request = new PublishRequest
{
TopicAsTopicName = new TopicName("[PROJECT]", "[TOPIC]"),
Messages = {
new PubsubMessage
{
Data = ByteString.CopyFromUtf8(""),
},
},
};
// Make the request
PublishResponse response = publisherServiceApiClient.Publish(request);
// End snippet
}
/// <summary>Snippet for GetTopicAsync</summary>
public async Task GetTopicAsync()
{
// Snippet: GetTopicAsync(TopicName,CallSettings)
// Additional: GetTopicAsync(TopicName,CancellationToken)
// Create client
PublisherServiceApiClient publisherServiceApiClient = await PublisherServiceApiClient.CreateAsync();
// Initialize request argument(s)
TopicName topic = new TopicName("[PROJECT]", "[TOPIC]");
// Make the request
Topic response = await publisherServiceApiClient.GetTopicAsync(topic);
// End snippet
}
/// <summary>Snippet for GetTopic</summary>
public void GetTopic()
{
// Snippet: GetTopic(TopicName,CallSettings)
// Create client
PublisherServiceApiClient publisherServiceApiClient = PublisherServiceApiClient.Create();
// Initialize request argument(s)
TopicName topic = new TopicName("[PROJECT]", "[TOPIC]");
// Make the request
Topic response = publisherServiceApiClient.GetTopic(topic);
// End snippet
}
/// <summary>Snippet for GetTopicAsync</summary>
public async Task GetTopicAsync_RequestObject()
{
// Snippet: GetTopicAsync(GetTopicRequest,CallSettings)
// Create client
PublisherServiceApiClient publisherServiceApiClient = await PublisherServiceApiClient.CreateAsync();
// Initialize request argument(s)
GetTopicRequest request = new GetTopicRequest
{
TopicAsTopicName = new TopicName("[PROJECT]", "[TOPIC]"),
};
// Make the request
Topic response = await publisherServiceApiClient.GetTopicAsync(request);
// End snippet
}
/// <summary>Snippet for GetTopic</summary>
public void GetTopic_RequestObject()
{
// Snippet: GetTopic(GetTopicRequest,CallSettings)
// Create client
PublisherServiceApiClient publisherServiceApiClient = PublisherServiceApiClient.Create();
// Initialize request argument(s)
GetTopicRequest request = new GetTopicRequest
{
TopicAsTopicName = new TopicName("[PROJECT]", "[TOPIC]"),
};
// Make the request
Topic response = publisherServiceApiClient.GetTopic(request);
// End snippet
}
/// <summary>Snippet for ListTopicsAsync</summary>
public async Task ListTopicsAsync()
{
// Snippet: ListTopicsAsync(ProjectName,string,int?,CallSettings)
// Create client
PublisherServiceApiClient publisherServiceApiClient = await PublisherServiceApiClient.CreateAsync();
// Initialize request argument(s)
ProjectName project = new ProjectName("[PROJECT]");
// Make the request
PagedAsyncEnumerable<ListTopicsResponse, Topic> response =
publisherServiceApiClient.ListTopicsAsync(project);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Topic item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListTopicsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Topic item in page)
{
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Topic> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Topic item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListTopics</summary>
public void ListTopics()
{
// Snippet: ListTopics(ProjectName,string,int?,CallSettings)
// Create client
PublisherServiceApiClient publisherServiceApiClient = PublisherServiceApiClient.Create();
// Initialize request argument(s)
ProjectName project = new ProjectName("[PROJECT]");
// Make the request
PagedEnumerable<ListTopicsResponse, Topic> response =
publisherServiceApiClient.ListTopics(project);
// Iterate over all response items, lazily performing RPCs as required
foreach (Topic item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListTopicsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Topic item in page)
{
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Topic> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Topic item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListTopicsAsync</summary>
public async Task ListTopicsAsync_RequestObject()
{
// Snippet: ListTopicsAsync(ListTopicsRequest,CallSettings)
// Create client
PublisherServiceApiClient publisherServiceApiClient = await PublisherServiceApiClient.CreateAsync();
// Initialize request argument(s)
ListTopicsRequest request = new ListTopicsRequest
{
ProjectAsProjectName = new ProjectName("[PROJECT]"),
};
// Make the request
PagedAsyncEnumerable<ListTopicsResponse, Topic> response =
publisherServiceApiClient.ListTopicsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Topic item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListTopicsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Topic item in page)
{
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Topic> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Topic item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListTopics</summary>
public void ListTopics_RequestObject()
{
// Snippet: ListTopics(ListTopicsRequest,CallSettings)
// Create client
PublisherServiceApiClient publisherServiceApiClient = PublisherServiceApiClient.Create();
// Initialize request argument(s)
ListTopicsRequest request = new ListTopicsRequest
{
ProjectAsProjectName = new ProjectName("[PROJECT]"),
};
// Make the request
PagedEnumerable<ListTopicsResponse, Topic> response =
publisherServiceApiClient.ListTopics(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (Topic item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListTopicsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Topic item in page)
{
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Topic> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Topic item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListTopicSubscriptionsAsync</summary>
public async Task ListTopicSubscriptionsAsync()
{
// Snippet: ListTopicSubscriptionsAsync(TopicName,string,int?,CallSettings)
// Create client
PublisherServiceApiClient publisherServiceApiClient = await PublisherServiceApiClient.CreateAsync();
// Initialize request argument(s)
TopicName topic = new TopicName("[PROJECT]", "[TOPIC]");
// Make the request
PagedAsyncEnumerable<ListTopicSubscriptionsResponse, SubscriptionName> response =
publisherServiceApiClient.ListTopicSubscriptionsAsync(topic);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((SubscriptionName item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListTopicSubscriptionsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (SubscriptionName item in page)
{
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<SubscriptionName> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (SubscriptionName item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListTopicSubscriptions</summary>
public void ListTopicSubscriptions()
{
// Snippet: ListTopicSubscriptions(TopicName,string,int?,CallSettings)
// Create client
PublisherServiceApiClient publisherServiceApiClient = PublisherServiceApiClient.Create();
// Initialize request argument(s)
TopicName topic = new TopicName("[PROJECT]", "[TOPIC]");
// Make the request
PagedEnumerable<ListTopicSubscriptionsResponse, SubscriptionName> response =
publisherServiceApiClient.ListTopicSubscriptions(topic);
// Iterate over all response items, lazily performing RPCs as required
foreach (SubscriptionName item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListTopicSubscriptionsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (SubscriptionName item in page)
{
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<SubscriptionName> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (SubscriptionName item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListTopicSubscriptionsAsync</summary>
public async Task ListTopicSubscriptionsAsync_RequestObject()
{
// Snippet: ListTopicSubscriptionsAsync(ListTopicSubscriptionsRequest,CallSettings)
// Create client
PublisherServiceApiClient publisherServiceApiClient = await PublisherServiceApiClient.CreateAsync();
// Initialize request argument(s)
ListTopicSubscriptionsRequest request = new ListTopicSubscriptionsRequest
{
TopicAsTopicName = new TopicName("[PROJECT]", "[TOPIC]"),
};
// Make the request
PagedAsyncEnumerable<ListTopicSubscriptionsResponse, SubscriptionName> response =
publisherServiceApiClient.ListTopicSubscriptionsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((SubscriptionName item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListTopicSubscriptionsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (SubscriptionName item in page)
{
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<SubscriptionName> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (SubscriptionName item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListTopicSubscriptions</summary>
public void ListTopicSubscriptions_RequestObject()
{
// Snippet: ListTopicSubscriptions(ListTopicSubscriptionsRequest,CallSettings)
// Create client
PublisherServiceApiClient publisherServiceApiClient = PublisherServiceApiClient.Create();
// Initialize request argument(s)
ListTopicSubscriptionsRequest request = new ListTopicSubscriptionsRequest
{
TopicAsTopicName = new TopicName("[PROJECT]", "[TOPIC]"),
};
// Make the request
PagedEnumerable<ListTopicSubscriptionsResponse, SubscriptionName> response =
publisherServiceApiClient.ListTopicSubscriptions(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (SubscriptionName item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListTopicSubscriptionsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (SubscriptionName item in page)
{
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<SubscriptionName> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (SubscriptionName item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for DeleteTopicAsync</summary>
public async Task DeleteTopicAsync()
{
// Snippet: DeleteTopicAsync(TopicName,CallSettings)
// Additional: DeleteTopicAsync(TopicName,CancellationToken)
// Create client
PublisherServiceApiClient publisherServiceApiClient = await PublisherServiceApiClient.CreateAsync();
// Initialize request argument(s)
TopicName topic = new TopicName("[PROJECT]", "[TOPIC]");
// Make the request
await publisherServiceApiClient.DeleteTopicAsync(topic);
// End snippet
}
/// <summary>Snippet for DeleteTopic</summary>
public void DeleteTopic()
{
// Snippet: DeleteTopic(TopicName,CallSettings)
// Create client
PublisherServiceApiClient publisherServiceApiClient = PublisherServiceApiClient.Create();
// Initialize request argument(s)
TopicName topic = new TopicName("[PROJECT]", "[TOPIC]");
// Make the request
publisherServiceApiClient.DeleteTopic(topic);
// End snippet
}
/// <summary>Snippet for DeleteTopicAsync</summary>
public async Task DeleteTopicAsync_RequestObject()
{
// Snippet: DeleteTopicAsync(DeleteTopicRequest,CallSettings)
// Create client
PublisherServiceApiClient publisherServiceApiClient = await PublisherServiceApiClient.CreateAsync();
// Initialize request argument(s)
DeleteTopicRequest request = new DeleteTopicRequest
{
TopicAsTopicName = new TopicName("[PROJECT]", "[TOPIC]"),
};
// Make the request
await publisherServiceApiClient.DeleteTopicAsync(request);
// End snippet
}
/// <summary>Snippet for DeleteTopic</summary>
public void DeleteTopic_RequestObject()
{
// Snippet: DeleteTopic(DeleteTopicRequest,CallSettings)
// Create client
PublisherServiceApiClient publisherServiceApiClient = PublisherServiceApiClient.Create();
// Initialize request argument(s)
DeleteTopicRequest request = new DeleteTopicRequest
{
TopicAsTopicName = new TopicName("[PROJECT]", "[TOPIC]"),
};
// Make the request
publisherServiceApiClient.DeleteTopic(request);
// End snippet
}
/// <summary>Snippet for SetIamPolicyAsync</summary>
public async Task SetIamPolicyAsync()
{
// Snippet: SetIamPolicyAsync(string,Policy,CallSettings)
// Additional: SetIamPolicyAsync(string,Policy,CancellationToken)
// Create client
PublisherServiceApiClient publisherServiceApiClient = await PublisherServiceApiClient.CreateAsync();
// Initialize request argument(s)
string formattedResource = new TopicName("[PROJECT]", "[TOPIC]").ToString();
Policy policy = new Policy();
// Make the request
Policy response = await publisherServiceApiClient.SetIamPolicyAsync(formattedResource, policy);
// End snippet
}
/// <summary>Snippet for SetIamPolicy</summary>
public void SetIamPolicy()
{
// Snippet: SetIamPolicy(string,Policy,CallSettings)
// Create client
PublisherServiceApiClient publisherServiceApiClient = PublisherServiceApiClient.Create();
// Initialize request argument(s)
string formattedResource = new TopicName("[PROJECT]", "[TOPIC]").ToString();
Policy policy = new Policy();
// Make the request
Policy response = publisherServiceApiClient.SetIamPolicy(formattedResource, policy);
// End snippet
}
/// <summary>Snippet for SetIamPolicyAsync</summary>
public async Task SetIamPolicyAsync_RequestObject()
{
// Snippet: SetIamPolicyAsync(SetIamPolicyRequest,CallSettings)
// Create client
PublisherServiceApiClient publisherServiceApiClient = await PublisherServiceApiClient.CreateAsync();
// Initialize request argument(s)
SetIamPolicyRequest request = new SetIamPolicyRequest
{
Resource = new TopicName("[PROJECT]", "[TOPIC]").ToString(),
Policy = new Policy(),
};
// Make the request
Policy response = await publisherServiceApiClient.SetIamPolicyAsync(request);
// End snippet
}
/// <summary>Snippet for SetIamPolicy</summary>
public void SetIamPolicy_RequestObject()
{
// Snippet: SetIamPolicy(SetIamPolicyRequest,CallSettings)
// Create client
PublisherServiceApiClient publisherServiceApiClient = PublisherServiceApiClient.Create();
// Initialize request argument(s)
SetIamPolicyRequest request = new SetIamPolicyRequest
{
Resource = new TopicName("[PROJECT]", "[TOPIC]").ToString(),
Policy = new Policy(),
};
// Make the request
Policy response = publisherServiceApiClient.SetIamPolicy(request);
// End snippet
}
/// <summary>Snippet for GetIamPolicyAsync</summary>
public async Task GetIamPolicyAsync()
{
// Snippet: GetIamPolicyAsync(string,CallSettings)
// Additional: GetIamPolicyAsync(string,CancellationToken)
// Create client
PublisherServiceApiClient publisherServiceApiClient = await PublisherServiceApiClient.CreateAsync();
// Initialize request argument(s)
string formattedResource = new TopicName("[PROJECT]", "[TOPIC]").ToString();
// Make the request
Policy response = await publisherServiceApiClient.GetIamPolicyAsync(formattedResource);
// End snippet
}
/// <summary>Snippet for GetIamPolicy</summary>
public void GetIamPolicy()
{
// Snippet: GetIamPolicy(string,CallSettings)
// Create client
PublisherServiceApiClient publisherServiceApiClient = PublisherServiceApiClient.Create();
// Initialize request argument(s)
string formattedResource = new TopicName("[PROJECT]", "[TOPIC]").ToString();
// Make the request
Policy response = publisherServiceApiClient.GetIamPolicy(formattedResource);
// End snippet
}
/// <summary>Snippet for GetIamPolicyAsync</summary>
public async Task GetIamPolicyAsync_RequestObject()
{
// Snippet: GetIamPolicyAsync(GetIamPolicyRequest,CallSettings)
// Create client
PublisherServiceApiClient publisherServiceApiClient = await PublisherServiceApiClient.CreateAsync();
// Initialize request argument(s)
GetIamPolicyRequest request = new GetIamPolicyRequest
{
Resource = new TopicName("[PROJECT]", "[TOPIC]").ToString(),
};
// Make the request
Policy response = await publisherServiceApiClient.GetIamPolicyAsync(request);
// End snippet
}
/// <summary>Snippet for GetIamPolicy</summary>
public void GetIamPolicy_RequestObject()
{
// Snippet: GetIamPolicy(GetIamPolicyRequest,CallSettings)
// Create client
PublisherServiceApiClient publisherServiceApiClient = PublisherServiceApiClient.Create();
// Initialize request argument(s)
GetIamPolicyRequest request = new GetIamPolicyRequest
{
Resource = new TopicName("[PROJECT]", "[TOPIC]").ToString(),
};
// Make the request
Policy response = publisherServiceApiClient.GetIamPolicy(request);
// End snippet
}
/// <summary>Snippet for TestIamPermissionsAsync</summary>
public async Task TestIamPermissionsAsync()
{
// Snippet: TestIamPermissionsAsync(string,IEnumerable<string>,CallSettings)
// Additional: TestIamPermissionsAsync(string,IEnumerable<string>,CancellationToken)
// Create client
PublisherServiceApiClient publisherServiceApiClient = await PublisherServiceApiClient.CreateAsync();
// Initialize request argument(s)
string formattedResource = new TopicName("[PROJECT]", "[TOPIC]").ToString();
IEnumerable<string> permissions = new List<string>();
// Make the request
TestIamPermissionsResponse response = await publisherServiceApiClient.TestIamPermissionsAsync(formattedResource, permissions);
// End snippet
}
/// <summary>Snippet for TestIamPermissions</summary>
public void TestIamPermissions()
{
// Snippet: TestIamPermissions(string,IEnumerable<string>,CallSettings)
// Create client
PublisherServiceApiClient publisherServiceApiClient = PublisherServiceApiClient.Create();
// Initialize request argument(s)
string formattedResource = new TopicName("[PROJECT]", "[TOPIC]").ToString();
IEnumerable<string> permissions = new List<string>();
// Make the request
TestIamPermissionsResponse response = publisherServiceApiClient.TestIamPermissions(formattedResource, permissions);
// End snippet
}
/// <summary>Snippet for TestIamPermissionsAsync</summary>
public async Task TestIamPermissionsAsync_RequestObject()
{
// Snippet: TestIamPermissionsAsync(TestIamPermissionsRequest,CallSettings)
// Create client
PublisherServiceApiClient publisherServiceApiClient = await PublisherServiceApiClient.CreateAsync();
// Initialize request argument(s)
TestIamPermissionsRequest request = new TestIamPermissionsRequest
{
Resource = new TopicName("[PROJECT]", "[TOPIC]").ToString(),
Permissions = { },
};
// Make the request
TestIamPermissionsResponse response = await publisherServiceApiClient.TestIamPermissionsAsync(request);
// End snippet
}
/// <summary>Snippet for TestIamPermissions</summary>
public void TestIamPermissions_RequestObject()
{
// Snippet: TestIamPermissions(TestIamPermissionsRequest,CallSettings)
// Create client
PublisherServiceApiClient publisherServiceApiClient = PublisherServiceApiClient.Create();
// Initialize request argument(s)
TestIamPermissionsRequest request = new TestIamPermissionsRequest
{
Resource = new TopicName("[PROJECT]", "[TOPIC]").ToString(),
Permissions = { },
};
// Make the request
TestIamPermissionsResponse response = publisherServiceApiClient.TestIamPermissions(request);
// End snippet
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Globalization;
using System.IO;
using System.Text;
using System.Diagnostics;
using System.Threading;
using System.Windows.Forms;
using OpenLiveWriter.CoreServices.Threading;
using Timer = System.Windows.Forms.Timer;
using OpenLiveWriter.Interop.Com;
using OpenLiveWriter.Interop.Windows;
using OpenLiveWriter.BrowserControl;
using mshtml;
namespace OpenLiveWriter.CoreServices
{
public class HtmlScreenCaptureCore
{
public HtmlScreenCaptureCore(Uri url, int contentWidth)
{
_htmlUrl = UrlHelper.SafeToAbsoluteUri(url);
_contentWidth = contentWidth;
}
public HtmlScreenCaptureCore(string htmlContent, int contentWidth)
{
_htmlContent = htmlContent;
_contentWidth = contentWidth;
}
public bool ShowWaitCursor
{
get { return _showWaitCursor; }
set { _showWaitCursor = value; }
}
private string[] _ids;
public string[] Ids
{
get { return _ids; }
set { _ids = value; }
}
public int MaximumHeight
{
get { return _maximumHeight; }
set { _maximumHeight = value; }
}
public event HtmlDocumentAvailableHandlerCore HtmlDocumentAvailable;
public event HtmlScreenCaptureAvailableHandlerCore HtmlScreenCaptureAvailable;
public ElementCaptureProperties GetElementCaptureProperties(string id)
{
return _elementCaptureProperties[id];
}
public Bitmap CaptureHtml(int timeoutMs)
{
if (timeoutMs <= 0)
throw new ArgumentException("You must specify a timeout value greater than 0", "timeoutMs");
// set the timeout
_timeoutMs = timeoutMs;
ConditionVariable signal = new ConditionVariable();
// open a new form on a background, STA thread
Thread formThread = ThreadHelper.NewThread(new ThreadStart(delegate { ThreadMain(signal, _ids); }), "BrowserScreenCaptureForm", true, true, true);
formThread.Start();
// wait for it to complete or timeout
using (WaitCursor waitCursor = ShowWaitCursor ? new WaitCursor() : null)
{
signal.WaitForSignal(30000); // this should actually return very quickly
if (formThread.Join(_timeoutMs))
{
// throw an exception if one occurred
if (_exception != null)
throw _exception;
// return the captured bitmap
return (Bitmap)Bitmap.FromStream(StreamHelper.AsStream(_capturedBitmap));
}
else
{
// timed out, make sure we tell the form to close if
// it hasn't already
_applicationContext.CloseFormAndExit();
// return null
return null;
}
}
}
public static Bitmap TakeSnapshot(IViewObject obj, int width, int height)
{
// draw the view on a Bitmap
IntPtr hBitmapDC = IntPtr.Zero;
IntPtr hBitmap = IntPtr.Zero;
IntPtr hPreviousObject = IntPtr.Zero;
Bitmap bitmap = null;
try
{
// create GDI objects used for drawing
hBitmapDC = Gdi32.CreateCompatibleDC(User32.GetDC(IntPtr.Zero));
hBitmap = Gdi32.CreateCompatibleBitmap(User32.GetDC(IntPtr.Zero), width, height);
hPreviousObject = Gdi32.SelectObject(hBitmapDC, hBitmap);
RECT sourceRect = new RECT();
sourceRect.right = width;
sourceRect.bottom = height;
// draw the bitmap
obj.Draw(DVASPECT.CONTENT, 1, IntPtr.Zero, IntPtr.Zero, User32.GetDC(IntPtr.Zero),
hBitmapDC, ref sourceRect, IntPtr.Zero, IntPtr.Zero, 0);
// convert to a managed bitmap
bitmap = Bitmap.FromHbitmap(hBitmap);
}
finally
{
// restore previous object
Gdi32.SelectObject(hBitmapDC, hPreviousObject);
if (hBitmapDC != IntPtr.Zero)
Gdi32.DeleteDC(hBitmapDC);
if (hBitmap != IntPtr.Zero)
Gdi32.DeleteObject(hBitmap);
}
return bitmap;
}
[STAThread]
private void ThreadMain(ConditionVariable signal, string[] ids)
{
HtmlScreenCaptureForm form = null;
try
{
// housekeeping initialization
Application.OleRequired();
// create the form and execute the capture
form = new HtmlScreenCaptureForm(this);
this.Ids = ids;
form.Ids = ids;
form.DoCapture();
// Create and run the form
_applicationContext = new FormLifetimeApplicationContext(form);
signal.Signal();
Application.Run(_applicationContext);
// propragate exceptions that happened inside the AppContext
if (_applicationContext.Exception != null)
throw _applicationContext.Exception;
}
catch (Exception ex)
{
_exception = ex;
}
finally
{
if (form != null)
form.Close();
}
}
internal string HtmlUrl
{
get { return _htmlUrl; }
}
internal string HtmlContent
{
get { return _htmlContent; }
}
internal int ContentWidth
{
get { return _contentWidth; }
}
internal int TimeoutMs
{
get { return _timeoutMs; }
}
internal void FireHtmlDocumentAvailable(HtmlDocumentAvailableEventArgsCore e)
{
if (HtmlDocumentAvailable != null)
HtmlDocumentAvailable(this, e);
}
internal void FireHtmlScreenCaptureAvailable(HtmlScreenCaptureAvailableEventArgsCore e)
{
if (HtmlScreenCaptureAvailable != null)
HtmlScreenCaptureAvailable(this, e);
}
internal void SetCapturedBitmap(Bitmap bitmap)
{
MemoryStream ms = new MemoryStream();
bitmap.Save(ms, ImageFormat.Bmp);
ms.Seek(0, SeekOrigin.Begin);
_capturedBitmap = ms.ToArray();
}
internal void SetElementCaptureProperties(string id, Bitmap bitmap, Color backgroundColor, Padding padding)
{
byte[] bytes = null;
if (bitmap != null)
{
MemoryStream ms = new MemoryStream();
bitmap.Save(ms, ImageFormat.Bmp);
ms.Seek(0, SeekOrigin.Begin);
bytes = ms.ToArray();
}
_elementCaptureProperties[id] = new ElementCaptureProperties(bytes, backgroundColor, padding);
}
internal void SetException(Exception exception)
{
_exception = exception;
}
// capture parameters
private int _maximumHeight = -1;
private bool _showWaitCursor = true;
private string _htmlUrl;
private string _htmlContent;
private int _contentWidth;
private int _timeoutMs;
// successfully captured bitmap
private byte[] _capturedBitmap;
private Dictionary<string, ElementCaptureProperties> _elementCaptureProperties = new Dictionary<string, ElementCaptureProperties>();
// error that occured during processing
private Exception _exception;
private FormLifetimeApplicationContext _applicationContext;
}
public class ElementCaptureProperties
{
private byte[] _capturedBitmap;
public Padding Padding { get; set; }
public ElementCaptureProperties(byte[] capturedBitmap, Color backgroundColor, Padding padding)
{
_capturedBitmap = capturedBitmap;
BackgroundColor = backgroundColor;
Padding = padding;
}
public Color BackgroundColor { get; private set; }
public Bitmap Bitmap
{
get
{
return _capturedBitmap == null
? null
: (Bitmap)Bitmap.FromStream(StreamHelper.AsStream(_capturedBitmap));
}
}
}
public class HtmlScreenCaptureAvailableEventArgsCore : EventArgs
{
public HtmlScreenCaptureAvailableEventArgsCore(Bitmap bitmap)
{
_bitmap = bitmap;
}
public Bitmap Bitmap
{
get { return _bitmap; }
}
private Bitmap _bitmap;
public bool CaptureCompleted
{
get { return _captureCompletedBytes; }
set { _captureCompletedBytes = value; }
}
private bool _captureCompletedBytes = true;
}
public class HtmlDocumentAvailableEventArgsCore : EventArgs
{
public HtmlDocumentAvailableEventArgsCore(object document)
{
_document = document;
}
public object Document
{
get { return _document; }
}
private object _document;
public bool DocumentReady
{
get { return _documentReady; }
set { _documentReady = value; }
}
private bool _documentReady = true;
}
public delegate void HtmlScreenCaptureAvailableHandlerCore(object sender, HtmlScreenCaptureAvailableEventArgsCore e);
public delegate void HtmlDocumentAvailableHandlerCore(object sender, HtmlDocumentAvailableEventArgsCore e);
/// <summary>
/// Special application context that will mirror the lifetime of a Form
/// without calling Form.Show (as the standard implementation of
/// ApplicationContext does)
/// </summary>
internal class FormLifetimeApplicationContext : ApplicationContext
{
public FormLifetimeApplicationContext(Form form)
{
_form = form;
if (form.IsHandleCreated)
_hwnd = form.Handle;
else
form.HandleCreated += delegate { _hwnd = form.Handle; };
_form.Closed += new EventHandler(form_Closed);
}
public Exception Exception
{
get { return _exception; }
}
private Exception _exception;
public void CloseFormAndExit()
{
// notify the form that it should close (call using PostMessage b/c
// this call may come from another thread). This will trigger the
// Form.Closed event and cleanup will proceed from there
if (_hwnd != IntPtr.Zero)
User32.PostMessage(_hwnd, WM.CLOSE, UIntPtr.Zero, IntPtr.Zero);
}
private void form_Closed(object sender, EventArgs e)
{
try
{
// safely ensure form is disposed
try { _form.Dispose(); }
catch { }
}
catch (Exception ex)
{
_exception = ex;
}
finally
{
ExitThread();
}
}
private Form _form;
private IntPtr _hwnd;
}
internal class HtmlScreenCaptureForm : BaseForm
{
public HtmlScreenCaptureForm(HtmlScreenCaptureCore htmlScreenCaptureCore)
{
// save reference to parent object
_htmlScreenCaptureCore = htmlScreenCaptureCore;
// set the timeout time
_timeoutTime = DateTime.Now.AddMilliseconds(_htmlScreenCaptureCore.TimeoutMs);
// create and add the underlying browser control
_browserControl = new ExplorerBrowserControl();
_browserControl.Silent = true;
Controls.Add(_browserControl);
}
public void DoCapture()
{
// show the form w/o activating then make it invisible
User32.SetWindowPos(Handle, HWND.BOTTOM, -1, -1, 1, 1, SWP.NOACTIVATE);
Visible = false;
// determine the url used for navigation
string navigateUrl;
if (_htmlScreenCaptureCore.HtmlUrl != null)
{
navigateUrl = _htmlScreenCaptureCore.HtmlUrl;
}
else
{
_contentFile = TempFileManager.Instance.CreateTempFile("content.htm");
using (TextWriter textWriter = new StreamWriter(_contentFile, false, Encoding.UTF8))
{
String html = _htmlScreenCaptureCore.HtmlContent;
//add the "Mark Of The Web" so that the HTML will execute in the Internet Zone
//otherwise, it will execute in the Local Machine zone, which won't allow JavaScript
//or object/embed tags.
html = HTMLDocumentHelper.AddMarkOfTheWeb(html, "about:internet");
textWriter.Write(html);
}
navigateUrl = _contentFile;
}
// navigate to the file then wait for document complete for further processing
_browserControl.DocumentComplete += new BrowserDocumentEventHandler(_browserControl_DocumentComplete);
_browserControl.Navigate(navigateUrl);
}
private void _browserControl_DocumentComplete(object sender, BrowserDocumentEventArgs e)
{
Timer timer = null;
try
{
// unsubscribe from the event
_browserControl.DocumentComplete -= new BrowserDocumentEventHandler(_browserControl_DocumentComplete);
// get the document
IHTMLDocument2 document = _browserControl.Document as IHTMLDocument2;
// eliminate borders, scroll bars, and margins
IHTMLElement element = document.body;
element.style.borderStyle = "none";
IHTMLBodyElement body = element as IHTMLBodyElement;
body.scroll = "no";
body.leftMargin = 0;
body.rightMargin = 0;
body.topMargin = 0;
body.bottomMargin = 0;
// set the width and height of the browser control to the correct
// values for the snapshot
// width specified by the caller
_browserControl.Width = _htmlScreenCaptureCore.ContentWidth;
if (_htmlScreenCaptureCore.MaximumHeight > 0)
_browserControl.Height = _htmlScreenCaptureCore.MaximumHeight;
else
{
// height of the content calculated based on this width
IHTMLElement2 element2 = element as IHTMLElement2;
_browserControl.Height = element2.scrollHeight;
}
// release UI thread to load the video thumbnail on screen
// (the Tick may need to fire more than once to allow enough
// time and message processing for an embedded object to
// be fully initialized)
timer = new Timer();
timer.Interval = WAIT_INTERVAL;
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
}
catch (Exception ex)
{
_htmlScreenCaptureCore.SetException(ex);
CleanupAndExit(timer);
}
}
/// <summary>
/// Prevents asserts that happen within timer_Tick from going bonkers; since
/// they can happen reentrantly, you can end up with hundreds of assert windows.
/// </summary>
private bool reentrant = false;
private void timer_Tick(object sender, EventArgs e)
{
if (reentrant)
return;
reentrant = true;
Timer timer = null;
try
{
timer = sender as Timer;
IHTMLDocument2 document = _browserControl.Document as IHTMLDocument2;
// make sure the document is ready
if (!DocumentReady(document))
{
if (TimedOut)
CleanupAndExit(timer);
return;
}
if (Ids != null)
{
IHTMLDocument3 doc3 = document as IHTMLDocument3;
foreach (string elementId in Ids)
{
IHTMLStyle3 style3 = (IHTMLStyle3)(doc3.getElementById(elementId)).style;
style3.wordWrap = "normal";
}
int originalWidth = _browserControl.Width;
int originalHeight = _browserControl.Height;
foreach (string elementId in Ids)
{
try
{
IHTMLElement element = doc3.getElementById(elementId);
_browserControl.Height = element.offsetHeight + 2 + 2;
element.scrollIntoView(true);
Padding padding = HTMLElementHelper.PaddingInPixels(element);
Color backgroundColor = HTMLColorHelper.GetBackgroundColor(element, true, null, Color.White);
using (Bitmap elementBitmap = GetElementPreviewImage(doc3, element, _browserControl.Width, _browserControl.Height))
{
_htmlScreenCaptureCore.SetElementCaptureProperties(elementId, elementBitmap, backgroundColor, padding);
}
}
catch (Exception ex)
{
Trace.Fail("Failed to capture element " + elementId + ": " + ex);
}
}
// Restore the browser control size
_browserControl.Width = originalWidth;
_browserControl.Height = originalHeight;
}
// fire event to see if the Bitmap is ready
using (Bitmap bitmap = HtmlScreenCaptureCore.TakeSnapshot((IViewObject)_browserControl.Document, _browserControl.Width, _browserControl.Height))
{
HtmlScreenCaptureAvailableEventArgsCore ea = new HtmlScreenCaptureAvailableEventArgsCore(bitmap);
_htmlScreenCaptureCore.FireHtmlScreenCaptureAvailable(ea);
if (ea.CaptureCompleted)
{
// provide the bitmap to our parent object
_htmlScreenCaptureCore.SetCapturedBitmap(bitmap);
//bitmap.Save(@"c:\temp\captured.bmp");
// exit
CleanupAndExit(timer);
}
else if (TimedOut) // if we have timed out then exit
{
CleanupAndExit(timer);
}
// otherwise just let the Timer call us again
// at the next interval...
}
}
catch (Exception ex)
{
_htmlScreenCaptureCore.SetException(ex);
CleanupAndExit(timer);
}
finally
{
reentrant = false;
}
}
private void CleanupAndExit(Timer timer)
{
// safely dispose timer
try
{
if (timer != null)
{
timer.Tick -= new EventHandler(timer_Tick);
timer.Stop();
timer.Dispose();
}
}
catch (Exception ex)
{
Trace.Fail("Unexpected exception disposing exception: " + ex.ToString());
}
// close the form
Close();
}
private string[] _ids;
public string[] Ids
{
get { return _ids; }
set { _ids = value; }
}
private bool DocumentReady(IHTMLDocument2 document)
{
// check for a browser that is still busy
if (_browserControl.Browser.Busy)
return false;
// check for embeds that are not ready
foreach (object embedObject in document.embeds)
{
DispHTMLEmbed dispEmbed = embedObject as DispHTMLEmbed;
if (dispEmbed.readyState.ToString() != "complete")
return false;
}
// fire documented completed hook to clients and return result
HtmlDocumentAvailableEventArgsCore ea = new HtmlDocumentAvailableEventArgsCore(document);
_htmlScreenCaptureCore.FireHtmlDocumentAvailable(ea);
return ea.DocumentReady;
}
private static Bitmap GetElementPreviewImage(IHTMLDocument3 doc3, IHTMLElement element, int snapshotWidth, int snapshotHeight)
{
try
{
// @RIBBON TODO: Need to make this work for RTL as well.
IDisplayServices displayServices = ((IDisplayServices)doc3);
element.scrollIntoView(true);
tagPOINT offset = new tagPOINT();
offset.x = 0;
offset.y = 0;
displayServices.TransformPoint(ref offset, _COORD_SYSTEM.COORD_SYSTEM_CONTENT, _COORD_SYSTEM.COORD_SYSTEM_GLOBAL, element);
using (Bitmap snapshotAfter = HtmlScreenCaptureCore.TakeSnapshot((IViewObject)doc3, snapshotWidth, snapshotHeight))
{
//snapshotAfter.Save(@"c:\temp\snapshot" + element.id + ".bmp");
Rectangle elementRect;
elementRect = new Rectangle(Math.Max(2, offset.x), 2, Math.Min(element.offsetWidth, element.offsetParent.offsetWidth), element.offsetHeight);
if (element.offsetWidth <= 0 || element.offsetHeight <= 0)
return null;
Bitmap cropped = ImageHelper2.CropBitmap(snapshotAfter, elementRect);
//cropped.Save(@"c:\temp\snapshot" + element.id + ".cropped.bmp");
return cropped;
}
}
catch (Exception ex)
{
Trace.Fail("Failed to get element preview image for id " + element.id + ": " + ex);
return null;
}
}
private bool TimedOut
{
get
{
return DateTime.Now > _timeoutTime;
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (_contentFile != null && File.Exists(_contentFile))
{
try { File.Delete(_contentFile); }
catch { }
}
try { _browserControl.Dispose(); }
catch { }
}
base.Dispose(disposing);
}
private ExplorerBrowserControl _browserControl;
private string _contentFile;
private HtmlScreenCaptureCore _htmlScreenCaptureCore;
private DateTime _timeoutTime;
private const int WAIT_INTERVAL = 100;
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvc = Google.Ads.GoogleAds.V9.Common;
using gagve = Google.Ads.GoogleAds.V9.Enums;
using gagvr = Google.Ads.GoogleAds.V9.Resources;
using gaxgrpc = Google.Api.Gax.Grpc;
using gr = Google.Rpc;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using NUnit.Framework;
using Google.Ads.GoogleAds.V9.Services;
namespace Google.Ads.GoogleAds.Tests.V9.Services
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedAdGroupServiceClientTest
{
[Category("Autogenerated")][Test]
public void GetAdGroupRequestObject()
{
moq::Mock<AdGroupService.AdGroupServiceClient> mockGrpcClient = new moq::Mock<AdGroupService.AdGroupServiceClient>(moq::MockBehavior.Strict);
GetAdGroupRequest request = new GetAdGroupRequest
{
ResourceNameAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"),
};
gagvr::AdGroup expectedResponse = new gagvr::AdGroup
{
ResourceNameAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"),
Status = gagve::AdGroupStatusEnum.Types.AdGroupStatus.Removed,
UrlCustomParameters =
{
new gagvc::CustomParameter(),
},
Type = gagve::AdGroupTypeEnum.Types.AdGroupType.VideoTrueViewInDisplay,
ExplorerAutoOptimizerSetting = new gagvc::ExplorerAutoOptimizerSetting(),
AdRotationMode = gagve::AdGroupAdRotationModeEnum.Types.AdGroupAdRotationMode.Unspecified,
DisplayCustomBidDimension = gagve::TargetingDimensionEnum.Types.TargetingDimension.AgeRange,
TargetingSetting = new gagvc::TargetingSetting(),
EffectiveTargetCpaSource = gagve::BiddingSourceEnum.Types.BiddingSource.Unknown,
EffectiveTargetRoasSource = gagve::BiddingSourceEnum.Types.BiddingSource.AdGroupCriterion,
Id = -6774108720365892680L,
AdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"),
BaseAdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"),
TrackingUrlTemplate = "tracking_url_template157f152a",
CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"),
CpcBidMicros = 7321761304249472746L,
CpmBidMicros = -6938481569984464040L,
TargetCpaMicros = 5263516020894046876L,
CpvBidMicros = 3393527949878021854L,
TargetCpmMicros = 2683842186664132327L,
TargetRoas = 1.0830159587289216E+18,
PercentCpcBidMicros = 3342096754779167220L,
FinalUrlSuffix = "final_url_suffix046ed37a",
EffectiveTargetCpaMicros = 9173558632194584770L,
EffectiveTargetRoas = -5.789428044530098E+17,
LabelsAsAdGroupLabelNames =
{
gagvr::AdGroupLabelName.FromCustomerAdGroupLabel("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[LABEL_ID]"),
},
ExcludedParentAssetFieldTypes =
{
gagve::AssetFieldTypeEnum.Types.AssetFieldType.HotelCallout,
},
};
mockGrpcClient.Setup(x => x.GetAdGroup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AdGroupServiceClient client = new AdGroupServiceClientImpl(mockGrpcClient.Object, null);
gagvr::AdGroup response = client.GetAdGroup(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetAdGroupRequestObjectAsync()
{
moq::Mock<AdGroupService.AdGroupServiceClient> mockGrpcClient = new moq::Mock<AdGroupService.AdGroupServiceClient>(moq::MockBehavior.Strict);
GetAdGroupRequest request = new GetAdGroupRequest
{
ResourceNameAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"),
};
gagvr::AdGroup expectedResponse = new gagvr::AdGroup
{
ResourceNameAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"),
Status = gagve::AdGroupStatusEnum.Types.AdGroupStatus.Removed,
UrlCustomParameters =
{
new gagvc::CustomParameter(),
},
Type = gagve::AdGroupTypeEnum.Types.AdGroupType.VideoTrueViewInDisplay,
ExplorerAutoOptimizerSetting = new gagvc::ExplorerAutoOptimizerSetting(),
AdRotationMode = gagve::AdGroupAdRotationModeEnum.Types.AdGroupAdRotationMode.Unspecified,
DisplayCustomBidDimension = gagve::TargetingDimensionEnum.Types.TargetingDimension.AgeRange,
TargetingSetting = new gagvc::TargetingSetting(),
EffectiveTargetCpaSource = gagve::BiddingSourceEnum.Types.BiddingSource.Unknown,
EffectiveTargetRoasSource = gagve::BiddingSourceEnum.Types.BiddingSource.AdGroupCriterion,
Id = -6774108720365892680L,
AdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"),
BaseAdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"),
TrackingUrlTemplate = "tracking_url_template157f152a",
CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"),
CpcBidMicros = 7321761304249472746L,
CpmBidMicros = -6938481569984464040L,
TargetCpaMicros = 5263516020894046876L,
CpvBidMicros = 3393527949878021854L,
TargetCpmMicros = 2683842186664132327L,
TargetRoas = 1.0830159587289216E+18,
PercentCpcBidMicros = 3342096754779167220L,
FinalUrlSuffix = "final_url_suffix046ed37a",
EffectiveTargetCpaMicros = 9173558632194584770L,
EffectiveTargetRoas = -5.789428044530098E+17,
LabelsAsAdGroupLabelNames =
{
gagvr::AdGroupLabelName.FromCustomerAdGroupLabel("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[LABEL_ID]"),
},
ExcludedParentAssetFieldTypes =
{
gagve::AssetFieldTypeEnum.Types.AssetFieldType.HotelCallout,
},
};
mockGrpcClient.Setup(x => x.GetAdGroupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::AdGroup>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AdGroupServiceClient client = new AdGroupServiceClientImpl(mockGrpcClient.Object, null);
gagvr::AdGroup responseCallSettings = await client.GetAdGroupAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::AdGroup responseCancellationToken = await client.GetAdGroupAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetAdGroup()
{
moq::Mock<AdGroupService.AdGroupServiceClient> mockGrpcClient = new moq::Mock<AdGroupService.AdGroupServiceClient>(moq::MockBehavior.Strict);
GetAdGroupRequest request = new GetAdGroupRequest
{
ResourceNameAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"),
};
gagvr::AdGroup expectedResponse = new gagvr::AdGroup
{
ResourceNameAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"),
Status = gagve::AdGroupStatusEnum.Types.AdGroupStatus.Removed,
UrlCustomParameters =
{
new gagvc::CustomParameter(),
},
Type = gagve::AdGroupTypeEnum.Types.AdGroupType.VideoTrueViewInDisplay,
ExplorerAutoOptimizerSetting = new gagvc::ExplorerAutoOptimizerSetting(),
AdRotationMode = gagve::AdGroupAdRotationModeEnum.Types.AdGroupAdRotationMode.Unspecified,
DisplayCustomBidDimension = gagve::TargetingDimensionEnum.Types.TargetingDimension.AgeRange,
TargetingSetting = new gagvc::TargetingSetting(),
EffectiveTargetCpaSource = gagve::BiddingSourceEnum.Types.BiddingSource.Unknown,
EffectiveTargetRoasSource = gagve::BiddingSourceEnum.Types.BiddingSource.AdGroupCriterion,
Id = -6774108720365892680L,
AdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"),
BaseAdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"),
TrackingUrlTemplate = "tracking_url_template157f152a",
CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"),
CpcBidMicros = 7321761304249472746L,
CpmBidMicros = -6938481569984464040L,
TargetCpaMicros = 5263516020894046876L,
CpvBidMicros = 3393527949878021854L,
TargetCpmMicros = 2683842186664132327L,
TargetRoas = 1.0830159587289216E+18,
PercentCpcBidMicros = 3342096754779167220L,
FinalUrlSuffix = "final_url_suffix046ed37a",
EffectiveTargetCpaMicros = 9173558632194584770L,
EffectiveTargetRoas = -5.789428044530098E+17,
LabelsAsAdGroupLabelNames =
{
gagvr::AdGroupLabelName.FromCustomerAdGroupLabel("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[LABEL_ID]"),
},
ExcludedParentAssetFieldTypes =
{
gagve::AssetFieldTypeEnum.Types.AssetFieldType.HotelCallout,
},
};
mockGrpcClient.Setup(x => x.GetAdGroup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AdGroupServiceClient client = new AdGroupServiceClientImpl(mockGrpcClient.Object, null);
gagvr::AdGroup response = client.GetAdGroup(request.ResourceName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetAdGroupAsync()
{
moq::Mock<AdGroupService.AdGroupServiceClient> mockGrpcClient = new moq::Mock<AdGroupService.AdGroupServiceClient>(moq::MockBehavior.Strict);
GetAdGroupRequest request = new GetAdGroupRequest
{
ResourceNameAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"),
};
gagvr::AdGroup expectedResponse = new gagvr::AdGroup
{
ResourceNameAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"),
Status = gagve::AdGroupStatusEnum.Types.AdGroupStatus.Removed,
UrlCustomParameters =
{
new gagvc::CustomParameter(),
},
Type = gagve::AdGroupTypeEnum.Types.AdGroupType.VideoTrueViewInDisplay,
ExplorerAutoOptimizerSetting = new gagvc::ExplorerAutoOptimizerSetting(),
AdRotationMode = gagve::AdGroupAdRotationModeEnum.Types.AdGroupAdRotationMode.Unspecified,
DisplayCustomBidDimension = gagve::TargetingDimensionEnum.Types.TargetingDimension.AgeRange,
TargetingSetting = new gagvc::TargetingSetting(),
EffectiveTargetCpaSource = gagve::BiddingSourceEnum.Types.BiddingSource.Unknown,
EffectiveTargetRoasSource = gagve::BiddingSourceEnum.Types.BiddingSource.AdGroupCriterion,
Id = -6774108720365892680L,
AdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"),
BaseAdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"),
TrackingUrlTemplate = "tracking_url_template157f152a",
CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"),
CpcBidMicros = 7321761304249472746L,
CpmBidMicros = -6938481569984464040L,
TargetCpaMicros = 5263516020894046876L,
CpvBidMicros = 3393527949878021854L,
TargetCpmMicros = 2683842186664132327L,
TargetRoas = 1.0830159587289216E+18,
PercentCpcBidMicros = 3342096754779167220L,
FinalUrlSuffix = "final_url_suffix046ed37a",
EffectiveTargetCpaMicros = 9173558632194584770L,
EffectiveTargetRoas = -5.789428044530098E+17,
LabelsAsAdGroupLabelNames =
{
gagvr::AdGroupLabelName.FromCustomerAdGroupLabel("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[LABEL_ID]"),
},
ExcludedParentAssetFieldTypes =
{
gagve::AssetFieldTypeEnum.Types.AssetFieldType.HotelCallout,
},
};
mockGrpcClient.Setup(x => x.GetAdGroupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::AdGroup>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AdGroupServiceClient client = new AdGroupServiceClientImpl(mockGrpcClient.Object, null);
gagvr::AdGroup responseCallSettings = await client.GetAdGroupAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::AdGroup responseCancellationToken = await client.GetAdGroupAsync(request.ResourceName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetAdGroupResourceNames()
{
moq::Mock<AdGroupService.AdGroupServiceClient> mockGrpcClient = new moq::Mock<AdGroupService.AdGroupServiceClient>(moq::MockBehavior.Strict);
GetAdGroupRequest request = new GetAdGroupRequest
{
ResourceNameAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"),
};
gagvr::AdGroup expectedResponse = new gagvr::AdGroup
{
ResourceNameAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"),
Status = gagve::AdGroupStatusEnum.Types.AdGroupStatus.Removed,
UrlCustomParameters =
{
new gagvc::CustomParameter(),
},
Type = gagve::AdGroupTypeEnum.Types.AdGroupType.VideoTrueViewInDisplay,
ExplorerAutoOptimizerSetting = new gagvc::ExplorerAutoOptimizerSetting(),
AdRotationMode = gagve::AdGroupAdRotationModeEnum.Types.AdGroupAdRotationMode.Unspecified,
DisplayCustomBidDimension = gagve::TargetingDimensionEnum.Types.TargetingDimension.AgeRange,
TargetingSetting = new gagvc::TargetingSetting(),
EffectiveTargetCpaSource = gagve::BiddingSourceEnum.Types.BiddingSource.Unknown,
EffectiveTargetRoasSource = gagve::BiddingSourceEnum.Types.BiddingSource.AdGroupCriterion,
Id = -6774108720365892680L,
AdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"),
BaseAdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"),
TrackingUrlTemplate = "tracking_url_template157f152a",
CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"),
CpcBidMicros = 7321761304249472746L,
CpmBidMicros = -6938481569984464040L,
TargetCpaMicros = 5263516020894046876L,
CpvBidMicros = 3393527949878021854L,
TargetCpmMicros = 2683842186664132327L,
TargetRoas = 1.0830159587289216E+18,
PercentCpcBidMicros = 3342096754779167220L,
FinalUrlSuffix = "final_url_suffix046ed37a",
EffectiveTargetCpaMicros = 9173558632194584770L,
EffectiveTargetRoas = -5.789428044530098E+17,
LabelsAsAdGroupLabelNames =
{
gagvr::AdGroupLabelName.FromCustomerAdGroupLabel("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[LABEL_ID]"),
},
ExcludedParentAssetFieldTypes =
{
gagve::AssetFieldTypeEnum.Types.AssetFieldType.HotelCallout,
},
};
mockGrpcClient.Setup(x => x.GetAdGroup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AdGroupServiceClient client = new AdGroupServiceClientImpl(mockGrpcClient.Object, null);
gagvr::AdGroup response = client.GetAdGroup(request.ResourceNameAsAdGroupName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetAdGroupResourceNamesAsync()
{
moq::Mock<AdGroupService.AdGroupServiceClient> mockGrpcClient = new moq::Mock<AdGroupService.AdGroupServiceClient>(moq::MockBehavior.Strict);
GetAdGroupRequest request = new GetAdGroupRequest
{
ResourceNameAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"),
};
gagvr::AdGroup expectedResponse = new gagvr::AdGroup
{
ResourceNameAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"),
Status = gagve::AdGroupStatusEnum.Types.AdGroupStatus.Removed,
UrlCustomParameters =
{
new gagvc::CustomParameter(),
},
Type = gagve::AdGroupTypeEnum.Types.AdGroupType.VideoTrueViewInDisplay,
ExplorerAutoOptimizerSetting = new gagvc::ExplorerAutoOptimizerSetting(),
AdRotationMode = gagve::AdGroupAdRotationModeEnum.Types.AdGroupAdRotationMode.Unspecified,
DisplayCustomBidDimension = gagve::TargetingDimensionEnum.Types.TargetingDimension.AgeRange,
TargetingSetting = new gagvc::TargetingSetting(),
EffectiveTargetCpaSource = gagve::BiddingSourceEnum.Types.BiddingSource.Unknown,
EffectiveTargetRoasSource = gagve::BiddingSourceEnum.Types.BiddingSource.AdGroupCriterion,
Id = -6774108720365892680L,
AdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"),
BaseAdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"),
TrackingUrlTemplate = "tracking_url_template157f152a",
CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"),
CpcBidMicros = 7321761304249472746L,
CpmBidMicros = -6938481569984464040L,
TargetCpaMicros = 5263516020894046876L,
CpvBidMicros = 3393527949878021854L,
TargetCpmMicros = 2683842186664132327L,
TargetRoas = 1.0830159587289216E+18,
PercentCpcBidMicros = 3342096754779167220L,
FinalUrlSuffix = "final_url_suffix046ed37a",
EffectiveTargetCpaMicros = 9173558632194584770L,
EffectiveTargetRoas = -5.789428044530098E+17,
LabelsAsAdGroupLabelNames =
{
gagvr::AdGroupLabelName.FromCustomerAdGroupLabel("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[LABEL_ID]"),
},
ExcludedParentAssetFieldTypes =
{
gagve::AssetFieldTypeEnum.Types.AssetFieldType.HotelCallout,
},
};
mockGrpcClient.Setup(x => x.GetAdGroupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::AdGroup>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AdGroupServiceClient client = new AdGroupServiceClientImpl(mockGrpcClient.Object, null);
gagvr::AdGroup responseCallSettings = await client.GetAdGroupAsync(request.ResourceNameAsAdGroupName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::AdGroup responseCancellationToken = await client.GetAdGroupAsync(request.ResourceNameAsAdGroupName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void MutateAdGroupsRequestObject()
{
moq::Mock<AdGroupService.AdGroupServiceClient> mockGrpcClient = new moq::Mock<AdGroupService.AdGroupServiceClient>(moq::MockBehavior.Strict);
MutateAdGroupsRequest request = new MutateAdGroupsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new AdGroupOperation(),
},
PartialFailure = false,
ValidateOnly = true,
ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly,
};
MutateAdGroupsResponse expectedResponse = new MutateAdGroupsResponse
{
Results =
{
new MutateAdGroupResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateAdGroups(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AdGroupServiceClient client = new AdGroupServiceClientImpl(mockGrpcClient.Object, null);
MutateAdGroupsResponse response = client.MutateAdGroups(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task MutateAdGroupsRequestObjectAsync()
{
moq::Mock<AdGroupService.AdGroupServiceClient> mockGrpcClient = new moq::Mock<AdGroupService.AdGroupServiceClient>(moq::MockBehavior.Strict);
MutateAdGroupsRequest request = new MutateAdGroupsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new AdGroupOperation(),
},
PartialFailure = false,
ValidateOnly = true,
ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly,
};
MutateAdGroupsResponse expectedResponse = new MutateAdGroupsResponse
{
Results =
{
new MutateAdGroupResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateAdGroupsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateAdGroupsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AdGroupServiceClient client = new AdGroupServiceClientImpl(mockGrpcClient.Object, null);
MutateAdGroupsResponse responseCallSettings = await client.MutateAdGroupsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
MutateAdGroupsResponse responseCancellationToken = await client.MutateAdGroupsAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void MutateAdGroups()
{
moq::Mock<AdGroupService.AdGroupServiceClient> mockGrpcClient = new moq::Mock<AdGroupService.AdGroupServiceClient>(moq::MockBehavior.Strict);
MutateAdGroupsRequest request = new MutateAdGroupsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new AdGroupOperation(),
},
};
MutateAdGroupsResponse expectedResponse = new MutateAdGroupsResponse
{
Results =
{
new MutateAdGroupResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateAdGroups(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AdGroupServiceClient client = new AdGroupServiceClientImpl(mockGrpcClient.Object, null);
MutateAdGroupsResponse response = client.MutateAdGroups(request.CustomerId, request.Operations);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task MutateAdGroupsAsync()
{
moq::Mock<AdGroupService.AdGroupServiceClient> mockGrpcClient = new moq::Mock<AdGroupService.AdGroupServiceClient>(moq::MockBehavior.Strict);
MutateAdGroupsRequest request = new MutateAdGroupsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new AdGroupOperation(),
},
};
MutateAdGroupsResponse expectedResponse = new MutateAdGroupsResponse
{
Results =
{
new MutateAdGroupResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateAdGroupsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateAdGroupsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AdGroupServiceClient client = new AdGroupServiceClientImpl(mockGrpcClient.Object, null);
MutateAdGroupsResponse responseCallSettings = await client.MutateAdGroupsAsync(request.CustomerId, request.Operations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
MutateAdGroupsResponse responseCancellationToken = await client.MutateAdGroupsAsync(request.CustomerId, request.Operations, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
// 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Http.Functional.Tests
{
public sealed partial class HttpClientTest
{
[Fact]
public void Dispose_MultipleTimes_Success()
{
var client = new HttpClient(new CustomResponseHandler((r, c) => Task.FromResult(new HttpResponseMessage())));
client.Dispose();
client.Dispose();
}
[Fact]
public void DefaultRequestHeaders_Idempotent()
{
using (var client = new HttpClient(new CustomResponseHandler((r, c) => Task.FromResult(new HttpResponseMessage()))))
{
Assert.NotNull(client.DefaultRequestHeaders);
Assert.Same(client.DefaultRequestHeaders, client.DefaultRequestHeaders);
}
}
[Fact]
public void BaseAddress_Roundtrip_Equal()
{
using (var client = new HttpClient(new CustomResponseHandler((r, c) => Task.FromResult(new HttpResponseMessage()))))
{
Assert.Null(client.BaseAddress);
Uri uri = new Uri(CreateFakeUri());
client.BaseAddress = uri;
Assert.Equal(uri, client.BaseAddress);
client.BaseAddress = null;
Assert.Null(client.BaseAddress);
}
}
[Fact]
public void BaseAddress_InvalidUri_Throws()
{
using (var client = new HttpClient(new CustomResponseHandler((r, c) => Task.FromResult(new HttpResponseMessage()))))
{
AssertExtensions.Throws<ArgumentException>("value", () => client.BaseAddress = new Uri("ftp://onlyhttpsupported"));
AssertExtensions.Throws<ArgumentException>("value", () => client.BaseAddress = new Uri("/onlyabsolutesupported", UriKind.Relative));
}
}
[Fact]
public void Timeout_Roundtrip_Equal()
{
using (var client = new HttpClient(new CustomResponseHandler((r, c) => Task.FromResult(new HttpResponseMessage()))))
{
client.Timeout = Timeout.InfiniteTimeSpan;
Assert.Equal(Timeout.InfiniteTimeSpan, client.Timeout);
client.Timeout = TimeSpan.FromSeconds(1);
Assert.Equal(TimeSpan.FromSeconds(1), client.Timeout);
}
}
[Fact]
public void Timeout_OutOfRange_Throws()
{
using (var client = new HttpClient(new CustomResponseHandler((r, c) => Task.FromResult(new HttpResponseMessage()))))
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => client.Timeout = TimeSpan.FromSeconds(-2));
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => client.Timeout = TimeSpan.FromSeconds(0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => client.Timeout = TimeSpan.FromSeconds(int.MaxValue));
}
}
[Fact]
public void MaxResponseContentBufferSize_Roundtrip_Equal()
{
using (var client = new HttpClient(new CustomResponseHandler((r, c) => Task.FromResult(new HttpResponseMessage()))))
{
client.MaxResponseContentBufferSize = 1;
Assert.Equal(1, client.MaxResponseContentBufferSize);
client.MaxResponseContentBufferSize = int.MaxValue;
Assert.Equal(int.MaxValue, client.MaxResponseContentBufferSize);
}
}
[Fact]
public void MaxResponseContentBufferSize_OutOfRange_Throws()
{
using (var client = new HttpClient(new CustomResponseHandler((r, c) => Task.FromResult(new HttpResponseMessage()))))
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => client.MaxResponseContentBufferSize = -1);
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => client.MaxResponseContentBufferSize = 0);
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => client.MaxResponseContentBufferSize = 1 + (long)int.MaxValue);
}
}
[Theory]
[InlineData(1, 2, true)]
[InlineData(1, 127, true)]
[InlineData(254, 255, true)]
[InlineData(10, 256, true)]
[InlineData(1, 440, true)]
[InlineData(2, 1, false)]
[InlineData(2, 2, false)]
[InlineData(1000, 1000, false)]
public async Task MaxResponseContentBufferSize_ThrowsIfTooSmallForContent(int maxSize, int contentLength, bool exceptionExpected)
{
var content = new CustomContent(async s =>
{
await s.WriteAsync(TestHelper.GenerateRandomContent(contentLength));
});
var handler = new CustomResponseHandler((r, c) => Task.FromResult(new HttpResponseMessage() { Content = content }));
using (var client = new HttpClient(handler))
{
client.MaxResponseContentBufferSize = maxSize;
if (exceptionExpected)
{
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(CreateFakeUri()));
}
else
{
await client.GetAsync(CreateFakeUri());
}
}
}
[Fact]
public async Task Properties_CantChangeAfterOperation_Throws()
{
using (var client = new HttpClient(new CustomResponseHandler((r,c) => Task.FromResult(new HttpResponseMessage()))))
{
(await client.GetAsync(CreateFakeUri())).Dispose();
Assert.Throws<InvalidOperationException>(() => client.BaseAddress = null);
Assert.Throws<InvalidOperationException>(() => client.Timeout = TimeSpan.FromSeconds(1));
Assert.Throws<InvalidOperationException>(() => client.MaxResponseContentBufferSize = 1);
}
}
[Theory]
[InlineData(null)]
[InlineData("/something.html")]
public void GetAsync_NoBaseAddress_InvalidUri_ThrowsException(string uri)
{
using (var client = new HttpClient(new CustomResponseHandler((r, c) => Task.FromResult(new HttpResponseMessage()))))
{
Assert.Throws<InvalidOperationException>(() => { client.GetAsync(uri == null ? null : new Uri(uri, UriKind.RelativeOrAbsolute)); });
}
}
[Theory]
[InlineData(null)]
[InlineData("/")]
public async Task GetAsync_BaseAddress_ValidUri_Success(string uri)
{
using (var client = new HttpClient(new CustomResponseHandler((r,c) => Task.FromResult(new HttpResponseMessage()))))
{
client.BaseAddress = new Uri(CreateFakeUri());
using (HttpResponseMessage response = await client.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task GetContentAsync_ErrorStatusCode_ExpectedExceptionThrown(bool withResponseContent)
{
using (var client = new HttpClient(new CustomResponseHandler(
(r,c) => Task.FromResult(new HttpResponseMessage(HttpStatusCode.BadRequest)
{
Content = withResponseContent ? new ByteArrayContent(new byte[1]) : null
}))))
{
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetStringAsync(CreateFakeUri()));
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetByteArrayAsync(CreateFakeUri()));
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetStreamAsync(CreateFakeUri()));
}
}
[Fact]
public async Task GetContentAsync_NullResponse_Throws()
{
using (var client = new HttpClient(new CustomResponseHandler((r,c) => Task.FromResult<HttpResponseMessage>(null))))
{
await Assert.ThrowsAnyAsync<InvalidOperationException>(() => client.GetStringAsync(CreateFakeUri()));
}
}
[Fact]
public async Task GetContentAsync_NullResponseContent_ReturnsDefaultValue()
{
using (var client = new HttpClient(new CustomResponseHandler((r,c) => Task.FromResult(new HttpResponseMessage() { Content = null }))))
{
Assert.Same(string.Empty, await client.GetStringAsync(CreateFakeUri()));
Assert.Same(Array.Empty<byte>(), await client.GetByteArrayAsync(CreateFakeUri()));
Assert.Same(Stream.Null, await client.GetStreamAsync(CreateFakeUri()));
}
}
[Fact]
public async Task GetContentAsync_SerializingContentThrows_Synchronous_Throws()
{
var e = new FormatException();
using (var client = new HttpClient(new CustomResponseHandler(
(r, c) => Task.FromResult(new HttpResponseMessage() { Content = new CustomContent(stream => { throw e; }) }))))
{
Assert.Same(e, await Assert.ThrowsAsync<FormatException>(() => client.GetStringAsync(CreateFakeUri())));
Assert.Same(e, await Assert.ThrowsAsync<FormatException>(() => client.GetByteArrayAsync(CreateFakeUri())));
Assert.Same(e, await Assert.ThrowsAsync<FormatException>(() => client.GetStreamAsync(CreateFakeUri())));
}
}
[Fact]
public async Task GetContentAsync_SerializingContentThrows_Asynchronous_Throws()
{
var e = new FormatException();
using (var client = new HttpClient(new CustomResponseHandler(
(r, c) => Task.FromResult(new HttpResponseMessage() { Content = new CustomContent(stream => Task.FromException(e)) }))))
{
Assert.Same(e, await Assert.ThrowsAsync<FormatException>(() => client.GetStringAsync(CreateFakeUri())));
Assert.Same(e, await Assert.ThrowsAsync<FormatException>(() => client.GetByteArrayAsync(CreateFakeUri())));
Assert.Same(e, await Assert.ThrowsAsync<FormatException>(() => client.GetStreamAsync(CreateFakeUri())));
}
}
[Fact]
public async Task GetPutPostDeleteAsync_Canceled_Throws()
{
using (var client = new HttpClient(new CustomResponseHandler((r, c) => WhenCanceled<HttpResponseMessage>(c))))
{
var content = new ByteArrayContent(new byte[1]);
var cts = new CancellationTokenSource();
Task t1 = client.GetAsync(CreateFakeUri(), cts.Token);
Task t2 = client.GetAsync(CreateFakeUri(), HttpCompletionOption.ResponseContentRead, cts.Token);
Task t3 = client.PostAsync(CreateFakeUri(), content, cts.Token);
Task t4 = client.PutAsync(CreateFakeUri(), content, cts.Token);
Task t5 = client.DeleteAsync(CreateFakeUri(), cts.Token);
cts.Cancel();
await Assert.ThrowsAsync<TaskCanceledException>(() => t1);
await Assert.ThrowsAsync<TaskCanceledException>(() => t2);
await Assert.ThrowsAsync<TaskCanceledException>(() => t3);
await Assert.ThrowsAsync<TaskCanceledException>(() => t4);
await Assert.ThrowsAsync<TaskCanceledException>(() => t5);
}
}
[Fact]
public async Task GetPutPostDeleteAsync_Success()
{
Action<HttpResponseMessage> verify = message => { using (message) Assert.Equal(HttpStatusCode.OK, message.StatusCode); };
using (var client = new HttpClient(new CustomResponseHandler((r, c) => Task.FromResult(new HttpResponseMessage()))))
{
verify(await client.GetAsync(CreateFakeUri()));
verify(await client.GetAsync(CreateFakeUri(), CancellationToken.None));
verify(await client.GetAsync(CreateFakeUri(), HttpCompletionOption.ResponseContentRead));
verify(await client.GetAsync(CreateFakeUri(), HttpCompletionOption.ResponseContentRead, CancellationToken.None));
verify(await client.PostAsync(CreateFakeUri(), new ByteArrayContent(new byte[1])));
verify(await client.PostAsync(CreateFakeUri(), new ByteArrayContent(new byte[1]), CancellationToken.None));
verify(await client.PutAsync(CreateFakeUri(), new ByteArrayContent(new byte[1])));
verify(await client.PutAsync(CreateFakeUri(), new ByteArrayContent(new byte[1]), CancellationToken.None));
verify(await client.DeleteAsync(CreateFakeUri()));
verify(await client.DeleteAsync(CreateFakeUri(), CancellationToken.None));
}
}
[Fact]
public void GetAsync_CustomException_Synchronous_ThrowsException()
{
var e = new FormatException();
using (var client = new HttpClient(new CustomResponseHandler((r, c) => { throw e; })))
{
FormatException thrown = Assert.Throws<FormatException>(() => { client.GetAsync(CreateFakeUri()); });
Assert.Same(e, thrown);
}
}
[Fact]
public async Task GetAsync_CustomException_Asynchronous_ThrowsException()
{
var e = new FormatException();
using (var client = new HttpClient(new CustomResponseHandler((r, c) => Task.FromException<HttpResponseMessage>(e))))
{
FormatException thrown = await Assert.ThrowsAsync<FormatException>(() => client.GetAsync(CreateFakeUri()));
Assert.Same(e, thrown);
}
}
[Fact]
public void SendAsync_NullRequest_ThrowsException()
{
using (var client = new HttpClient(new CustomResponseHandler((r,c) => Task.FromResult<HttpResponseMessage>(null))))
{
AssertExtensions.Throws<ArgumentNullException>("request", () => { client.SendAsync(null); });
}
}
[Fact]
public async Task SendAsync_DuplicateRequest_ThrowsException()
{
using (var client = new HttpClient(new CustomResponseHandler((r, c) => Task.FromResult(new HttpResponseMessage()))))
using (var request = new HttpRequestMessage(HttpMethod.Get, CreateFakeUri()))
{
(await client.SendAsync(request)).Dispose();
Assert.Throws<InvalidOperationException>(() => { client.SendAsync(request); });
}
}
[Fact]
public async Task SendAsync_RequestContentNotDisposed()
{
var content = new ByteArrayContent(new byte[1]);
using (var request = new HttpRequestMessage(HttpMethod.Get, CreateFakeUri()) { Content = content })
using (var client = new HttpClient(new CustomResponseHandler((r, c) => Task.FromResult(new HttpResponseMessage()))))
{
await client.SendAsync(request);
await content.ReadAsStringAsync(); // no exception
}
}
[Fact]
public void Dispose_UseAfterDispose_Throws()
{
var client = new HttpClient(new CustomResponseHandler((r, c) => Task.FromResult(new HttpResponseMessage())));
client.Dispose();
Assert.Throws<ObjectDisposedException>(() => client.BaseAddress = null);
Assert.Throws<ObjectDisposedException>(() => client.CancelPendingRequests());
Assert.Throws<ObjectDisposedException>(() => { client.DeleteAsync(CreateFakeUri()); });
Assert.Throws<ObjectDisposedException>(() => { client.GetAsync(CreateFakeUri()); });
Assert.Throws<ObjectDisposedException>(() => { client.GetByteArrayAsync(CreateFakeUri()); });
Assert.Throws<ObjectDisposedException>(() => { client.GetStreamAsync(CreateFakeUri()); });
Assert.Throws<ObjectDisposedException>(() => { client.GetStringAsync(CreateFakeUri()); });
Assert.Throws<ObjectDisposedException>(() => { client.PostAsync(CreateFakeUri(), new ByteArrayContent(new byte[1])); });
Assert.Throws<ObjectDisposedException>(() => { client.PutAsync(CreateFakeUri(), new ByteArrayContent(new byte[1])); });
Assert.Throws<ObjectDisposedException>(() => { client.SendAsync(new HttpRequestMessage(HttpMethod.Get, CreateFakeUri())); });
Assert.Throws<ObjectDisposedException>(() => { client.Timeout = TimeSpan.FromSeconds(1); });
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void CancelAllPending_AllPendingOperationsCanceled(bool withInfiniteTimeout)
{
using (var client = new HttpClient(new CustomResponseHandler((r, c) => WhenCanceled<HttpResponseMessage>(c))))
{
if (withInfiniteTimeout)
{
client.Timeout = Timeout.InfiniteTimeSpan;
}
Task<HttpResponseMessage>[] tasks = Enumerable.Range(0, 3).Select(_ => client.GetAsync(CreateFakeUri())).ToArray();
client.CancelPendingRequests();
Assert.All(tasks, task => Assert.Throws<TaskCanceledException>(() => task.GetAwaiter().GetResult()));
}
}
[Fact]
public void Timeout_TooShort_AllPendingOperationsCanceled()
{
using (var client = new HttpClient(new CustomResponseHandler((r, c) => WhenCanceled<HttpResponseMessage>(c))))
{
client.Timeout = TimeSpan.FromMilliseconds(1);
Task<HttpResponseMessage>[] tasks = Enumerable.Range(0, 3).Select(_ => client.GetAsync(CreateFakeUri())).ToArray();
Assert.All(tasks, task => Assert.Throws<TaskCanceledException>(() => task.GetAwaiter().GetResult()));
}
}
[Fact]
[OuterLoop("One second delay in getting server's response")]
public async Task Timeout_SetTo30AndGetResponseQuickly_Success()
{
var handler = new CustomResponseHandler(async (r, c) =>
{
await Task.Delay(TimeSpan.FromSeconds(0.5));
return new HttpResponseMessage();
});
using (var client = new HttpClient(handler))
{
client.Timeout = TimeSpan.FromSeconds(30);
await client.GetAsync(CreateFakeUri());
}
}
private static string CreateFakeUri() => $"http://{Guid.NewGuid().ToString("N")}";
private static async Task<T> WhenCanceled<T>(CancellationToken cancellationToken)
{
await Task.Delay(-1, cancellationToken).ConfigureAwait(false);
return default(T);
}
private sealed class CustomResponseHandler : HttpMessageHandler
{
private readonly Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> _func;
public CustomResponseHandler(Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> func) { _func = func; }
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
return _func(request, cancellationToken);
}
}
private sealed class CustomContent : HttpContent
{
private readonly Func<Stream, Task> _func;
public CustomContent(Func<Stream, Task> func) { _func = func; }
protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
return _func(stream);
}
protected override bool TryComputeLength(out long length)
{
length = 0;
return false;
}
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using StreamCompanion.Common.Extensions;
using StreamCompanionTypes;
using StreamCompanionTypes.DataTypes;
using StreamCompanionTypes.Enums;
using StreamCompanionTypes.Interfaces.Services;
using StreamCompanionTypes.Interfaces.Sources;
namespace osu_StreamCompanion.Code.Core.Maps.Processing
{
public sealed class OsuEventHandler : IDisposable
{
public static ConfigEntry ConserveCpuInterval = new("ConserveCpuInterval", 350);
public static ConfigEntry ConserveMemory = new("ConserveMemory", true);
private readonly SettingNames _names = SettingNames.Instance;
private IContextAwareLogger _logger;
private readonly MainMapDataGetter _mainMapDataGetter;
private ISettings _settings;
private Task WorkerTask;
private CancellationTokenSource workerCancellationTokenSource = new CancellationTokenSource();
private ConcurrentStack<IMapSearchArgs> TasksMsn = new ConcurrentStack<IMapSearchArgs>();
private ConcurrentStack<IMapSearchArgs> TasksMemory = new ConcurrentStack<IMapSearchArgs>();
private CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
private readonly WorkerState _workerState = new WorkerState();
public OsuEventHandler(MainMapDataGetter mainMapDataGetter, List<IOsuEventSource> osuEventSources, ISettings settings, IContextAwareLogger logger)
{
_settings = settings;
_mainMapDataGetter = mainMapDataGetter;
foreach (var source in osuEventSources)
{
source.NewOsuEvent += NewOsuEvent;
}
_logger = logger;
WorkerTask = Task.Run(OsuEventWorkerLoop);
}
private void NewOsuEvent(object sender, IMapSearchArgs mapSearchArgs)
{
if (mapSearchArgs == null || workerCancellationTokenSource.IsCancellationRequested)
return;
var eventData = new
{
eventType = mapSearchArgs.EventType,
mapId = mapSearchArgs.MapId.ToString(),
raw = mapSearchArgs.Raw,
hash = mapSearchArgs.MapHash,
playMode = mapSearchArgs.PlayMode?.ToString() ?? "null",
sourceName = mapSearchArgs.SourceName
}.ToString();
_logger.Log($"Received event: {eventData}", LogLevel.Debug);
if (mapSearchArgs.SourceName.Contains("OsuMemory"))
{
_cancellationTokenSource.TryCancel();
TasksMemory.Clear();
_logger.SetContextData("OsuMemory_event", eventData);
TasksMemory.Push(mapSearchArgs);
return;
}
TasksMsn.Clear();
TasksMsn.Push(mapSearchArgs);
}
private async Task OsuEventWorkerLoop()
{
while (true)
{
if (workerCancellationTokenSource.IsCancellationRequested)
{
_cancellationTokenSource?.TryCancel();
return;
}
try
{
await HandleMapSearchArgs(GetSearchArgs());
}
catch (OperationCanceledException)
{
_workerState.LastProcessingCancelled = true;
}
catch (Exception ex)
{
ex.Data["PreventedCrash"] = 1;
_logger.Log(ex, LogLevel.Critical);
_logger.Log("Prevented crash in event worker, token data for last event might be incorrect! This exception has been automatically reported.", LogLevel.Warning);
}
await Task.Delay(5);
}
}
private IMapSearchArgs GetSearchArgs()
{
IMapSearchArgs mapSearchArgs;
if (!_workerState.MemorySearchFailed)
{
TasksMemory.TryPop(out mapSearchArgs);
return mapSearchArgs;
}
_workerState.MemorySearchFailed = false;
TasksMsn.TryPop(out mapSearchArgs);
return mapSearchArgs;
}
private async Task HandleMapSearchArgs(IMapSearchArgs mapSearchArgs)
{
if (mapSearchArgs == null)
return;
_cancellationTokenSource.Dispose();
_cancellationTokenSource = new CancellationTokenSource();
var cancellationToken = _cancellationTokenSource.Token;
var mapSearchResult = await FindBeatmaps(mapSearchArgs, cancellationToken);
if (_settings.Get<bool>(ConserveMemory))
GC.Collect();
if (mapSearchResult == null)
return;
if (!mapSearchResult.BeatmapsFound.Any() && mapSearchArgs.SourceName.Contains("OsuMemory"))
{
_workerState.MemorySearchFailed = true;
return;
}
mapSearchResult.MapSource = mapSearchArgs.SourceName;
await HandleMapSearchResult(mapSearchResult, cancellationToken);
}
private async Task<IMapSearchResult> FindBeatmaps(IMapSearchArgs mapSearchArgs, CancellationToken token)
{
if (mapSearchArgs.MapId == 0 && string.IsNullOrEmpty(mapSearchArgs.MapHash) && string.IsNullOrEmpty(mapSearchArgs.Raw))
return null;
var performMapSearch = true;
if (_workerState.LastProcessingCancelled)
{
_workerState.LastProcessingCancelled = false;
//preserve previous search results if we have same playMode & same map _file hash_ & same mods
performMapSearch = _workerState.LastMapSearchResult == null
|| _workerState.LastMapSearchResult.PlayMode != mapSearchArgs.PlayMode
|| !_workerState.LastMapSearchResult.BeatmapsFound.Any()
|| string.IsNullOrWhiteSpace(mapSearchArgs.MapHash)
|| _workerState.LastMapSearchResult.SearchArgs.MapHash != mapSearchArgs.MapHash
|| _workerState.LastMapSearchResult.SearchArgs.Mods != mapSearchArgs.Mods;
mapSearchArgs.EventType = OsuEventType.MapChange;
}
if (performMapSearch && (mapSearchArgs.EventType == OsuEventType.MapChange || _workerState.LastMapSearchResult == null || !_workerState.LastMapSearchResult.BeatmapsFound.Any()))
{
await DelayBeatmapSearch(token);
_logger.SetContextData("SearchingForBeatmaps", "1");
_workerState.LastMapSearchResult = await _mainMapDataGetter.FindMapData(mapSearchArgs, token);
_logger.SetContextData("SearchingForBeatmaps", "0");
return _workerState.LastMapSearchResult;
}
_logger.Log((!performMapSearch ? "Skipped map search & " : "") + "Reusing last search result", LogLevel.Trace);
var searchResult = new MapSearchResult(mapSearchArgs)
{
Mods = _workerState.LastMapSearchResult.Mods
};
searchResult.BeatmapsFound.AddRange(_workerState.LastMapSearchResult.BeatmapsFound);
searchResult.SharedObjects.AddRange(_workerState.LastMapSearchResult.SharedObjects);
return _workerState.LastMapSearchResult = searchResult;
}
private Task DelayBeatmapSearch(CancellationToken token)
{
var interval = _settings.Get<int>(ConserveCpuInterval);
return interval > 0
? Task.Delay(interval, token)
: Task.CompletedTask;
}
private async Task HandleMapSearchResult(IMapSearchResult mapSearchResult, CancellationToken token)
{
_logger.SetContextData("searchResult", new
{
mods = mapSearchResult.Mods?.Mods.ToString() ?? "null",
rawName = $"{mapSearchResult.BeatmapsFound[0]?.Artist} - {mapSearchResult.BeatmapsFound[0]?.Title} [{mapSearchResult.BeatmapsFound[0]?.DiffName}]",
mapId = mapSearchResult.BeatmapsFound[0]?.MapId.ToString(),
action = mapSearchResult.Action.ToString()
}.ToString());
await _mainMapDataGetter.ProcessMapResult(mapSearchResult, token);
}
public void Dispose()
{
workerCancellationTokenSource.TryCancel();
workerCancellationTokenSource.Dispose();
_cancellationTokenSource.TryCancel();
_cancellationTokenSource.Dispose();
}
private class WorkerState
{
public bool MemorySearchFailed { get; set; }
public IMapSearchResult LastMapSearchResult { get; set; }
public bool LastProcessingCancelled { get; set; }
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Runtime;
namespace System.ServiceModel.Channels
{
// code that pools items and closes/aborts them as necessary.
// shared by IConnection and IChannel users
public abstract class CommunicationPool<TKey, TItem>
where TKey : class
where TItem : class
{
private Dictionary<TKey, EndpointConnectionPool> _endpointPools;
// need to make sure we prune over a certain number of endpoint pools
private int _pruneAccrual;
private const int pruneThreshold = 30;
protected CommunicationPool(int maxCount)
{
MaxIdleConnectionPoolCount = maxCount;
_endpointPools = new Dictionary<TKey, EndpointConnectionPool>();
OpenCount = 1;
}
public int MaxIdleConnectionPoolCount { get; }
protected object ThisLock
{
get { return this; }
}
internal int OpenCount { get; set; }
protected abstract void AbortItem(TItem item);
protected abstract void CloseItem(TItem item, TimeSpan timeout);
protected abstract void CloseItemAsync(TItem item, TimeSpan timeout);
protected abstract TKey GetPoolKey(EndpointAddress address, Uri via);
protected virtual EndpointConnectionPool CreateEndpointConnectionPool(TKey key)
{
return new EndpointConnectionPool(this, key);
}
public bool Close(TimeSpan timeout)
{
lock (ThisLock)
{
if (OpenCount <= 0)
{
return true;
}
OpenCount--;
if (OpenCount == 0)
{
OnClose(timeout);
return true;
}
return false;
}
}
private List<TItem> PruneIfNecessary()
{
List<TItem> itemsToClose = null;
_pruneAccrual++;
if (_pruneAccrual > pruneThreshold)
{
_pruneAccrual = 0;
itemsToClose = new List<TItem>();
// first prune the connection pool contents
foreach (EndpointConnectionPool pool in _endpointPools.Values)
{
pool.Prune(itemsToClose);
}
// figure out which connection pools are now empty
List<TKey> endpointKeysToRemove = null;
foreach (KeyValuePair<TKey, EndpointConnectionPool> poolEntry in _endpointPools)
{
if (poolEntry.Value.CloseIfEmpty())
{
if (endpointKeysToRemove == null)
{
endpointKeysToRemove = new List<TKey>();
}
endpointKeysToRemove.Add(poolEntry.Key);
}
}
// and then prune the connection pools themselves
if (endpointKeysToRemove != null)
{
for (int i = 0; i < endpointKeysToRemove.Count; i++)
{
_endpointPools.Remove(endpointKeysToRemove[i]);
}
}
}
return itemsToClose;
}
private EndpointConnectionPool GetEndpointPool(TKey key, TimeSpan timeout)
{
EndpointConnectionPool result = null;
List<TItem> itemsToClose = null;
lock (ThisLock)
{
if (!_endpointPools.TryGetValue(key, out result))
{
itemsToClose = PruneIfNecessary();
result = CreateEndpointConnectionPool(key);
_endpointPools.Add(key, result);
}
}
Contract.Assert(result != null, "EndpointPool must be non-null at this point");
if (itemsToClose != null && itemsToClose.Count > 0)
{
// allocate half the remaining timeout for our graceful shutdowns
TimeoutHelper timeoutHelper = new TimeoutHelper(TimeoutHelper.Divide(timeout, 2));
for (int i = 0; i < itemsToClose.Count; i++)
{
result.CloseIdleConnection(itemsToClose[i], timeoutHelper.RemainingTime());
}
}
return result;
}
public bool TryOpen()
{
lock (ThisLock)
{
if (OpenCount <= 0)
{
// can't reopen connection pools since the registry purges them on close
return false;
}
else
{
OpenCount++;
return true;
}
}
}
protected virtual void OnClosed()
{
}
private void OnClose(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
foreach (EndpointConnectionPool pool in _endpointPools.Values)
{
try
{
pool.Close(timeoutHelper.RemainingTime());
}
catch (CommunicationException)
{
}
catch (TimeoutException exception)
{
if (WcfEventSource.Instance.CloseTimeoutIsEnabled())
{
WcfEventSource.Instance.CloseTimeout(exception.Message);
}
}
}
_endpointPools.Clear();
}
public void AddConnection(TKey key, TItem connection, TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
EndpointConnectionPool endpointPool = GetEndpointPool(key, timeoutHelper.RemainingTime());
endpointPool.AddConnection(connection, timeoutHelper.RemainingTime());
}
public TItem TakeConnection(EndpointAddress address, Uri via, TimeSpan timeout, out TKey key)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
key = GetPoolKey(address, via);
EndpointConnectionPool endpointPool = GetEndpointPool(key, timeoutHelper.RemainingTime());
return endpointPool.TakeConnection(timeoutHelper.RemainingTime());
}
public void ReturnConnection(TKey key, TItem connection, bool connectionIsStillGood, TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
EndpointConnectionPool endpointPool = GetEndpointPool(key, timeoutHelper.RemainingTime());
endpointPool.ReturnConnection(connection, connectionIsStillGood, timeoutHelper.RemainingTime());
}
// base class for our collection of Idle connections
protected abstract class IdleConnectionPool
{
public abstract int Count { get; }
public abstract bool Add(TItem item);
public abstract bool Return(TItem item);
public abstract TItem Take(out bool closeItem);
}
protected class EndpointConnectionPool
{
private List<TItem> _busyConnections;
private bool _closed;
private IdleConnectionPool _idleConnections;
public EndpointConnectionPool(CommunicationPool<TKey, TItem> parent, TKey key)
{
Key = key;
Parent = parent;
_busyConnections = new List<TItem>();
}
protected TKey Key { get; }
private IdleConnectionPool IdleConnections
{
get
{
if (_idleConnections == null)
{
_idleConnections = GetIdleConnectionPool();
}
return _idleConnections;
}
}
protected CommunicationPool<TKey, TItem> Parent { get; }
protected object ThisLock
{
get { return this; }
}
// close down the pool if empty
public bool CloseIfEmpty()
{
lock (ThisLock)
{
if (!_closed)
{
if (_busyConnections.Count > 0)
{
return false;
}
if (_idleConnections != null && _idleConnections.Count > 0)
{
return false;
}
_closed = true;
}
}
return true;
}
protected virtual void AbortItem(TItem item)
{
Parent.AbortItem(item);
}
protected virtual void CloseItem(TItem item, TimeSpan timeout)
{
Parent.CloseItem(item, timeout);
}
protected virtual void CloseItemAsync(TItem item, TimeSpan timeout)
{
Parent.CloseItemAsync(item, timeout);
}
public void Abort()
{
if (_closed)
{
return;
}
List<TItem> idleItemsToClose = null;
lock (ThisLock)
{
if (_closed)
{
return;
}
_closed = true;
idleItemsToClose = SnapshotIdleConnections();
}
AbortConnections(idleItemsToClose);
}
public void Close(TimeSpan timeout)
{
List<TItem> itemsToClose = null;
lock (ThisLock)
{
if (_closed)
{
return;
}
_closed = true;
itemsToClose = SnapshotIdleConnections();
}
try
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
for (int i = 0; i < itemsToClose.Count; i++)
{
CloseItem(itemsToClose[i], timeoutHelper.RemainingTime());
}
itemsToClose.Clear();
}
finally
{
AbortConnections(itemsToClose);
}
}
private void AbortConnections(List<TItem> idleItemsToClose)
{
for (int i = 0; i < idleItemsToClose.Count; i++)
{
AbortItem(idleItemsToClose[i]);
}
for (int i = 0; i < _busyConnections.Count; i++)
{
AbortItem(_busyConnections[i]);
}
_busyConnections.Clear();
}
// must call under lock (ThisLock) since we are calling IdleConnections.Take()
private List<TItem> SnapshotIdleConnections()
{
List<TItem> itemsToClose = new List<TItem>();
bool dummy;
for (; ; )
{
TItem item = IdleConnections.Take(out dummy);
if (item == null)
{
break;
}
itemsToClose.Add(item);
}
return itemsToClose;
}
public void AddConnection(TItem connection, TimeSpan timeout)
{
bool closeConnection = false;
lock (ThisLock)
{
if (!_closed && Parent.OpenCount > 0)
{
if (!IdleConnections.Add(connection))
{
closeConnection = true;
}
}
else
{
closeConnection = true;
}
}
if (closeConnection)
{
CloseIdleConnection(connection, timeout);
}
}
protected virtual IdleConnectionPool GetIdleConnectionPool()
{
return new PoolIdleConnectionPool(Parent.MaxIdleConnectionPoolCount);
}
public virtual void Prune(List<TItem> itemsToClose)
{
}
public TItem TakeConnection(TimeSpan timeout)
{
TItem item = null;
List<TItem> itemsToClose = null;
lock (ThisLock)
{
if (_closed)
{
return null;
}
bool closeItem;
while (true)
{
item = IdleConnections.Take(out closeItem);
if (item == null)
{
break;
}
if (!closeItem)
{
_busyConnections.Add(item);
break;
}
if (itemsToClose == null)
{
itemsToClose = new List<TItem>();
}
itemsToClose.Add(item);
}
}
// cleanup any stale items accrued from IdleConnections
if (itemsToClose != null)
{
// and only allocate half the timeout passed in for our graceful shutdowns
TimeoutHelper timeoutHelper = new TimeoutHelper(TimeoutHelper.Divide(timeout, 2));
for (int i = 0; i < itemsToClose.Count; i++)
{
CloseIdleConnection(itemsToClose[i], timeoutHelper.RemainingTime());
}
}
if (WcfEventSource.Instance.ConnectionPoolMissIsEnabled())
{
if (item == null && _busyConnections != null)
{
WcfEventSource.Instance.ConnectionPoolMiss(Key != null ? Key.ToString() : string.Empty, _busyConnections.Count);
}
}
return item;
}
public void ReturnConnection(TItem connection, bool connectionIsStillGood, TimeSpan timeout)
{
bool closeConnection = false;
bool abortConnection = false;
lock (ThisLock)
{
if (!_closed)
{
if (_busyConnections.Remove(connection) && connectionIsStillGood)
{
if (Parent.OpenCount == 0 || !IdleConnections.Return(connection))
{
closeConnection = true;
}
}
else
{
abortConnection = true;
}
}
else
{
abortConnection = true;
}
}
if (closeConnection)
{
CloseIdleConnection(connection, timeout);
}
else if (abortConnection)
{
AbortItem(connection);
OnConnectionAborted();
}
}
public void CloseIdleConnection(TItem connection, TimeSpan timeout)
{
bool throwing = true;
try
{
CloseItemAsync(connection, timeout);
throwing = false;
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
}
finally
{
if (throwing)
{
AbortItem(connection);
}
}
}
protected virtual void OnConnectionAborted()
{
}
protected class PoolIdleConnectionPool
: IdleConnectionPool
{
private Pool<TItem> _idleConnections;
private int _maxCount;
public PoolIdleConnectionPool(int maxCount)
{
_idleConnections = new Pool<TItem>(maxCount);
_maxCount = maxCount;
}
public override int Count
{
get { return _idleConnections.Count; }
}
public override bool Add(TItem connection)
{
return ReturnToPool(connection);
}
public override bool Return(TItem connection)
{
return ReturnToPool(connection);
}
private bool ReturnToPool(TItem connection)
{
bool result = _idleConnections.Return(connection);
if (!result)
{
if (WcfEventSource.Instance.MaxOutboundConnectionsPerEndpointExceededIsEnabled())
{
WcfEventSource.Instance.MaxOutboundConnectionsPerEndpointExceeded(SR.Format(SR.TraceCodeConnectionPoolMaxOutboundConnectionsPerEndpointQuotaReached, _maxCount));
}
}
else if (WcfEventSource.Instance.OutboundConnectionsPerEndpointRatioIsEnabled())
{
WcfEventSource.Instance.OutboundConnectionsPerEndpointRatio(_idleConnections.Count, _maxCount);
}
return result;
}
public override TItem Take(out bool closeItem)
{
closeItem = false;
TItem ret = _idleConnections.Take();
if (WcfEventSource.Instance.OutboundConnectionsPerEndpointRatioIsEnabled())
{
WcfEventSource.Instance.OutboundConnectionsPerEndpointRatio(_idleConnections.Count, _maxCount);
}
return ret;
}
}
}
}
// all our connection pools support Idling out of connections and lease timeout
// (though Named Pipes doesn't leverage the lease timeout)
public abstract class ConnectionPool : IdlingCommunicationPool<string, IConnection>
{
private int _connectionBufferSize;
private TimeSpan _maxOutputDelay;
protected ConnectionPool(IConnectionOrientedTransportChannelFactorySettings settings, TimeSpan leaseTimeout)
: base(settings.MaxOutboundConnectionsPerEndpoint, settings.IdleTimeout, leaseTimeout)
{
_connectionBufferSize = settings.ConnectionBufferSize;
_maxOutputDelay = settings.MaxOutputDelay;
Name = settings.ConnectionPoolGroupName;
}
public string Name { get; }
protected override void AbortItem(IConnection item)
{
item.Abort();
}
protected override void CloseItem(IConnection item, TimeSpan timeout)
{
item.Close(timeout, false);
}
protected override void CloseItemAsync(IConnection item, TimeSpan timeout)
{
item.Close(timeout, true);
}
public virtual bool IsCompatible(IConnectionOrientedTransportChannelFactorySettings settings)
{
return (
(Name == settings.ConnectionPoolGroupName) &&
(_connectionBufferSize == settings.ConnectionBufferSize) &&
(MaxIdleConnectionPoolCount == settings.MaxOutboundConnectionsPerEndpoint) &&
(IdleTimeout == settings.IdleTimeout) &&
(_maxOutputDelay == settings.MaxOutputDelay)
);
}
}
}
| |
// 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.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
namespace Avalonia.Media
{
/// <summary>
/// Parses a path markup string.
/// </summary>
public class PathMarkupParser
{
private static readonly Dictionary<char, Command> Commands = new Dictionary<char, Command>
{
{ 'F', Command.FillRule },
{ 'M', Command.Move },
{ 'L', Command.Line },
{ 'H', Command.HorizontalLine },
{ 'V', Command.VerticalLine },
{ 'C', Command.CubicBezierCurve },
{ 'A', Command.Arc },
{ 'Z', Command.Close },
};
private static readonly Dictionary<char, FillRule> FillRules = new Dictionary<char, FillRule>
{
{'0', FillRule.EvenOdd },
{'1', FillRule.NonZero }
};
private StreamGeometry _geometry;
private readonly StreamGeometryContext _context;
/// <summary>
/// Initializes a new instance of the <see cref="PathMarkupParser"/> class.
/// </summary>
/// <param name="geometry">The geometry in which the path should be stored.</param>
/// <param name="context">The context for <paramref name="geometry"/>.</param>
public PathMarkupParser(StreamGeometry geometry, StreamGeometryContext context)
{
_geometry = geometry;
_context = context;
}
/// <summary>
/// Defines the command currently being processed.
/// </summary>
private enum Command
{
None,
FillRule,
Move,
Line,
HorizontalLine,
VerticalLine,
CubicBezierCurve,
Arc,
Close,
}
/// <summary>
/// Parses the specified markup string.
/// </summary>
/// <param name="s">The markup string.</param>
public void Parse(string s)
{
bool openFigure = false;
using (StringReader reader = new StringReader(s))
{
Command command = Command.None;
Point point = new Point();
bool relative = false;
while (ReadCommand(reader, ref command, ref relative))
{
switch (command)
{
case Command.FillRule:
_context.SetFillRule(ReadFillRule(reader));
break;
case Command.Move:
if (openFigure)
{
_context.EndFigure(false);
}
point = ReadPoint(reader, point, relative);
_context.BeginFigure(point, true);
openFigure = true;
break;
case Command.Line:
point = ReadPoint(reader, point, relative);
_context.LineTo(point);
break;
case Command.HorizontalLine:
if (!relative)
{
point = point.WithX(ReadDouble(reader));
}
else
{
point = new Point(point.X + ReadDouble(reader), point.Y);
}
_context.LineTo(point);
break;
case Command.VerticalLine:
if (!relative)
{
point = point.WithY(ReadDouble(reader));
}
else
{
point = new Point(point.X, point.Y + ReadDouble(reader));
}
_context.LineTo(point);
break;
case Command.CubicBezierCurve:
{
Point point1 = ReadPoint(reader, point, relative);
Point point2 = ReadPoint(reader, point, relative);
point = ReadPoint(reader, point, relative);
_context.CubicBezierTo(point1, point2, point);
break;
}
case Command.Arc:
{
Size size = ReadSize(reader);
ReadSeparator(reader);
double rotationAngle = ReadDouble(reader);
ReadSeparator(reader);
bool isLargeArc = ReadBool(reader);
ReadSeparator(reader);
SweepDirection sweepDirection = ReadBool(reader) ? SweepDirection.Clockwise : SweepDirection.CounterClockwise;
point = ReadPoint(reader, point, relative);
_context.ArcTo(point, size, rotationAngle, isLargeArc, sweepDirection);
break;
}
case Command.Close:
_context.EndFigure(true);
openFigure = false;
break;
default:
throw new NotSupportedException("Unsupported command");
}
}
if (openFigure)
{
_context.EndFigure(false);
}
}
}
private static bool ReadCommand(
StringReader reader,
ref Command command,
ref bool relative)
{
ReadWhitespace(reader);
int i = reader.Peek();
if (i == -1)
{
return false;
}
else
{
char c = (char)i;
Command next = Command.None;
if (!Commands.TryGetValue(char.ToUpperInvariant(c), out next))
{
if ((char.IsDigit(c) || c == '.' || c == '+' || c == '-') &&
(command != Command.None))
{
return true;
}
else
{
throw new InvalidDataException("Unexpected path command '" + c + "'.");
}
}
command = next;
relative = char.IsLower(c);
reader.Read();
return true;
}
}
private static FillRule ReadFillRule(StringReader reader)
{
int i = reader.Read();
if (i == -1)
{
throw new InvalidDataException("Invalid fill rule");
}
char c = (char)i;
FillRule rule;
if (!FillRules.TryGetValue(c, out rule))
{
throw new InvalidDataException("Invalid fill rule");
}
return rule;
}
private static double ReadDouble(StringReader reader)
{
ReadWhitespace(reader);
// TODO: Handle Infinity, NaN and scientific notation.
StringBuilder b = new StringBuilder();
bool readSign = false;
bool readPoint = false;
bool readExponent = false;
int i;
while ((i = reader.Peek()) != -1)
{
char c = char.ToUpperInvariant((char)i);
if (((c == '+' || c == '-') && !readSign) ||
(c == '.' && !readPoint) ||
(c == 'E' && !readExponent) ||
char.IsDigit(c))
{
b.Append(c);
reader.Read();
if (!readSign)
{
readSign = c == '+' || c == '-';
}
if (!readPoint)
{
readPoint = c == '.';
}
if (c == 'E')
{
readSign = false;
readExponent = c == 'E';
}
}
else
{
break;
}
}
return double.Parse(b.ToString(), CultureInfo.InvariantCulture);
}
private static Point ReadPoint(StringReader reader, Point current, bool relative)
{
if (!relative)
{
current = new Point();
}
ReadWhitespace(reader);
double x = current.X + ReadDouble(reader);
ReadSeparator(reader);
double y = current.Y + ReadDouble(reader);
return new Point(x, y);
}
private static Size ReadSize(StringReader reader)
{
ReadWhitespace(reader);
double x = ReadDouble(reader);
ReadSeparator(reader);
double y = ReadDouble(reader);
return new Size(x, y);
}
private static bool ReadBool(StringReader reader)
{
return ReadDouble(reader) != 0;
}
private static Point ReadRelativePoint(StringReader reader, Point lastPoint)
{
ReadWhitespace(reader);
double x = ReadDouble(reader);
ReadSeparator(reader);
double y = ReadDouble(reader);
return new Point(lastPoint.X + x, lastPoint.Y + y);
}
private static void ReadSeparator(StringReader reader)
{
int i;
bool readComma = false;
while ((i = reader.Peek()) != -1)
{
char c = (char)i;
if (char.IsWhiteSpace(c))
{
reader.Read();
}
else if (c == ',')
{
if (readComma)
{
throw new InvalidDataException("Unexpected ','.");
}
readComma = true;
reader.Read();
}
else
{
break;
}
}
}
private static void ReadWhitespace(StringReader reader)
{
int i;
while ((i = reader.Peek()) != -1)
{
char c = (char)i;
if (char.IsWhiteSpace(c))
{
reader.Read();
}
else
{
break;
}
}
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using Baseline;
using Marten.Events;
using Marten.Linq;
using Marten.Linq.QueryHandlers;
using Marten.Schema.BulkLoading;
using Marten.Schema.Identity;
using Marten.Schema.Identity.Sequences;
using Marten.Transforms;
using Marten.Util;
namespace Marten.Schema
{
public class DocumentSchema : IDocumentSchema, IDDLRunner, IDisposable
{
private readonly ConcurrentDictionary<Type, IDocumentStorage> _documentTypes =
new ConcurrentDictionary<Type, IDocumentStorage>();
private readonly IConnectionFactory _factory;
private readonly IMartenLogger _logger;
private readonly ConcurrentDictionary<Type, object> _bulkLoaders = new ConcurrentDictionary<Type, object>();
private readonly ConcurrentDictionary<Type, IDocumentUpsert> _upserts = new ConcurrentDictionary<Type, IDocumentUpsert>();
private readonly ConcurrentDictionary<Type, object> _identityAssignments = new ConcurrentDictionary<Type, object>();
private readonly ConcurrentDictionary<string, TransformFunction> _transforms = new ConcurrentDictionary<string, TransformFunction>();
private readonly Lazy<SequenceFactory> _sequences;
private readonly IDictionary<string, SystemFunction> _systemFunctions = new Dictionary<string, SystemFunction>();
public DocumentSchema(StoreOptions options, IConnectionFactory factory, IMartenLogger logger)
{
_factory = factory;
_logger = logger;
StoreOptions = options;
_sequences = new Lazy<SequenceFactory>(() =>
{
var sequences = new SequenceFactory(this, _factory, options, _logger);
var patch = new SchemaPatch(StoreOptions.DdlRules);
sequences.GenerateSchemaObjectsIfNecessary(StoreOptions.AutoCreateSchemaObjects, this, patch);
apply(sequences, patch);
return sequences;
});
Parser = new MartenExpressionParser(StoreOptions.Serializer(), StoreOptions);
HandlerFactory = new QueryHandlerFactory(this, options.Serializer());
DbObjects = new DbObjects(_factory, this);
addSystemFunction(options, "mt_immutable_timestamp", "text");
_eventQuery = new Lazy<EventQueryMapping>(() => new EventQueryMapping(StoreOptions));
}
private void addSystemFunction(StoreOptions options, string functionName, string args)
{
_systemFunctions.Add(functionName, new SystemFunction(options, functionName, args));
}
public void Dispose()
{
}
public void EnsureFunctionExists(string functionName)
{
var systemFunction = _systemFunctions[functionName];
if (!systemFunction.Checked)
{
systemFunction.GenerateSchemaObjectsIfNecessary(StoreOptions.AutoCreateSchemaObjects, this, new SchemaPatch(this));
}
}
public IEnumerable<ISchemaObjects> AllSchemaObjects()
{
var mappings = AllMappings.OrderBy(x => x.DocumentType.Name).TopologicalSort(m =>
{
var documentMapping = m as DocumentMapping;
if (documentMapping == null)
{
return Enumerable.Empty<IDocumentMapping>();
}
return documentMapping.ForeignKeys
.Select(keyDefinition => keyDefinition.ReferenceDocumentType)
.Select(MappingFor);
});
foreach (var function in _systemFunctions.Values.OrderBy(x => x.Name))
{
yield return function;
}
foreach (var mapping in mappings)
{
yield return mapping.SchemaObjects;
}
yield return new SequenceFactory(this, _factory, StoreOptions, _logger);
foreach (var transform in StoreOptions.Transforms.AllFunctions().OrderBy(x => x.Name))
{
yield return transform;
}
if (Events.IsActive)
{
yield return Events.SchemaObjects;
}
}
public IDbObjects DbObjects { get; }
public IEnumerable<IDocumentMapping> AllMappings => StoreOptions.AllDocumentMappings;
public IBulkLoader<T> BulkLoaderFor<T>()
{
EnsureStorageExists(typeof(T));
return _bulkLoaders.GetOrAdd(typeof(T), t =>
{
var assignment = IdAssignmentFor<T>();
var mapping = MappingFor(typeof(T));
if (mapping is DocumentMapping)
{
return new BulkLoader<T>(StoreOptions.Serializer(), mapping.As<DocumentMapping>(), assignment);
}
throw new ArgumentOutOfRangeException("T", "Marten cannot do bulk inserts of " + typeof(T).FullName);
}).As<IBulkLoader<T>>();
}
public IDocumentUpsert UpsertFor(Type documentType)
{
EnsureStorageExists(documentType);
return _upserts.GetOrAdd(documentType, type =>
{
return MappingFor(documentType).BuildUpsert(this);
});
}
public MartenExpressionParser Parser { get; }
public StoreOptions StoreOptions { get; }
private readonly Lazy<EventQueryMapping> _eventQuery;
public IDocumentMapping MappingFor(Type documentType)
{
if (documentType == typeof(IEvent))
{
return _eventQuery.Value;
}
return StoreOptions.FindMapping(documentType);
}
public void EnsureStorageExists(Type documentType)
{
// TODO -- HACK! Do something later that's more systematic
if (documentType == typeof(StreamState)) return;
if (documentType == typeof(EventStream))
{
var patch = new SchemaPatch(this);
Events.SchemaObjects
.GenerateSchemaObjectsIfNecessary(StoreOptions.AutoCreateSchemaObjects, this, patch);
return;
}
buildSchemaObjectsIfNecessary(MappingFor(documentType));
}
public IDocumentStorage StorageFor(Type documentType)
{
return _documentTypes.GetOrAdd(documentType, type =>
{
var mapping = MappingFor(documentType);
if (mapping is IDocumentStorage)
{
buildSchemaObjectsIfNecessary(mapping);
return mapping.As<IDocumentStorage>();
}
assertNoDuplicateDocumentAliases();
IDocumentStorage storage = mapping.BuildStorage(this);
buildSchemaObjectsIfNecessary(mapping);
return storage;
});
}
public EventGraph Events => StoreOptions.Events;
public string[] AllSchemaNames()
{
var schemas =
AllMappings.OfType<DocumentMapping>().Select(x => x.DatabaseSchemaName).Distinct().ToList();
schemas.Fill(StoreOptions.DatabaseSchemaName);
schemas.Fill(StoreOptions.Events.DatabaseSchemaName);
var schemaNames = schemas.Select(x => x.ToLowerInvariant()).ToArray();
return schemaNames;
}
public ISequences Sequences => _sequences.Value;
public void WriteDDL(string filename)
{
var sql = ToDDL();
new FileSystem().WriteStringToFile(filename, sql);
}
public void WritePatch(string filename, bool withSchemas = true)
{
if (!Path.IsPathRooted(filename))
{
filename = AppContext.BaseDirectory.AppendPath(filename);
}
var patch = ToPatch(withSchemas);
patch.WriteUpdateFile(filename);
var dropFile = SchemaPatch.ToDropFileName(filename);
patch.WriteRollbackFile(dropFile);
}
public SchemaPatch ToPatch(bool withSchemas = true)
{
var patch = new SchemaPatch(StoreOptions.DdlRules);
if (withSchemas)
{
var allSchemaNames = AllSchemaNames();
DatabaseSchemaGenerator.WriteSql(StoreOptions, allSchemaNames, patch.UpWriter);
}
foreach (var schemaObject in AllSchemaObjects())
{
schemaObject.WritePatch(this, patch);
}
return patch;
}
public SchemaPatch ToPatch(Type documentType)
{
var mapping = MappingFor(documentType);
var patch = new SchemaPatch(StoreOptions.DdlRules);
mapping.SchemaObjects.WritePatch(this, patch);
return patch;
}
public void AssertDatabaseMatchesConfiguration()
{
var patch = ToPatch(false);
if (patch.UpdateDDL.Trim().IsNotEmpty())
{
throw new SchemaValidationException(patch.UpdateDDL);
}
}
public void ApplyAllConfiguredChangesToDatabase()
{
var patch = new SchemaPatch(this);
var allSchemaNames = AllSchemaNames();
DatabaseSchemaGenerator.WriteSql(StoreOptions, allSchemaNames, patch.UpWriter);
patch.Updates.Apply(this, patch.UpdateDDL);
foreach (var schemaObject in AllSchemaObjects())
{
schemaObject.GenerateSchemaObjectsIfNecessary(StoreOptions.AutoCreateSchemaObjects, this, patch);
}
}
public void WriteDDLByType(string directory)
{
var system = new FileSystem();
system.DeleteDirectory(directory);
system.CreateDirectory(directory);
var schemaObjects = AllSchemaObjects().ToArray();
writeDatabaseSchemaGenerationScript(directory, system, schemaObjects);
foreach (var schemaObject in schemaObjects)
{
var writer = new StringWriter();
schemaObject.WriteSchemaObjects(this, writer);
var file = directory.AppendPath(schemaObject.Name + ".sql");
new SchemaPatch(StoreOptions.DdlRules).WriteTransactionalFile(file, writer.ToString());
}
}
public void WritePatchByType(string directory)
{
var system = new FileSystem();
system.DeleteDirectory(directory);
system.CreateDirectory(directory);
var schemaObjects = AllSchemaObjects().ToArray();
writeDatabaseSchemaGenerationScript(directory, system, schemaObjects);
foreach (var schemaObject in schemaObjects)
{
var patch = new SchemaPatch(StoreOptions.DdlRules);
schemaObject.WritePatch(this, patch);
if (patch.UpdateDDL.IsNotEmpty())
{
var file = directory.AppendPath(schemaObject.Name + ".sql");
patch.WriteUpdateFile(file);
}
}
}
public string ToDDL()
{
var writer = new StringWriter();
new SchemaPatch(StoreOptions.DdlRules).WriteTransactionalScript(writer, w =>
{
var allSchemaNames = AllSchemaNames();
DatabaseSchemaGenerator.WriteSql(StoreOptions, allSchemaNames, w);
foreach (var schemaObject in AllSchemaObjects())
{
schemaObject.WriteSchemaObjects(this, writer);
}
});
return writer.ToString();
}
public IResolver<T> ResolverFor<T>()
{
return StorageFor(typeof(T)).As<IResolver<T>>();
}
public IdAssignment<T> IdAssignmentFor<T>()
{
return _identityAssignments.GetOrAdd(typeof(T), t =>
{
var mapping = MappingFor(typeof(T));
return mapping.ToIdAssignment<T>(this);
}).As<IdAssignment<T>>();
}
public TransformFunction TransformFor(string name)
{
return _transforms.GetOrAdd(name, key =>
{
var transform = StoreOptions.Transforms.For(key);
var patch = new SchemaPatch(StoreOptions.DdlRules);
transform.GenerateSchemaObjectsIfNecessary(StoreOptions.AutoCreateSchemaObjects, this, patch);
apply(transform, patch);
return transform;
});
}
public IQueryHandlerFactory HandlerFactory { get; }
public IEnumerable<SystemFunction> SystemFunctions => _systemFunctions.Values;
public void ResetSchemaExistenceChecks()
{
if (_sequences.IsValueCreated)
{
_sequences.Value.ResetSchemaExistenceChecks();
}
foreach (var schemaObject in AllSchemaObjects())
{
schemaObject.ResetSchemaExistenceChecks();
}
_documentTypes.Clear();
_transforms.Clear();
}
private void writeDatabaseSchemaGenerationScript(string directory, FileSystem system, ISchemaObjects[] schemaObjects)
{
var allSchemaNames = AllSchemaNames();
var script = DatabaseSchemaGenerator.GenerateScript(StoreOptions, allSchemaNames);
var writer = new StringWriter();
if (script.IsNotEmpty())
{
writer.WriteLine(script);
writer.WriteLine();
}
foreach (var schemaObject in schemaObjects)
{
writer.WriteLine($"\\i {schemaObject.Name}.sql");
}
var filename = directory.AppendPath("all.sql");
system.WriteStringToFile(filename, writer.ToString());
}
void IDDLRunner.Apply(object subject, string ddl)
{
if (ddl.Trim().IsEmpty()) return;
try
{
_factory.RunSql(ddl);
_logger.SchemaChange(ddl);
}
catch (Exception e)
{
throw new MartenSchemaException(subject, ddl, e);
}
}
private void apply(object subject, SchemaPatch patch)
{
var ddl = patch.UpdateDDL.Trim();
if (ddl.IsEmpty()) return;
try
{
_factory.RunSql(ddl);
_logger.SchemaChange(ddl);
}
catch (Exception e)
{
throw new MartenSchemaException(subject, ddl, e);
}
}
private void buildSchemaObjectsIfNecessary(IDocumentMapping mapping)
{
var sortedMappings = new[] {mapping}.TopologicalSort(x =>
{
var documentMapping = x as DocumentMapping;
if (documentMapping == null)
{
return Enumerable.Empty<IDocumentMapping>();
}
return documentMapping.ForeignKeys
.Select(keyDefinition => keyDefinition.ReferenceDocumentType)
.Select(MappingFor);
});
var patch = new SchemaPatch(this);
sortedMappings.Each(
x => x.SchemaObjects.GenerateSchemaObjectsIfNecessary(StoreOptions.AutoCreateSchemaObjects, this, patch));
}
private void assertNoDuplicateDocumentAliases()
{
var duplicates = StoreOptions.AllDocumentMappings.Where(x => !x.StructuralTyped).GroupBy(x => x.Alias).Where(x => x.Count() > 1).ToArray();
if (duplicates.Any())
{
var message = duplicates.Select(group =>
{
return
$"Document types {group.Select(x => x.DocumentType.Name).Join(", ")} all have the same document alias '{group.Key}'. You must explicitly make document type aliases to disambiguate the database schema objects";
}).Join("\n");
throw new AmbiguousDocumentTypeAliasesException(message);
}
}
public void RebuildSystemFunctions()
{
_systemFunctions.Values.Each(
x =>
x.GenerateSchemaObjectsIfNecessary(StoreOptions.AutoCreateSchemaObjects, this, new SchemaPatch(this)));
}
}
#if SERIALIZE
[Serializable]
#endif
public class AmbiguousDocumentTypeAliasesException : Exception
{
public AmbiguousDocumentTypeAliasesException(string message) : base(message)
{
}
#if SERIALIZE
protected AmbiguousDocumentTypeAliasesException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
#endif
}
#if SERIALIZE
[Serializable]
#endif
public class SchemaValidationException : Exception
{
public SchemaValidationException(string ddl) : base("Configuration to Schema Validation Failed! These changes detected:\n\n" + ddl)
{
}
#if SERIALIZE
protected SchemaValidationException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
#endif
}
}
| |
// 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.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.GenerateType
{
internal abstract partial class AbstractGenerateTypeService<TService, TSimpleNameSyntax, TObjectCreationExpressionSyntax, TExpressionSyntax, TTypeDeclarationSyntax, TArgumentSyntax>
{
protected class State
{
public string Name { get; private set; }
public bool NameIsVerbatim { get; private set; }
// The name node that we're on. Will be used to the name the type if it's
// generated.
public TSimpleNameSyntax SimpleName { get; private set; }
// The entire expression containing the name, not including the creation. i.e. "X.Foo"
// in "new X.Foo()".
public TExpressionSyntax NameOrMemberAccessExpression { get; private set; }
// The object creation node if we have one. i.e. if we're on the 'Foo' in "new X.Foo()".
public TObjectCreationExpressionSyntax ObjectCreationExpressionOpt { get; private set; }
// One of these will be non null. It's also possible for both to be non null. For
// example, if you have "class C { Foo f; }", then "Foo" can be generated inside C or
// inside the global namespace. The namespace can be null or the type can be null if the
// user has something like "ExistingType.NewType" or "ExistingNamespace.NewType". In
// that case they're being explicit about what they want to generate into.
public INamedTypeSymbol TypeToGenerateInOpt { get; private set; }
public string NamespaceToGenerateInOpt { get; private set; }
// If we can infer a base type or interface for this type.
//
// i.e.: "IList<int> foo = new MyList();"
public INamedTypeSymbol BaseTypeOrInterfaceOpt { get; private set; }
public bool IsInterface { get; private set; }
public bool IsStruct { get; private set; }
public bool IsAttribute { get; private set; }
public bool IsException { get; private set; }
public bool IsMembersWithModule { get; private set; }
public bool IsTypeGeneratedIntoNamespaceFromMemberAccess { get; private set; }
public bool IsSimpleNameGeneric { get; private set; }
public bool IsPublicAccessibilityForTypeGeneration { get; private set; }
public bool IsInterfaceOrEnumNotAllowedInTypeContext { get; private set; }
public IMethodSymbol DelegateMethodSymbol { get; private set; }
public bool IsDelegateAllowed { get; private set; }
public bool IsEnumNotAllowed { get; private set; }
public Compilation Compilation { get; }
public bool IsDelegateOnly { get; private set; }
public bool IsClassInterfaceTypes { get; private set; }
public List<TSimpleNameSyntax> PropertiesToGenerate { get; private set; }
private State(Compilation compilation)
{
Compilation = compilation;
}
public static State Generate(
TService service,
SemanticDocument document,
SyntaxNode node,
CancellationToken cancellationToken)
{
var state = new State(document.SemanticModel.Compilation);
if (!state.TryInitialize(service, document, node, cancellationToken))
{
return null;
}
return state;
}
private bool TryInitialize(
TService service,
SemanticDocument document,
SyntaxNode node,
CancellationToken cancellationToken)
{
if (!(node is TSimpleNameSyntax))
{
return false;
}
this.SimpleName = (TSimpleNameSyntax)node;
string name;
int arity;
var syntaxFacts = document.Project.LanguageServices.GetService<ISyntaxFactsService>();
syntaxFacts.GetNameAndArityOfSimpleName(this.SimpleName, out name, out arity);
this.Name = name;
this.NameIsVerbatim = syntaxFacts.IsVerbatimIdentifier(this.SimpleName.GetFirstToken());
if (string.IsNullOrWhiteSpace(this.Name))
{
return false;
}
// We only support simple names or dotted names. i.e. "(some + expr).Foo" is not a
// valid place to generate a type for Foo.
GenerateTypeServiceStateOptions generateTypeServiceStateOptions;
if (!service.TryInitializeState(document, this.SimpleName, cancellationToken, out generateTypeServiceStateOptions))
{
return false;
}
this.NameOrMemberAccessExpression = generateTypeServiceStateOptions.NameOrMemberAccessExpression;
this.ObjectCreationExpressionOpt = generateTypeServiceStateOptions.ObjectCreationExpressionOpt;
var semanticModel = document.SemanticModel;
var info = semanticModel.GetSymbolInfo(this.SimpleName, cancellationToken);
if (info.Symbol != null)
{
// This bound, so no need to generate anything.
return false;
}
var semanticFacts = document.Project.LanguageServices.GetService<ISemanticFactsService>();
if (!semanticFacts.IsTypeContext(semanticModel, this.NameOrMemberAccessExpression.SpanStart, cancellationToken) &&
!semanticFacts.IsExpressionContext(semanticModel, this.NameOrMemberAccessExpression.SpanStart, cancellationToken) &&
!semanticFacts.IsStatementContext(semanticModel, this.NameOrMemberAccessExpression.SpanStart, cancellationToken) &&
!semanticFacts.IsNameOfContext(semanticModel, this.NameOrMemberAccessExpression.SpanStart, cancellationToken) &&
!semanticFacts.IsNamespaceContext(semanticModel, this.NameOrMemberAccessExpression.SpanStart, cancellationToken))
{
return false;
}
// If this isn't something that can be created, then don't bother offering to create
// it.
if (info.CandidateReason == CandidateReason.NotCreatable)
{
return false;
}
if (info.CandidateReason == CandidateReason.Inaccessible ||
info.CandidateReason == CandidateReason.NotReferencable ||
info.CandidateReason == CandidateReason.OverloadResolutionFailure)
{
// We bound to something inaccessible, or overload resolution on a
// constructor call failed. Don't want to offer GenerateType here.
return false;
}
if (this.ObjectCreationExpressionOpt != null)
{
// If we're new'ing up something illegal, then don't offer generate type.
var typeInfo = semanticModel.GetTypeInfo(this.ObjectCreationExpressionOpt, cancellationToken);
if (typeInfo.Type.IsModuleType())
{
return false;
}
}
DetermineNamespaceOrTypeToGenerateIn(service, document, cancellationToken);
// Now, try to infer a possible base type for this new class/interface.
this.InferBaseType(service, document, cancellationToken);
this.IsInterface = GenerateInterface(service, cancellationToken);
this.IsStruct = GenerateStruct(service, semanticModel, cancellationToken);
this.IsAttribute = this.BaseTypeOrInterfaceOpt != null && this.BaseTypeOrInterfaceOpt.Equals(semanticModel.Compilation.AttributeType());
this.IsException = this.BaseTypeOrInterfaceOpt != null && this.BaseTypeOrInterfaceOpt.Equals(semanticModel.Compilation.ExceptionType());
this.IsMembersWithModule = generateTypeServiceStateOptions.IsMembersWithModule;
this.IsTypeGeneratedIntoNamespaceFromMemberAccess = generateTypeServiceStateOptions.IsTypeGeneratedIntoNamespaceFromMemberAccess;
this.IsInterfaceOrEnumNotAllowedInTypeContext = generateTypeServiceStateOptions.IsInterfaceOrEnumNotAllowedInTypeContext;
this.IsDelegateAllowed = generateTypeServiceStateOptions.IsDelegateAllowed;
this.IsDelegateOnly = generateTypeServiceStateOptions.IsDelegateOnly;
this.IsEnumNotAllowed = generateTypeServiceStateOptions.IsEnumNotAllowed;
this.DelegateMethodSymbol = generateTypeServiceStateOptions.DelegateCreationMethodSymbol;
this.IsClassInterfaceTypes = generateTypeServiceStateOptions.IsClassInterfaceTypes;
this.IsSimpleNameGeneric = service.IsGenericName(this.SimpleName);
this.PropertiesToGenerate = generateTypeServiceStateOptions.PropertiesToGenerate;
if (this.IsAttribute && this.TypeToGenerateInOpt.GetAllTypeParameters().Any())
{
this.TypeToGenerateInOpt = null;
}
return this.TypeToGenerateInOpt != null || this.NamespaceToGenerateInOpt != null;
}
private void InferBaseType(
TService service,
SemanticDocument document,
CancellationToken cancellationToken)
{
// See if we can find a possible base type for the type being generated.
// NOTE(cyrusn): I currently limit this to when we have an object creation node.
// That's because that's when we would have an expression that could be coverted to
// something else. i.e. if the user writes "IList<int> list = new Foo()" then we can
// infer a base interface for 'Foo'. However, if they write "IList<int> list = Foo"
// then we don't really want to infer a base type for 'Foo'.
// However, there are a few other cases were we can infer a base type.
var syntaxFacts = document.Project.LanguageServices.GetService<ISyntaxFactsService>();
if (service.IsInCatchDeclaration(this.NameOrMemberAccessExpression))
{
this.BaseTypeOrInterfaceOpt = document.SemanticModel.Compilation.ExceptionType();
}
else if (syntaxFacts.IsAttributeName(this.NameOrMemberAccessExpression))
{
this.BaseTypeOrInterfaceOpt = document.SemanticModel.Compilation.AttributeType();
}
else if (
service.IsArrayElementType(this.NameOrMemberAccessExpression) ||
service.IsInVariableTypeContext(this.NameOrMemberAccessExpression) ||
this.ObjectCreationExpressionOpt != null)
{
var expr = this.ObjectCreationExpressionOpt ?? this.NameOrMemberAccessExpression;
var typeInference = document.Project.LanguageServices.GetService<ITypeInferenceService>();
var baseType = typeInference.InferType(document.SemanticModel, expr, objectAsDefault: true, cancellationToken: cancellationToken) as INamedTypeSymbol;
SetBaseType(baseType);
}
}
private void SetBaseType(INamedTypeSymbol baseType)
{
if (baseType == null)
{
return;
}
// A base type need to be non class or interface type. Also, being 'object' is
// redundant as the base type.
if (baseType.IsSealed || baseType.IsStatic || baseType.SpecialType == SpecialType.System_Object)
{
return;
}
if (baseType.TypeKind != TypeKind.Class && baseType.TypeKind != TypeKind.Interface)
{
return;
}
this.BaseTypeOrInterfaceOpt = baseType;
}
private bool GenerateStruct(TService service, SemanticModel semanticModel, CancellationToken cancellationToken)
{
return service.IsInValueTypeConstraintContext(semanticModel, this.NameOrMemberAccessExpression, cancellationToken);
}
private bool GenerateInterface(
TService service,
CancellationToken cancellationToken)
{
if (!this.IsAttribute &&
!this.IsException &&
this.Name.LooksLikeInterfaceName() &&
this.ObjectCreationExpressionOpt == null &&
(this.BaseTypeOrInterfaceOpt == null || this.BaseTypeOrInterfaceOpt.TypeKind == TypeKind.Interface))
{
return true;
}
return service.IsInInterfaceList(this.NameOrMemberAccessExpression);
}
private void DetermineNamespaceOrTypeToGenerateIn(
TService service,
SemanticDocument document,
CancellationToken cancellationToken)
{
DetermineNamespaceOrTypeToGenerateInWorker(service, document.SemanticModel, cancellationToken);
// Can only generate into a type if it's a class and it's from source.
if (this.TypeToGenerateInOpt != null)
{
if (this.TypeToGenerateInOpt.TypeKind != TypeKind.Class &&
this.TypeToGenerateInOpt.TypeKind != TypeKind.Module)
{
this.TypeToGenerateInOpt = null;
}
else
{
var symbol = SymbolFinder.FindSourceDefinitionAsync(this.TypeToGenerateInOpt, document.Project.Solution, cancellationToken).WaitAndGetResult(cancellationToken);
if (symbol == null ||
!symbol.IsKind(SymbolKind.NamedType) ||
!symbol.Locations.Any(loc => loc.IsInSource))
{
this.TypeToGenerateInOpt = null;
return;
}
var sourceTreeToBeGeneratedIn = symbol.Locations.First(loc => loc.IsInSource).SourceTree;
var documentToBeGeneratedIn = document.Project.Solution.GetDocument(sourceTreeToBeGeneratedIn);
if (documentToBeGeneratedIn == null)
{
this.TypeToGenerateInOpt = null;
return;
}
// If the 2 documents are in different project then we must have Public Accessibility.
// If we are generating in a website project, we also want to type to be public so the
// designer files can access the type.
if (documentToBeGeneratedIn.Project != document.Project ||
service.GeneratedTypesMustBePublic(documentToBeGeneratedIn.Project))
{
this.IsPublicAccessibilityForTypeGeneration = true;
}
this.TypeToGenerateInOpt = (INamedTypeSymbol)symbol;
}
}
if (this.TypeToGenerateInOpt != null)
{
if (!CodeGenerator.CanAdd(document.Project.Solution, this.TypeToGenerateInOpt, cancellationToken))
{
this.TypeToGenerateInOpt = null;
}
}
}
private bool DetermineNamespaceOrTypeToGenerateInWorker(
TService service,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
// If we're on the right of a dot, see if we can figure out what's on the left. If
// it doesn't bind to a type or a namespace, then we can't proceed.
if (this.SimpleName != this.NameOrMemberAccessExpression)
{
return DetermineNamespaceOrTypeToGenerateIn(
service, semanticModel,
service.GetLeftSideOfDot(this.SimpleName), cancellationToken);
}
else
{
// The name is standing alone. We can either generate the type into our
// containing type, or into our containing namespace.
//
// TODO(cyrusn): We need to make this logic work if the type is in the
// base/interface list of a type.
var format = SymbolDisplayFormat.FullyQualifiedFormat.WithGlobalNamespaceStyle(SymbolDisplayGlobalNamespaceStyle.Omitted);
this.TypeToGenerateInOpt = service.DetermineTypeToGenerateIn(semanticModel, this.SimpleName, cancellationToken);
if (this.TypeToGenerateInOpt != null)
{
this.NamespaceToGenerateInOpt = this.TypeToGenerateInOpt.ContainingNamespace.ToDisplayString(format);
}
else
{
var namespaceSymbol = semanticModel.GetEnclosingNamespace(this.SimpleName.SpanStart, cancellationToken);
if (namespaceSymbol != null)
{
this.NamespaceToGenerateInOpt = namespaceSymbol.ToDisplayString(format);
}
}
}
return true;
}
private bool DetermineNamespaceOrTypeToGenerateIn(
TService service,
SemanticModel semanticModel,
TExpressionSyntax leftSide,
CancellationToken cancellationToken)
{
var leftSideInfo = semanticModel.GetSymbolInfo(leftSide, cancellationToken);
if (leftSideInfo.Symbol != null)
{
var symbol = leftSideInfo.Symbol;
if (symbol is INamespaceSymbol)
{
this.NamespaceToGenerateInOpt = symbol.ToNameDisplayString();
return true;
}
else if (symbol is INamedTypeSymbol)
{
// TODO: Code coverage
this.TypeToGenerateInOpt = (INamedTypeSymbol)symbol.OriginalDefinition;
return true;
}
// We bound to something other than a namespace or named type. Can't generate a
// type inside this.
return false;
}
else
{
// If it's a dotted name, then perhaps it's a namespace. i.e. the user wrote
// "new Foo.Bar.Baz()". In this case we want to generate a namespace for
// "Foo.Bar".
IList<string> nameParts;
if (service.TryGetNameParts(leftSide, out nameParts))
{
this.NamespaceToGenerateInOpt = string.Join(".", nameParts);
return true;
}
}
return false;
}
}
protected class GenerateTypeServiceStateOptions
{
public TExpressionSyntax NameOrMemberAccessExpression { get; set; }
public TObjectCreationExpressionSyntax ObjectCreationExpressionOpt { get; set; }
public IMethodSymbol DelegateCreationMethodSymbol { get; set; }
public List<TSimpleNameSyntax> PropertiesToGenerate { get; }
public bool IsMembersWithModule { get; set; }
public bool IsTypeGeneratedIntoNamespaceFromMemberAccess { get; set; }
public bool IsInterfaceOrEnumNotAllowedInTypeContext { get; set; }
public bool IsDelegateAllowed { get; set; }
public bool IsEnumNotAllowed { get; set; }
public bool IsDelegateOnly { get; internal set; }
public bool IsClassInterfaceTypes { get; internal set; }
public GenerateTypeServiceStateOptions()
{
NameOrMemberAccessExpression = null;
ObjectCreationExpressionOpt = null;
DelegateCreationMethodSymbol = null;
IsMembersWithModule = false;
PropertiesToGenerate = new List<TSimpleNameSyntax>();
IsTypeGeneratedIntoNamespaceFromMemberAccess = false;
IsInterfaceOrEnumNotAllowedInTypeContext = false;
IsDelegateAllowed = true;
IsEnumNotAllowed = false;
IsDelegateOnly = false;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
namespace DDay.iCal
{
public class RecurringEvaluator :
Evaluator
{
#region Private Fields
private IRecurrable m_Recurrable;
#endregion
#region Protected Properties
protected IRecurrable Recurrable
{
get { return m_Recurrable; }
set { m_Recurrable = value; }
}
#endregion
#region Constructors
public RecurringEvaluator(IRecurrable obj)
{
Recurrable = obj;
// We're not sure if the object is a calendar object
// or a calendar data type, so we need to assign
// the associated object manually
if (obj is ICalendarObject)
AssociatedObject = (ICalendarObject)obj;
if (obj is ICalendarDataType)
{
ICalendarDataType dt = (ICalendarDataType)obj;
AssociatedObject = dt.AssociatedObject;
}
}
#endregion
#region Protected Methods
/// <summary>
/// Evaulates the RRule component, and adds each specified Period
/// to the <see cref="Periods"/> collection.
/// </summary>
/// <param name="FromDate">The beginning date of the range to evaluate.</param>
/// <param name="ToDate">The end date of the range to evaluate.</param>
virtual protected void EvaluateRRule(IDateTime referenceDate, DateTime periodStart, DateTime periodEnd, bool includeReferenceDateInResults)
{
// Handle RRULEs
if (Recurrable.RecurrenceRules != null &&
Recurrable.RecurrenceRules.Count > 0)
{
foreach (IRecurrencePattern rrule in Recurrable.RecurrenceRules)
{
IEvaluator evaluator = rrule.GetService(typeof(IEvaluator)) as IEvaluator;
if (evaluator != null)
{
IList<IPeriod> periods = evaluator.Evaluate(referenceDate, periodStart, periodEnd, includeReferenceDateInResults);
foreach (IPeriod p in periods)
{
if (!Periods.Contains(p))
Periods.Add(p);
}
}
}
}
else if (includeReferenceDateInResults)
{
// If no RRULEs were found, then we still need to add
// the initial reference date to the results.
IPeriod p = new Period(referenceDate.Copy<IDateTime>());
if (!Periods.Contains(p))
Periods.Add(p);
}
}
/// <summary>
/// Evalates the RDate component, and adds each specified DateTime or
/// Period to the <see cref="Periods"/> collection.
/// </summary>
/// <param name="FromDate">The beginning date of the range to evaluate.</param>
/// <param name="ToDate">The end date of the range to evaluate.</param>
virtual protected void EvaluateRDate(IDateTime referenceDate, DateTime periodStart, DateTime periodEnd)
{
// Handle RDATEs
if (Recurrable.RecurrenceDates != null)
{
foreach (IPeriodList rdate in Recurrable.RecurrenceDates)
{
IEvaluator evaluator = rdate.GetService(typeof(IEvaluator)) as IEvaluator;
if (evaluator != null)
{
IList<IPeriod> periods = evaluator.Evaluate(referenceDate, periodStart, periodEnd, false);
foreach (IPeriod p in periods)
{
if (!Periods.Contains(p))
Periods.Add(p);
}
}
}
}
}
/// <summary>
/// Evaulates the ExRule component, and excludes each specified DateTime
/// from the <see cref="Periods"/> collection.
/// </summary>
/// <param name="FromDate">The beginning date of the range to evaluate.</param>
/// <param name="ToDate">The end date of the range to evaluate.</param>
virtual protected void EvaluateExRule(IDateTime referenceDate, DateTime periodStart, DateTime periodEnd)
{
// Handle EXRULEs
if (Recurrable.ExceptionRules != null)
{
foreach (IRecurrencePattern exrule in Recurrable.ExceptionRules)
{
IEvaluator evaluator = exrule.GetService(typeof(IEvaluator)) as IEvaluator;
if (evaluator != null)
{
IList<IPeriod> periods = evaluator.Evaluate(referenceDate, periodStart, periodEnd, false);
foreach (IPeriod p in periods)
{
if (this.Periods.Contains(p))
this.Periods.Remove(p);
}
}
}
}
}
/// <summary>
/// Evalates the ExDate component, and excludes each specified DateTime or
/// Period from the <see cref="Periods"/> collection.
/// </summary>
/// <param name="FromDate">The beginning date of the range to evaluate.</param>
/// <param name="ToDate">The end date of the range to evaluate.</param>
virtual protected void EvaluateExDate(IDateTime referenceDate, DateTime periodStart, DateTime periodEnd)
{
// Handle EXDATEs
if (Recurrable.ExceptionDates != null)
{
foreach (IPeriodList exdate in Recurrable.ExceptionDates)
{
IEvaluator evaluator = exdate.GetService(typeof(IEvaluator)) as IEvaluator;
if (evaluator != null)
{
IList<IPeriod> periods = evaluator.Evaluate(referenceDate, periodStart, periodEnd, false);
foreach (IPeriod p in periods)
{
// If no time was provided for the ExDate, then it excludes the entire day
if (!p.StartTime.HasTime || (p.EndTime != null && !p.EndTime.HasTime))
p.MatchesDateOnly = true;
while (Periods.Contains(p))
Periods.Remove(p);
}
}
}
}
}
#endregion
#region Overrides
public override IList<IPeriod> Evaluate(IDateTime referenceDate, DateTime periodStart, DateTime periodEnd, bool includeReferenceDateInResults)
{
// Evaluate extra time periods, without re-evaluating ones that were already evaluated
if ((EvaluationStartBounds == DateTime.MaxValue && EvaluationEndBounds == DateTime.MinValue) ||
(periodEnd.Equals(EvaluationStartBounds)) ||
(periodStart.Equals(EvaluationEndBounds)))
{
EvaluateRRule(referenceDate, periodStart, periodEnd, includeReferenceDateInResults);
EvaluateRDate(referenceDate, periodStart, periodEnd);
EvaluateExRule(referenceDate, periodStart, periodEnd);
EvaluateExDate(referenceDate, periodStart, periodEnd);
if (EvaluationStartBounds == DateTime.MaxValue || EvaluationStartBounds > periodStart)
EvaluationStartBounds = periodStart;
if (EvaluationEndBounds == DateTime.MinValue || EvaluationEndBounds < periodEnd)
EvaluationEndBounds = periodEnd;
}
else
{
if (EvaluationStartBounds != DateTime.MaxValue && periodStart < EvaluationStartBounds)
Evaluate(referenceDate, periodStart, EvaluationStartBounds, includeReferenceDateInResults);
if (EvaluationEndBounds != DateTime.MinValue && periodEnd > EvaluationEndBounds)
Evaluate(referenceDate, EvaluationEndBounds, periodEnd, includeReferenceDateInResults);
}
// Sort the list
m_Periods.Sort();
return Periods;
}
#endregion
}
}
| |
using System;
using System.Runtime.InteropServices;
namespace SpyUO
{
internal sealed class NativeMethods
{
[StructLayout( LayoutKind.Sequential )]
public struct PROCESS_INFORMATION
{
public IntPtr hProcess;
public IntPtr hThread;
public uint dwProcessId;
public uint dwThreadId;
}
[StructLayout( LayoutKind.Sequential )]
public struct STARTUPINFO
{
public uint cb;
[MarshalAs( UnmanagedType.LPTStr )]
public string lpReserved;
[MarshalAs( UnmanagedType.LPTStr )]
public string lpDesktop;
[MarshalAs( UnmanagedType.LPTStr )]
public string lpTitle;
public uint dwX;
public uint dwY;
public uint dwXSize;
public uint dwYSize;
public uint dwXCountChars;
public uint dwYCountChars;
public uint dwFillAttribute;
public uint dwFlags;
public ushort wShowWindow;
public ushort cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
}
[Flags]
public enum CreationFlag : uint
{
DEBUG_PROCESS = 0x00000001,
DEBUG_ONLY_THIS_PROCESS = 0x00000002,
CREATE_SUSPENDED = 0x00000004,
DETACHED_PROCESS = 0x00000008,
CREATE_NEW_CONSOLE = 0x00000010,
NORMAL_PRIORITY_CLASS = 0x00000020,
IDLE_PRIORITY_CLASS = 0x00000040,
HIGH_PRIORITY_CLASS = 0x00000080,
REALTIME_PRIORITY_CLASS = 0x00000100,
CREATE_NEW_PROCESS_GROUP = 0x00000200,
CREATE_UNICODE_ENVIRONMENT = 0x00000400,
CREATE_SEPARATE_WOW_VDM = 0x00000800,
CREATE_SHARED_WOW_VDM = 0x00001000,
CREATE_FORCEDOS = 0x00002000,
BELOW_NORMAL_PRIORITY_CLASS = 0x00004000,
ABOVE_NORMAL_PRIORITY_CLASS = 0x00008000,
STACK_SIZE_PARAM_IS_A_RESERVATION = 0x00010000,
CREATE_BREAKAWAY_FROM_JOB = 0x01000000,
CREATE_PRESERVE_CODE_AUTHZ_LEVEL = 0x02000000,
CREATE_DEFAULT_ERROR_MODE = 0x04000000,
CREATE_NO_WINDOW = 0x08000000,
PROFILE_USER = 0x10000000,
PROFILE_KERNEL = 0x20000000,
PROFILE_SERVER = 0x40000000,
CREATE_IGNORE_SYSTEM_DEFAULT = 0x80000000
}
[DllImport( "Kernel32" )]
public static extern bool CreateProcess
(
[MarshalAs( UnmanagedType.LPStr )] string lpApplicationName,
[MarshalAs( UnmanagedType.LPStr )] string lpCommandLine,
IntPtr lpProcessAttributes,
IntPtr lpThreadAttributes,
bool bInheritHandles,
CreationFlag dwCreationFlags,
IntPtr lpEnvironment,
[MarshalAs( UnmanagedType.LPStr )] string lpCurrentDirectory,
ref STARTUPINFO lpStartupInfo,
out PROCESS_INFORMATION lpProcessInformation
);
[DllImport( "Kernel32" )]
public static extern bool DebugActiveProcess
(
uint dwProcessId
);
[DllImport( "Kernel32" )]
public static extern bool DebugActiveProcessStop
(
uint dwProcessId
);
[Flags]
public enum DesiredAccessProcess : uint
{
PROCESS_TERMINATE = 0x0001,
PROCESS_CREATE_THREAD = 0x0002,
PROCESS_VM_OPERATION = 0x0008,
PROCESS_VM_READ = 0x0010,
PROCESS_VM_WRITE = 0x0020,
PROCESS_DUP_HANDLE = 0x0040,
PROCESS_CREATE_PROCESS = 0x0080,
PROCESS_SET_QUOTA = 0x0100,
PROCESS_SET_INFORMATION = 0x0200,
PROCESS_QUERY_INFORMATION = 0x0400,
SYNCHRONIZE = 0x00100000,
PROCESS_ALL_ACCESS = SYNCHRONIZE | 0xF0FFF
}
[DllImport( "Kernel32" )]
public static extern IntPtr OpenProcess
(
DesiredAccessProcess dwDesiredAccess,
bool bInheritHandle,
uint dwProcessId
);
[Flags]
public enum DesiredAccessThread : uint
{
SYNCHRONIZE = 0x00100000,
THREAD_TERMINATE = 0x0001,
THREAD_SUSPEND_RESUME = 0x0002,
THREAD_GET_CONTEXT = 0x0008,
THREAD_SET_CONTEXT = 0x0010,
THREAD_SET_INFORMATION = 0x0020,
THREAD_QUERY_INFORMATION = 0x0040,
THREAD_SET_THREAD_TOKEN = 0x0080,
THREAD_IMPERSONATE = 0x0100,
THREAD_DIRECT_IMPERSONATION = 0x0200,
THREAD_ALL_ACCESS = SYNCHRONIZE | 0xF03FF
}
[DllImport( "Kernel32" )]
public static extern IntPtr OpenThread
(
DesiredAccessThread dwDesiredAccess,
bool bInheritHandle,
uint dwThreadId
);
[DllImport( "Kernel32" )]
public static extern bool CloseHandle
(
IntPtr hObject
);
public enum DebugEventCode : uint
{
EXCEPTION_DEBUG_EVENT = 1,
CREATE_THREAD_DEBUG_EVENT = 2,
CREATE_PROCESS_DEBUG_EVENT = 3,
EXIT_THREAD_DEBUG_EVENT = 4,
EXIT_PROCESS_DEBUG_EVENT = 5,
LOAD_DLL_DEBUG_EVENT = 6,
UNLOAD_DLL_DEBUG_EVENT = 7,
OUTPUT_DEBUG_STRING_EVENT = 8,
RIP_EVENT = 9
}
public const int EXCEPTION_MAXIMUM_PARAMETERS = 15;
[StructLayout( LayoutKind.Sequential )]
public struct EXCEPTION_RECORD
{
public uint ExceptionCode;
public uint ExceptionFlags;
public IntPtr ExceptionRecord;
public IntPtr ExceptionAddress;
public uint NumberParameters;
[MarshalAs( UnmanagedType.ByValArray, SizeConst = EXCEPTION_MAXIMUM_PARAMETERS)]
public uint[] ExceptionInformation;
}
[StructLayout( LayoutKind.Sequential )]
public struct EXCEPTION_DEBUG_INFO
{
public EXCEPTION_RECORD ExceptionRecord;
public uint dwFirstChance;
}
[StructLayout( LayoutKind.Sequential )]
public struct DEBUG_EVENT_EXCEPTION
{
public DebugEventCode dwDebugEventCode;
public uint dwProcessId;
public uint dwThreadId;
[StructLayout( LayoutKind.Explicit )]
public struct UnionException
{
[FieldOffset( 0 )]
public EXCEPTION_DEBUG_INFO Exception;
}
public UnionException u;
}
[DllImport( "Kernel32" )]
public static extern bool WaitForDebugEvent
(
ref DEBUG_EVENT_EXCEPTION lpDebugEvent,
uint dwMilliseconds
);
[Flags]
public enum ContinueStatus : uint
{
DBG_CONTINUE = 0x00010002,
DBG_EXCEPTION_NOT_HANDLED = 0x80010001
}
[DllImport( "Kernel32" )]
public static extern bool ContinueDebugEvent
(
uint dwProcessId,
uint dwThreadId,
ContinueStatus dwContinueStatus
);
[DllImport( "Kernel32" )]
public static extern bool ReadProcessMemory
(
IntPtr hProcess,
IntPtr lpBaseAddress,
byte[] lpBuffer,
uint nSize,
out uint lpNumberOfBytesRead
);
[DllImport( "Kernel32" )]
public static extern bool WriteProcessMemory
(
IntPtr hProcess,
IntPtr lpBaseAddress,
byte[] lpBuffer,
uint nSize,
out uint lpNumberOfBytesWritten
);
[DllImport( "Kernel32" )]
public static extern bool FlushInstructionCache
(
IntPtr hProcess,
IntPtr lpBaseAddress,
uint dwSize
);
[Flags]
public enum ContextFlags : uint
{
CONTEXT_i386 = 0x00010000,
CONTEXT_i486 = 0x00010000,
CONTEXT_CONTROL = CONTEXT_i386 | 0x00000001,
CONTEXT_INTEGER = CONTEXT_i386 | 0x00000002,
CONTEXT_SEGMENTS = CONTEXT_i386 | 0x00000004,
CONTEXT_FLOATING_POINT = CONTEXT_i386 | 0x00000008,
CONTEXT_DEBUG_REGISTERS = CONTEXT_i386 | 0x00000010,
CONTEXT_EXTENDED_REGISTERS = CONTEXT_i386 | 0x00000020,
CONTEXT_FULL = CONTEXT_CONTROL | CONTEXT_INTEGER | CONTEXT_SEGMENTS
}
[StructLayout( LayoutKind.Sequential )]
public struct FLOATING_SAVE_AREA
{
public uint ControlWord;
public uint StatusWord;
public uint TagWord;
public uint ErrorOffset;
public uint ErrorSelector;
public uint DataOffset;
public uint DataSelector;
[MarshalAs( UnmanagedType.ByValArray, SizeConst = 80 )]
public byte[] RegisterArea;
public uint Cr0NpxState;
}
[StructLayout( LayoutKind.Sequential )]
public struct CONTEXT
{
public ContextFlags ContextFlags;
public uint Dr0;
public uint Dr1;
public uint Dr2;
public uint Dr3;
public uint Dr6;
public uint Dr7;
public FLOATING_SAVE_AREA FloatSave;
public uint SegGs;
public uint SegFs;
public uint SegEs;
public uint SegDs;
public uint Edi;
public uint Esi;
public uint Ebx;
public uint Edx;
public uint Ecx;
public uint Eax;
public uint Ebp;
public uint Eip;
public uint SegCs;
public uint EFlags;
public uint Esp;
public uint SegSs;
[MarshalAs( UnmanagedType.ByValArray, SizeConst = 512 )]
public byte[] ExtendedRegisters;
}
[StructLayout( LayoutKind.Sequential )]
public struct WOW64_CONTEXT
{
public ContextFlags ContextFlags;
public uint Dr0;
public uint Dr1;
public uint Dr2;
public uint Dr3;
public uint Dr6;
public uint Dr7;
public FLOATING_SAVE_AREA FloatSave;
public uint SegGs;
public uint SegFs;
public uint SegEs;
public uint SegDs;
public uint Edi;
public uint Esi;
public uint Ebx;
public uint Edx;
public uint Ecx;
public uint Eax;
public uint Ebp;
public uint Eip;
public uint SegCs;
public uint EFlags;
public uint Esp;
public uint SegSs;
[MarshalAs( UnmanagedType.ByValArray, SizeConst = 512 )]
public byte[] ExtendedRegisters;
}
[DllImport( "Kernel32" )]
public static extern bool GetThreadContext
(
IntPtr hThread,
ref CONTEXT lpContext
);
[DllImport( "Kernel32" )]
public static extern bool Wow64GetThreadContext
(
IntPtr hThread,
ref WOW64_CONTEXT lpContext
);
[DllImport( "Kernel32" )]
public static extern bool SetThreadContext
(
IntPtr hThread,
ref CONTEXT lpContext
);
[DllImport( "Kernel32" )]
public static extern bool Wow64SetThreadContext
(
IntPtr hThread,
ref WOW64_CONTEXT lpContext
);
}
}
| |
/*
* 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 log4net;
using log4net.Config;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Framework.Monitoring;
using OpenSim.Framework.Servers;
using System;
using System.IO;
using System.Reflection;
using System.Xml;
namespace OpenSim.Server.Base
{
public class ServicesServerBase : ServerBase
{
// Logger
//
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// Command line args
//
protected string[] m_Arguments;
public string ConfigDirectory
{
get;
private set;
}
// Run flag
//
private bool m_Running = true;
// Handle all the automagical stuff
//
public ServicesServerBase(string prompt, string[] args) : base()
{
// Save raw arguments
m_Arguments = args;
// Read command line
ArgvConfigSource argvConfig = new ArgvConfigSource(args);
argvConfig.AddSwitch("Startup", "console", "c");
argvConfig.AddSwitch("Startup", "logfile", "l");
argvConfig.AddSwitch("Startup", "inifile", "i");
argvConfig.AddSwitch("Startup", "prompt", "p");
argvConfig.AddSwitch("Startup", "logconfig", "g");
// Automagically create the ini file name
string fileName = Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location);
string iniFile = fileName + ".ini";
string logConfig = null;
IConfig startupConfig = argvConfig.Configs["Startup"];
if (startupConfig != null)
{
// Check if a file name was given on the command line
iniFile = startupConfig.GetString("inifile", iniFile);
// Check if a prompt was given on the command line
prompt = startupConfig.GetString("prompt", prompt);
// Check for a Log4Net config file on the command line
logConfig =startupConfig.GetString("logconfig", logConfig);
}
// Find out of the file name is a URI and remote load it if possible.
// Load it as a local file otherwise.
Uri configUri;
try
{
if (Uri.TryCreate(iniFile, UriKind.Absolute, out configUri) &&
configUri.Scheme == Uri.UriSchemeHttp)
{
XmlReader r = XmlReader.Create(iniFile);
Config = new XmlConfigSource(r);
}
else
{
Config = new IniConfigSource(iniFile);
}
}
catch (Exception e)
{
System.Console.WriteLine("Error reading from config source. {0}", e.Message);
Environment.Exit(1);
}
// Merge OpSys env vars
m_log.Info("[CONFIG]: Loading environment variables for Config");
Util.MergeEnvironmentToConfig(Config);
// Merge the configuration from the command line into the loaded file
Config.Merge(argvConfig);
Config.ReplaceKeyValues();
// Refresh the startupConfig post merge
if (Config.Configs["Startup"] != null)
{
startupConfig = Config.Configs["Startup"];
}
ConfigDirectory = startupConfig.GetString("ConfigDirectory", ".");
prompt = startupConfig.GetString("Prompt", prompt);
// Allow derived classes to load config before the console is opened.
ReadConfig();
// Create main console
string consoleType = "local";
if (startupConfig != null)
consoleType = startupConfig.GetString("console", consoleType);
if (consoleType == "basic")
{
MainConsole.Instance = new CommandConsole(prompt);
}
else if (consoleType == "rest")
{
MainConsole.Instance = new RemoteConsole(prompt);
((RemoteConsole)MainConsole.Instance).ReadConfig(Config);
}
else
{
MainConsole.Instance = new LocalConsole(prompt);
}
m_console = MainConsole.Instance;
if (logConfig != null)
{
FileInfo cfg = new FileInfo(logConfig);
XmlConfigurator.Configure(cfg);
}
else
{
XmlConfigurator.Configure();
}
LogEnvironmentInformation();
RegisterCommonAppenders(startupConfig);
if (startupConfig.GetString("PIDFile", String.Empty) != String.Empty)
{
CreatePIDFile(startupConfig.GetString("PIDFile"));
}
RegisterCommonCommands();
RegisterCommonComponents(Config);
// Allow derived classes to perform initialization that
// needs to be done after the console has opened
Initialise();
}
public bool Running
{
get { return m_Running; }
}
public virtual int Run()
{
Watchdog.Enabled = true;
MemoryWatchdog.Enabled = true;
while (m_Running)
{
try
{
MainConsole.Instance.Prompt();
}
catch (Exception e)
{
m_log.ErrorFormat("Command error: {0}", e);
}
}
RemovePIDFile();
return 0;
}
protected override void ShutdownSpecific()
{
m_Running = false;
m_log.Info("[CONSOLE] Quitting");
base.ShutdownSpecific();
}
protected virtual void ReadConfig()
{
}
protected virtual void Initialise()
{
}
}
}
| |
// 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.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
[StructLayout(LayoutKind.Sequential, Pack = 8, Size = 8)]
struct MyVector64<T> where T : struct { }
[StructLayout(LayoutKind.Sequential, Pack = 16, Size = 16)]
struct MyVector128<T> where T : struct { }
[StructLayout(LayoutKind.Sequential, Pack = 32, Size = 32)]
struct MyVector256<T> where T : struct { }
interface ITestStructure
{
int Size { get; }
int OffsetOfByte { get; }
int OffsetOfValue { get; }
}
struct DefaultLayoutDefaultPacking<T> : ITestStructure
{
public byte _byte;
public T _value;
public int Size => Unsafe.SizeOf<DefaultLayoutDefaultPacking<T>>();
public int OffsetOfByte => Program.OffsetOf(ref this, ref _byte);
public int OffsetOfValue => Program.OffsetOf(ref this, ref _value);
}
[StructLayout(LayoutKind.Sequential)]
struct SequentialLayoutDefaultPacking<T> : ITestStructure
{
public byte _byte;
public T _value;
public int Size => Unsafe.SizeOf<SequentialLayoutDefaultPacking<T>>();
public int OffsetOfByte => Program.OffsetOf(ref this, ref _byte);
public int OffsetOfValue => Program.OffsetOf(ref this, ref _value);
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct SequentialLayoutMinPacking<T> : ITestStructure
{
public byte _byte;
public T _value;
public int Size => Unsafe.SizeOf<SequentialLayoutMinPacking<T>>();
public int OffsetOfByte => Program.OffsetOf(ref this, ref _byte);
public int OffsetOfValue => Program.OffsetOf(ref this, ref _value);
}
[StructLayout(LayoutKind.Sequential, Pack = 128)]
struct SequentialLayoutMaxPacking<T> : ITestStructure
{
public byte _byte;
public T _value;
public int Size => Unsafe.SizeOf<SequentialLayoutMaxPacking<T>>();
public int OffsetOfByte => Program.OffsetOf(ref this, ref _byte);
public int OffsetOfValue => Program.OffsetOf(ref this, ref _value);
}
[StructLayout(LayoutKind.Auto)]
struct AutoLayoutDefaultPacking<T> : ITestStructure
{
public byte _byte;
public T _value;
public int Size => Unsafe.SizeOf<AutoLayoutDefaultPacking<T>>();
public int OffsetOfByte => Program.OffsetOf(ref this, ref _byte);
public int OffsetOfValue => Program.OffsetOf(ref this, ref _value);
}
[StructLayout(LayoutKind.Auto, Pack = 1)]
struct AutoLayoutMinPacking<T> : ITestStructure
{
public byte _byte;
public T _value;
public int Size => Unsafe.SizeOf<AutoLayoutMinPacking<T>>();
public int OffsetOfByte => Program.OffsetOf(ref this, ref _byte);
public int OffsetOfValue => Program.OffsetOf(ref this, ref _value);
}
[StructLayout(LayoutKind.Auto, Pack = 128)]
struct AutoLayoutMaxPacking<T> : ITestStructure
{
public byte _byte;
public T _value;
public int Size => Unsafe.SizeOf<AutoLayoutMaxPacking<T>>();
public int OffsetOfByte => Program.OffsetOf(ref this, ref _byte);
public int OffsetOfValue => Program.OffsetOf(ref this, ref _value);
}
unsafe class Program
{
const int Pass = 100;
const int Fail = 0;
static int Main(string[] args)
{
bool succeeded = true;
// Test fundamental data types
succeeded &= TestBoolean();
succeeded &= TestByte();
succeeded &= TestChar();
succeeded &= TestDouble();
succeeded &= TestInt16();
succeeded &= TestInt32();
succeeded &= TestInt64();
succeeded &= TestIntPtr();
succeeded &= TestSByte();
succeeded &= TestSingle();
succeeded &= TestUInt16();
succeeded &= TestUInt32();
succeeded &= TestUInt64();
succeeded &= TestUIntPtr();
succeeded &= TestVector64();
succeeded &= TestVector128();
succeeded &= TestVector256();
// Test custom data types with explicit size/packing
succeeded &= TestMyVector64();
succeeded &= TestMyVector128();
succeeded &= TestMyVector256();
return succeeded ? Pass : Fail;
}
static bool TestBoolean()
{
bool succeeded = true;
succeeded &= Test<DefaultLayoutDefaultPacking<bool>>(
expectedSize: 2,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutDefaultPacking<bool>>(
expectedSize: 2,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMinPacking<bool>>(
expectedSize: 2,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMaxPacking<bool>>(
expectedSize: 2,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<AutoLayoutDefaultPacking<bool>>(
expectedSize: 2,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<AutoLayoutMinPacking<bool>>(
expectedSize: 2,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<AutoLayoutMaxPacking<bool>>(
expectedSize: 2,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
return succeeded;
}
static bool TestByte()
{
bool succeeded = true;
succeeded &= Test<DefaultLayoutDefaultPacking<byte>>(
expectedSize: 2,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutDefaultPacking<byte>>(
expectedSize: 2,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMinPacking<byte>>(
expectedSize: 2,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMaxPacking<byte>>(
expectedSize: 2,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<AutoLayoutDefaultPacking<byte>>(
expectedSize: 2,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<AutoLayoutMinPacking<byte>>(
expectedSize: 2,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<AutoLayoutMaxPacking<byte>>(
expectedSize: 2,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
return succeeded;
}
static bool TestChar()
{
bool succeeded = true;
succeeded &= Test<DefaultLayoutDefaultPacking<char>>(
expectedSize: 4,
expectedOffsetByte: 0,
expectedOffsetValue: 2
);
succeeded &= Test<SequentialLayoutDefaultPacking<char>>(
expectedSize: 4,
expectedOffsetByte: 0,
expectedOffsetValue: 2
);
succeeded &= Test<SequentialLayoutMinPacking<char>>(
expectedSize: 3,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMaxPacking<char>>(
expectedSize: 4,
expectedOffsetByte: 0,
expectedOffsetValue: 2
);
succeeded &= Test<AutoLayoutDefaultPacking<char>>(
expectedSize: 4,
expectedOffsetByte: 2,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMinPacking<char>>(
expectedSize: 4,
expectedOffsetByte: 2,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMaxPacking<char>>(
expectedSize: 4,
expectedOffsetByte: 2,
expectedOffsetValue: 0
);
return succeeded;
}
static bool TestDouble()
{
bool succeeded = true;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || (RuntimeInformation.ProcessArchitecture != Architecture.X86))
{
succeeded &= Test<DefaultLayoutDefaultPacking<double>>(
expectedSize: 16,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<SequentialLayoutDefaultPacking<double>>(
expectedSize: 16,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<SequentialLayoutMinPacking<double>>(
expectedSize: 9,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMaxPacking<double>>(
expectedSize: 16,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
if (RuntimeInformation.ProcessArchitecture != Architecture.X86)
{
succeeded &= Test<AutoLayoutDefaultPacking<double>>(
expectedSize: 16,
expectedOffsetByte: 8,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMinPacking<double>>(
expectedSize: 16,
expectedOffsetByte: 8,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMaxPacking<double>>(
expectedSize: 16,
expectedOffsetByte: 8,
expectedOffsetValue: 0
);
}
else
{
succeeded &= Test<AutoLayoutDefaultPacking<double>>(
expectedSize: 12,
expectedOffsetByte: 8,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMinPacking<double>>(
expectedSize: 12,
expectedOffsetByte: 8,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMaxPacking<double>>(
expectedSize: 12,
expectedOffsetByte: 8,
expectedOffsetValue: 0
);
}
}
else
{
// The System V ABI for i386 defines this type as having 4-byte alignment
succeeded &= Test<DefaultLayoutDefaultPacking<double>>(
expectedSize: 12,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<SequentialLayoutDefaultPacking<double>>(
expectedSize: 12,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<SequentialLayoutMinPacking<double>>(
expectedSize: 9,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMaxPacking<double>>(
expectedSize: 12,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<AutoLayoutDefaultPacking<double>>(
expectedSize: 12,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<AutoLayoutMinPacking<double>>(
expectedSize: 12,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<AutoLayoutMaxPacking<double>>(
expectedSize: 12,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
}
return succeeded;
}
static bool TestInt16()
{
bool succeeded = true;
succeeded &= Test<DefaultLayoutDefaultPacking<short>>(
expectedSize: 4,
expectedOffsetByte: 0,
expectedOffsetValue: 2
);
succeeded &= Test<SequentialLayoutDefaultPacking<short>>(
expectedSize: 4,
expectedOffsetByte: 0,
expectedOffsetValue: 2
);
succeeded &= Test<SequentialLayoutMinPacking<short>>(
expectedSize: 3,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMaxPacking<short>>(
expectedSize: 4,
expectedOffsetByte: 0,
expectedOffsetValue: 2
);
succeeded &= Test<AutoLayoutDefaultPacking<short>>(
expectedSize: 4,
expectedOffsetByte: 2,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMinPacking<short>>(
expectedSize: 4,
expectedOffsetByte: 2,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMaxPacking<short>>(
expectedSize: 4,
expectedOffsetByte: 2,
expectedOffsetValue: 0
);
return succeeded;
}
static bool TestInt32()
{
bool succeeded = true;
succeeded &= Test<DefaultLayoutDefaultPacking<int>>(
expectedSize: 8,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<SequentialLayoutDefaultPacking<int>>(
expectedSize: 8,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<SequentialLayoutMinPacking<int>>(
expectedSize: 5,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMaxPacking<int>>(
expectedSize: 8,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<AutoLayoutDefaultPacking<int>>(
expectedSize: 8,
expectedOffsetByte: 4,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMinPacking<int>>(
expectedSize: 8,
expectedOffsetByte: 4,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMaxPacking<int>>(
expectedSize: 8,
expectedOffsetByte: 4,
expectedOffsetValue: 0
);
return succeeded;
}
static bool TestInt64()
{
bool succeeded = true;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || (RuntimeInformation.ProcessArchitecture != Architecture.X86))
{
succeeded &= Test<DefaultLayoutDefaultPacking<long>>(
expectedSize: 16,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<SequentialLayoutDefaultPacking<long>>(
expectedSize: 16,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<SequentialLayoutMinPacking<long>>(
expectedSize: 9,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMaxPacking<long>>(
expectedSize: 16,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
if (RuntimeInformation.ProcessArchitecture != Architecture.X86)
{
succeeded &= Test<AutoLayoutDefaultPacking<long>>(
expectedSize: 16,
expectedOffsetByte: 8,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMinPacking<long>>(
expectedSize: 16,
expectedOffsetByte: 8,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMaxPacking<long>>(
expectedSize: 16,
expectedOffsetByte: 8,
expectedOffsetValue: 0
);
}
else
{
succeeded &= Test<AutoLayoutDefaultPacking<long>>(
expectedSize: 12,
expectedOffsetByte: 8,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMinPacking<long>>(
expectedSize: 12,
expectedOffsetByte: 8,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMaxPacking<long>>(
expectedSize: 12,
expectedOffsetByte: 8,
expectedOffsetValue: 0
);
}
}
else
{
// The System V ABI for i386 defines this type as having 4-byte alignment
succeeded &= Test<DefaultLayoutDefaultPacking<long>>(
expectedSize: 12,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<SequentialLayoutDefaultPacking<long>>(
expectedSize: 12,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<SequentialLayoutMinPacking<long>>(
expectedSize: 9,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMaxPacking<long>>(
expectedSize: 12,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<AutoLayoutDefaultPacking<long>>(
expectedSize: 12,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<AutoLayoutMinPacking<long>>(
expectedSize: 12,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<AutoLayoutMaxPacking<long>>(
expectedSize: 12,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
}
return succeeded;
}
static bool TestIntPtr()
{
bool succeeded = true;
if (Environment.Is64BitProcess)
{
succeeded &= Test<DefaultLayoutDefaultPacking<IntPtr>>(
expectedSize: 16,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<SequentialLayoutDefaultPacking<IntPtr>>(
expectedSize: 16,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<SequentialLayoutMinPacking<IntPtr>>(
expectedSize: 9,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMaxPacking<IntPtr>>(
expectedSize: 16,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<AutoLayoutDefaultPacking<IntPtr>>(
expectedSize: 16,
expectedOffsetByte: 8,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMinPacking<IntPtr>>(
expectedSize: 16,
expectedOffsetByte: 8,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMaxPacking<IntPtr>>(
expectedSize: 16,
expectedOffsetByte: 8,
expectedOffsetValue: 0
);
}
else
{
succeeded &= Test<DefaultLayoutDefaultPacking<IntPtr>>(
expectedSize: 8,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<SequentialLayoutDefaultPacking<IntPtr>>(
expectedSize: 8,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<SequentialLayoutMinPacking<IntPtr>>(
expectedSize: 5,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMaxPacking<IntPtr>>(
expectedSize: 8,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<AutoLayoutDefaultPacking<IntPtr>>(
expectedSize: 8,
expectedOffsetByte: 4,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMinPacking<IntPtr>>(
expectedSize: 8,
expectedOffsetByte: 4,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMaxPacking<IntPtr>>(
expectedSize: 8,
expectedOffsetByte: 4,
expectedOffsetValue: 0
);
}
return succeeded;
}
static bool TestSByte()
{
bool succeeded = true;
succeeded &= Test<DefaultLayoutDefaultPacking<sbyte>>(
expectedSize: 2,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutDefaultPacking<sbyte>>(
expectedSize: 2,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMinPacking<sbyte>>(
expectedSize: 2,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMaxPacking<sbyte>>(
expectedSize: 2,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<AutoLayoutDefaultPacking<sbyte>>(
expectedSize: 2,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<AutoLayoutMinPacking<sbyte>>(
expectedSize: 2,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<AutoLayoutMaxPacking<sbyte>>(
expectedSize: 2,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
return succeeded;
}
static bool TestSingle()
{
bool succeeded = true;
succeeded &= Test<DefaultLayoutDefaultPacking<float>>(
expectedSize: 8,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<SequentialLayoutDefaultPacking<float>>(
expectedSize: 8,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<SequentialLayoutMinPacking<float>>(
expectedSize: 5,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMaxPacking<float>>(
expectedSize: 8,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<AutoLayoutDefaultPacking<float>>(
expectedSize: 8,
expectedOffsetByte: 4,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMinPacking<float>>(
expectedSize: 8,
expectedOffsetByte: 4,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMaxPacking<float>>(
expectedSize: 8,
expectedOffsetByte: 4,
expectedOffsetValue: 0
);
return succeeded;
}
static bool TestUInt16()
{
bool succeeded = true;
succeeded &= Test<DefaultLayoutDefaultPacking<ushort>>(
expectedSize: 4,
expectedOffsetByte: 0,
expectedOffsetValue: 2
);
succeeded &= Test<SequentialLayoutDefaultPacking<ushort>>(
expectedSize: 4,
expectedOffsetByte: 0,
expectedOffsetValue: 2
);
succeeded &= Test<SequentialLayoutMinPacking<ushort>>(
expectedSize: 3,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMaxPacking<ushort>>(
expectedSize: 4,
expectedOffsetByte: 0,
expectedOffsetValue: 2
);
succeeded &= Test<AutoLayoutDefaultPacking<ushort>>(
expectedSize: 4,
expectedOffsetByte: 2,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMinPacking<ushort>>(
expectedSize: 4,
expectedOffsetByte: 2,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMaxPacking<ushort>>(
expectedSize: 4,
expectedOffsetByte: 2,
expectedOffsetValue: 0
);
return succeeded;
}
static bool TestUInt32()
{
bool succeeded = true;
succeeded &= Test<DefaultLayoutDefaultPacking<uint>>(
expectedSize: 8,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<SequentialLayoutDefaultPacking<uint>>(
expectedSize: 8,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<SequentialLayoutMinPacking<uint>>(
expectedSize: 5,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMaxPacking<uint>>(
expectedSize: 8,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<AutoLayoutDefaultPacking<uint>>(
expectedSize: 8,
expectedOffsetByte: 4,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMinPacking<uint>>(
expectedSize: 8,
expectedOffsetByte: 4,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMaxPacking<uint>>(
expectedSize: 8,
expectedOffsetByte: 4,
expectedOffsetValue: 0
);
return succeeded;
}
static bool TestUInt64()
{
bool succeeded = true;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || (RuntimeInformation.ProcessArchitecture != Architecture.X86))
{
succeeded &= Test<DefaultLayoutDefaultPacking<ulong>>(
expectedSize: 16,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<SequentialLayoutDefaultPacking<ulong>>(
expectedSize: 16,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<SequentialLayoutMinPacking<ulong>>(
expectedSize: 9,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMaxPacking<ulong>>(
expectedSize: 16,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
if (RuntimeInformation.ProcessArchitecture != Architecture.X86)
{
succeeded &= Test<AutoLayoutDefaultPacking<ulong>>(
expectedSize: 16,
expectedOffsetByte: 8,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMinPacking<ulong>>(
expectedSize: 16,
expectedOffsetByte: 8,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMaxPacking<ulong>>(
expectedSize: 16,
expectedOffsetByte: 8,
expectedOffsetValue: 0
);
}
else
{
succeeded &= Test<AutoLayoutDefaultPacking<ulong>>(
expectedSize: 12,
expectedOffsetByte: 8,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMinPacking<ulong>>(
expectedSize: 12,
expectedOffsetByte: 8,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMaxPacking<ulong>>(
expectedSize: 12,
expectedOffsetByte: 8,
expectedOffsetValue: 0
);
}
}
else
{
// The System V ABI for i386 defines this type as having 4-byte alignment
succeeded &= Test<DefaultLayoutDefaultPacking<ulong>>(
expectedSize: 12,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<SequentialLayoutDefaultPacking<ulong>>(
expectedSize: 12,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<SequentialLayoutMinPacking<ulong>>(
expectedSize: 9,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMaxPacking<ulong>>(
expectedSize: 12,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<AutoLayoutDefaultPacking<ulong>>(
expectedSize: 12,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<AutoLayoutMinPacking<ulong>>(
expectedSize: 12,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<AutoLayoutMaxPacking<ulong>>(
expectedSize: 12,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
}
return succeeded;
}
static bool TestUIntPtr()
{
bool succeeded = true;
if (Environment.Is64BitProcess)
{
succeeded &= Test<DefaultLayoutDefaultPacking<UIntPtr>>(
expectedSize: 16,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<SequentialLayoutDefaultPacking<UIntPtr>>(
expectedSize: 16,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<SequentialLayoutMinPacking<UIntPtr>>(
expectedSize: 9,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMaxPacking<UIntPtr>>(
expectedSize: 16,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<AutoLayoutDefaultPacking<UIntPtr>>(
expectedSize: 16,
expectedOffsetByte: 8,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMinPacking<UIntPtr>>(
expectedSize: 16,
expectedOffsetByte: 8,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMaxPacking<UIntPtr>>(
expectedSize: 16,
expectedOffsetByte: 8,
expectedOffsetValue: 0
);
}
else
{
succeeded &= Test<DefaultLayoutDefaultPacking<UIntPtr>>(
expectedSize: 8,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<SequentialLayoutDefaultPacking<UIntPtr>>(
expectedSize: 8,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<SequentialLayoutMinPacking<UIntPtr>>(
expectedSize: 5,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMaxPacking<UIntPtr>>(
expectedSize: 8,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<AutoLayoutDefaultPacking<UIntPtr>>(
expectedSize: 8,
expectedOffsetByte: 4,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMinPacking<UIntPtr>>(
expectedSize: 8,
expectedOffsetByte: 4,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMaxPacking<UIntPtr>>(
expectedSize: 8,
expectedOffsetByte: 4,
expectedOffsetValue: 0
);
}
return succeeded;
}
static bool TestVector64()
{
bool succeeded = true;
succeeded &= Test<DefaultLayoutDefaultPacking<Vector64<byte>>>(
expectedSize: 16,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<SequentialLayoutDefaultPacking<Vector64<byte>>>(
expectedSize: 16,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<SequentialLayoutMinPacking<Vector64<byte>>>(
expectedSize: 9,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMaxPacking<Vector64<byte>>>(
expectedSize: 16,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
if (RuntimeInformation.ProcessArchitecture != Architecture.X86)
{
succeeded &= Test<AutoLayoutDefaultPacking<Vector64<byte>>>(
expectedSize: 16,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<AutoLayoutMinPacking<Vector64<byte>>>(
expectedSize: 16,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<AutoLayoutMaxPacking<Vector64<byte>>>(
expectedSize: 16,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
}
else
{
succeeded &= Test<AutoLayoutDefaultPacking<Vector64<byte>>>(
expectedSize: 12,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<AutoLayoutMinPacking<Vector64<byte>>>(
expectedSize: 12,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<AutoLayoutMaxPacking<Vector64<byte>>>(
expectedSize: 12,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
}
return succeeded;
}
static bool TestVector128()
{
bool succeeded = true;
if (RuntimeInformation.ProcessArchitecture == Architecture.Arm)
{
// The Procedure Call Standard for ARM defines this type as having 8-byte alignment
succeeded &= Test<DefaultLayoutDefaultPacking<Vector128<byte>>>(
expectedSize: 24,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<SequentialLayoutDefaultPacking<Vector128<byte>>>(
expectedSize: 24,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<SequentialLayoutMaxPacking<Vector128<byte>>>(
expectedSize: 24,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
}
else
{
succeeded &= Test<DefaultLayoutDefaultPacking<Vector128<byte>>>(
expectedSize: 32,
expectedOffsetByte: 0,
expectedOffsetValue: 16
);
succeeded &= Test<SequentialLayoutDefaultPacking<Vector128<byte>>>(
expectedSize: 32,
expectedOffsetByte: 0,
expectedOffsetValue: 16
);
succeeded &= Test<SequentialLayoutMaxPacking<Vector128<byte>>>(
expectedSize: 32,
expectedOffsetByte: 0,
expectedOffsetValue: 16
);
}
succeeded &= Test<SequentialLayoutMinPacking<Vector128<byte>>>(
expectedSize: 17,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
if (RuntimeInformation.ProcessArchitecture != Architecture.X86)
{
succeeded &= Test<AutoLayoutDefaultPacking<Vector128<byte>>>(
expectedSize: 24,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<AutoLayoutMinPacking<Vector128<byte>>>(
expectedSize: 24,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<AutoLayoutMaxPacking<Vector128<byte>>>(
expectedSize: 24,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
}
else
{
succeeded &= Test<AutoLayoutDefaultPacking<Vector128<byte>>>(
expectedSize: 20,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<AutoLayoutMinPacking<Vector128<byte>>>(
expectedSize: 20,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<AutoLayoutMaxPacking<Vector128<byte>>>(
expectedSize: 20,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
}
return succeeded;
}
static bool TestVector256()
{
bool succeeded = true;
if (RuntimeInformation.ProcessArchitecture == Architecture.Arm)
{
// The Procedure Call Standard for ARM defines this type as having 8-byte alignment
succeeded &= Test<DefaultLayoutDefaultPacking<Vector256<byte>>>(
expectedSize: 40,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<SequentialLayoutDefaultPacking<Vector256<byte>>>(
expectedSize: 40,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<SequentialLayoutMaxPacking<Vector256<byte>>>(
expectedSize: 40,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
}
else if (RuntimeInformation.ProcessArchitecture == Architecture.Arm64)
{
// The Procedure Call Standard for ARM64 defines this type as having 16-byte alignment
succeeded &= Test<DefaultLayoutDefaultPacking<Vector256<byte>>>(
expectedSize: 48,
expectedOffsetByte: 0,
expectedOffsetValue: 16
);
succeeded &= Test<SequentialLayoutDefaultPacking<Vector256<byte>>>(
expectedSize: 48,
expectedOffsetByte: 0,
expectedOffsetValue: 16
);
succeeded &= Test<SequentialLayoutMaxPacking<Vector256<byte>>>(
expectedSize: 48,
expectedOffsetByte: 0,
expectedOffsetValue: 16
);
}
else
{
succeeded &= Test<DefaultLayoutDefaultPacking<Vector256<byte>>>(
expectedSize: 64,
expectedOffsetByte: 0,
expectedOffsetValue: 32
);
succeeded &= Test<SequentialLayoutDefaultPacking<Vector256<byte>>>(
expectedSize: 64,
expectedOffsetByte: 0,
expectedOffsetValue: 32
);
succeeded &= Test<SequentialLayoutMaxPacking<Vector256<byte>>>(
expectedSize: 64,
expectedOffsetByte: 0,
expectedOffsetValue: 32
);
}
succeeded &= Test<SequentialLayoutMinPacking<Vector256<byte>>>(
expectedSize: 33,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
if (RuntimeInformation.ProcessArchitecture != Architecture.X86)
{
succeeded &= Test<AutoLayoutDefaultPacking<Vector256<byte>>>(
expectedSize: 40,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<AutoLayoutMinPacking<Vector256<byte>>>(
expectedSize: 40,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<AutoLayoutMaxPacking<Vector256<byte>>>(
expectedSize: 40,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
}
else
{
succeeded &= Test<AutoLayoutDefaultPacking<Vector256<byte>>>(
expectedSize: 36,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<AutoLayoutMinPacking<Vector256<byte>>>(
expectedSize: 36,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<AutoLayoutMaxPacking<Vector256<byte>>>(
expectedSize: 36,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
}
return succeeded;
}
static bool TestMyVector64()
{
bool succeeded = true;
succeeded &= Test<DefaultLayoutDefaultPacking<MyVector64<byte>>>(
expectedSize: 9,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutDefaultPacking<MyVector64<byte>>>(
expectedSize: 9,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMinPacking<MyVector64<byte>>>(
expectedSize: 9,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMaxPacking<MyVector64<byte>>>(
expectedSize: 9,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
if (Environment.Is64BitProcess)
{
succeeded &= Test<AutoLayoutDefaultPacking<MyVector64<byte>>>(
expectedSize: 16,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<AutoLayoutMinPacking<MyVector64<byte>>>(
expectedSize: 16,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<AutoLayoutMaxPacking<MyVector64<byte>>>(
expectedSize: 16,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
}
else
{
succeeded &= Test<AutoLayoutDefaultPacking<MyVector64<byte>>>(
expectedSize: 12,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<AutoLayoutMinPacking<MyVector64<byte>>>(
expectedSize: 12,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<AutoLayoutMaxPacking<MyVector64<byte>>>(
expectedSize: 12,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
}
return succeeded;
}
static bool TestMyVector128()
{
bool succeeded = true;
succeeded &= Test<DefaultLayoutDefaultPacking<MyVector128<byte>>>(
expectedSize: 17,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutDefaultPacking<MyVector128<byte>>>(
expectedSize: 17,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMinPacking<MyVector128<byte>>>(
expectedSize: 17,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMaxPacking<MyVector128<byte>>>(
expectedSize: 17,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
if (Environment.Is64BitProcess)
{
succeeded &= Test<AutoLayoutDefaultPacking<MyVector128<byte>>>(
expectedSize: 24,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<AutoLayoutMinPacking<MyVector128<byte>>>(
expectedSize: 24,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<AutoLayoutMaxPacking<MyVector128<byte>>>(
expectedSize: 24,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
}
else
{
succeeded &= Test<AutoLayoutDefaultPacking<MyVector128<byte>>>(
expectedSize: 20,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<AutoLayoutMinPacking<MyVector128<byte>>>(
expectedSize: 20,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<AutoLayoutMaxPacking<MyVector128<byte>>>(
expectedSize: 20,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
}
return succeeded;
}
static bool TestMyVector256()
{
bool succeeded = true;
succeeded &= Test<DefaultLayoutDefaultPacking<MyVector256<byte>>>(
expectedSize: 33,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutDefaultPacking<MyVector256<byte>>>(
expectedSize: 33,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMinPacking<MyVector256<byte>>>(
expectedSize: 33,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMaxPacking<MyVector256<byte>>>(
expectedSize: 33,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
if (Environment.Is64BitProcess)
{
succeeded &= Test<AutoLayoutDefaultPacking<MyVector256<byte>>>(
expectedSize: 40,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<AutoLayoutMinPacking<MyVector256<byte>>>(
expectedSize: 40,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<AutoLayoutMaxPacking<MyVector256<byte>>>(
expectedSize: 40,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
}
else
{
succeeded &= Test<AutoLayoutDefaultPacking<MyVector256<byte>>>(
expectedSize: 36,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<AutoLayoutMinPacking<MyVector256<byte>>>(
expectedSize: 36,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<AutoLayoutMaxPacking<MyVector256<byte>>>(
expectedSize: 36,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
}
return succeeded;
}
static bool Test<T>(int expectedSize, int expectedOffsetByte, int expectedOffsetValue) where T : ITestStructure
{
bool succeeded = true;
var testStructure = default(T);
int size = testStructure.Size;
if (size != expectedSize)
{
Console.WriteLine($"Unexpected Size for {testStructure.GetType()}.");
Console.WriteLine($" Expected: {expectedSize}; Actual: {size}");
succeeded = false;
}
int offsetByte = testStructure.OffsetOfByte;
if (offsetByte != expectedOffsetByte)
{
Console.WriteLine($"Unexpected Offset for {testStructure.GetType()}.Byte.");
Console.WriteLine($" Expected: {expectedOffsetByte}; Actual: {offsetByte}");
succeeded = false;
}
int offsetValue = testStructure.OffsetOfValue;
if (offsetValue != expectedOffsetValue)
{
Console.WriteLine($"Unexpected Offset for {testStructure.GetType()}.Value.");
Console.WriteLine($" Expected: {expectedOffsetValue}; Actual: {offsetValue}");
succeeded = false;
}
if (!succeeded)
{
Console.WriteLine();
}
return succeeded;
}
internal static int OffsetOf<T, U>(ref T origin, ref U target)
{
return Unsafe.ByteOffset(ref origin, ref Unsafe.As<U, T>(ref target)).ToInt32();
}
}
| |
// ReSharper disable All
using System.Collections.Generic;
using System.Dynamic;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Controllers;
using Frapid.ApplicationState.Cache;
using Frapid.ApplicationState.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Frapid.Account.DataAccess;
using Frapid.DataAccess;
using Frapid.DataAccess.Models;
using Frapid.Framework;
using Frapid.Framework.Extensions;
using Frapid.WebApi;
namespace Frapid.Account.Api
{
/// <summary>
/// Provides a direct HTTP access to perform various tasks such as adding, editing, and removing Fb Access Tokens.
/// </summary>
[RoutePrefix("api/v1.0/account/fb-access-token")]
public class FbAccessTokenController : FrapidApiController
{
/// <summary>
/// The FbAccessToken repository.
/// </summary>
private IFbAccessTokenRepository FbAccessTokenRepository;
public FbAccessTokenController()
{
}
public FbAccessTokenController(IFbAccessTokenRepository repository)
{
this.FbAccessTokenRepository = repository;
}
protected override void Initialize(HttpControllerContext context)
{
base.Initialize(context);
if (this.FbAccessTokenRepository == null)
{
this.FbAccessTokenRepository = new Frapid.Account.DataAccess.FbAccessToken
{
_Catalog = this.MetaUser.Catalog,
_LoginId = this.MetaUser.LoginId,
_UserId = this.MetaUser.UserId
};
}
}
/// <summary>
/// Creates meta information of "fb access token" entity.
/// </summary>
/// <returns>Returns the "fb access token" meta information to perform CRUD operation.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("meta")]
[Route("~/api/account/fb-access-token/meta")]
[RestAuthorize]
public EntityView GetEntityView()
{
return new EntityView
{
PrimaryKey = "user_id",
Columns = new List<EntityColumn>()
{
new EntityColumn
{
ColumnName = "user_id",
PropertyName = "UserId",
DataType = "int",
DbDataType = "int4",
IsNullable = false,
IsPrimaryKey = true,
IsSerial = false,
Value = "",
MaxLength = 0
},
new EntityColumn
{
ColumnName = "fb_user_id",
PropertyName = "FbUserId",
DataType = "string",
DbDataType = "text",
IsNullable = true,
IsPrimaryKey = false,
IsSerial = false,
Value = "",
MaxLength = 0
},
new EntityColumn
{
ColumnName = "token",
PropertyName = "Token",
DataType = "string",
DbDataType = "text",
IsNullable = true,
IsPrimaryKey = false,
IsSerial = false,
Value = "",
MaxLength = 0
}
}
};
}
/// <summary>
/// Counts the number of fb access tokens.
/// </summary>
/// <returns>Returns the count of the fb access tokens.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("count")]
[Route("~/api/account/fb-access-token/count")]
[RestAuthorize]
public long Count()
{
try
{
return this.FbAccessTokenRepository.Count();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns all collection of fb access token.
/// </summary>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("all")]
[Route("~/api/account/fb-access-token/all")]
[RestAuthorize]
public IEnumerable<Frapid.Account.Entities.FbAccessToken> GetAll()
{
try
{
return this.FbAccessTokenRepository.GetAll();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns collection of fb access token for export.
/// </summary>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("export")]
[Route("~/api/account/fb-access-token/export")]
[RestAuthorize]
public IEnumerable<dynamic> Export()
{
try
{
return this.FbAccessTokenRepository.Export();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns an instance of fb access token.
/// </summary>
/// <param name="userId">Enter UserId to search for.</param>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("{userId}")]
[Route("~/api/account/fb-access-token/{userId}")]
[RestAuthorize]
public Frapid.Account.Entities.FbAccessToken Get(int userId)
{
try
{
return this.FbAccessTokenRepository.Get(userId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
[AcceptVerbs("GET", "HEAD")]
[Route("get")]
[Route("~/api/account/fb-access-token/get")]
[RestAuthorize]
public IEnumerable<Frapid.Account.Entities.FbAccessToken> Get([FromUri] int[] userIds)
{
try
{
return this.FbAccessTokenRepository.Get(userIds);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns the first instance of fb access token.
/// </summary>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("first")]
[Route("~/api/account/fb-access-token/first")]
[RestAuthorize]
public Frapid.Account.Entities.FbAccessToken GetFirst()
{
try
{
return this.FbAccessTokenRepository.GetFirst();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns the previous instance of fb access token.
/// </summary>
/// <param name="userId">Enter UserId to search for.</param>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("previous/{userId}")]
[Route("~/api/account/fb-access-token/previous/{userId}")]
[RestAuthorize]
public Frapid.Account.Entities.FbAccessToken GetPrevious(int userId)
{
try
{
return this.FbAccessTokenRepository.GetPrevious(userId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns the next instance of fb access token.
/// </summary>
/// <param name="userId">Enter UserId to search for.</param>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("next/{userId}")]
[Route("~/api/account/fb-access-token/next/{userId}")]
[RestAuthorize]
public Frapid.Account.Entities.FbAccessToken GetNext(int userId)
{
try
{
return this.FbAccessTokenRepository.GetNext(userId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns the last instance of fb access token.
/// </summary>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("last")]
[Route("~/api/account/fb-access-token/last")]
[RestAuthorize]
public Frapid.Account.Entities.FbAccessToken GetLast()
{
try
{
return this.FbAccessTokenRepository.GetLast();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a paginated collection containing 10 fb access tokens on each page, sorted by the property UserId.
/// </summary>
/// <returns>Returns the first page from the collection.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("")]
[Route("~/api/account/fb-access-token")]
[RestAuthorize]
public IEnumerable<Frapid.Account.Entities.FbAccessToken> GetPaginatedResult()
{
try
{
return this.FbAccessTokenRepository.GetPaginatedResult();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a paginated collection containing 10 fb access tokens on each page, sorted by the property UserId.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the resultset.</param>
/// <returns>Returns the requested page from the collection.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("page/{pageNumber}")]
[Route("~/api/account/fb-access-token/page/{pageNumber}")]
[RestAuthorize]
public IEnumerable<Frapid.Account.Entities.FbAccessToken> GetPaginatedResult(long pageNumber)
{
try
{
return this.FbAccessTokenRepository.GetPaginatedResult(pageNumber);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Counts the number of fb access tokens using the supplied filter(s).
/// </summary>
/// <param name="filters">The list of filter conditions.</param>
/// <returns>Returns the count of filtered fb access tokens.</returns>
[AcceptVerbs("POST")]
[Route("count-where")]
[Route("~/api/account/fb-access-token/count-where")]
[RestAuthorize]
public long CountWhere([FromBody]JArray filters)
{
try
{
List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer());
return this.FbAccessTokenRepository.CountWhere(f);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a filtered and paginated collection containing 10 fb access tokens on each page, sorted by the property UserId.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the resultset. If you provide a negative number, the result will not be paginated.</param>
/// <param name="filters">The list of filter conditions.</param>
/// <returns>Returns the requested page from the collection using the supplied filters.</returns>
[AcceptVerbs("POST")]
[Route("get-where/{pageNumber}")]
[Route("~/api/account/fb-access-token/get-where/{pageNumber}")]
[RestAuthorize]
public IEnumerable<Frapid.Account.Entities.FbAccessToken> GetWhere(long pageNumber, [FromBody]JArray filters)
{
try
{
List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer());
return this.FbAccessTokenRepository.GetWhere(pageNumber, f);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Counts the number of fb access tokens using the supplied filter name.
/// </summary>
/// <param name="filterName">The named filter.</param>
/// <returns>Returns the count of filtered fb access tokens.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("count-filtered/{filterName}")]
[Route("~/api/account/fb-access-token/count-filtered/{filterName}")]
[RestAuthorize]
public long CountFiltered(string filterName)
{
try
{
return this.FbAccessTokenRepository.CountFiltered(filterName);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a filtered and paginated collection containing 10 fb access tokens on each page, sorted by the property UserId.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the resultset. If you provide a negative number, the result will not be paginated.</param>
/// <param name="filterName">The named filter.</param>
/// <returns>Returns the requested page from the collection using the supplied filters.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("get-filtered/{pageNumber}/{filterName}")]
[Route("~/api/account/fb-access-token/get-filtered/{pageNumber}/{filterName}")]
[RestAuthorize]
public IEnumerable<Frapid.Account.Entities.FbAccessToken> GetFiltered(long pageNumber, string filterName)
{
try
{
return this.FbAccessTokenRepository.GetFiltered(pageNumber, filterName);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Displayfield is a lightweight key/value collection of fb access tokens.
/// </summary>
/// <returns>Returns an enumerable key/value collection of fb access tokens.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("display-fields")]
[Route("~/api/account/fb-access-token/display-fields")]
[RestAuthorize]
public IEnumerable<Frapid.DataAccess.Models.DisplayField> GetDisplayFields()
{
try
{
return this.FbAccessTokenRepository.GetDisplayFields();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// A custom field is a user defined field for fb access tokens.
/// </summary>
/// <returns>Returns an enumerable custom field collection of fb access tokens.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("custom-fields")]
[Route("~/api/account/fb-access-token/custom-fields")]
[RestAuthorize]
public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields()
{
try
{
return this.FbAccessTokenRepository.GetCustomFields(null);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// A custom field is a user defined field for fb access tokens.
/// </summary>
/// <returns>Returns an enumerable custom field collection of fb access tokens.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("custom-fields/{resourceId}")]
[Route("~/api/account/fb-access-token/custom-fields/{resourceId}")]
[RestAuthorize]
public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields(string resourceId)
{
try
{
return this.FbAccessTokenRepository.GetCustomFields(resourceId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Adds or edits your instance of FbAccessToken class.
/// </summary>
/// <param name="fbAccessToken">Your instance of fb access tokens class to add or edit.</param>
[AcceptVerbs("POST")]
[Route("add-or-edit")]
[Route("~/api/account/fb-access-token/add-or-edit")]
[RestAuthorize]
public object AddOrEdit([FromBody]Newtonsoft.Json.Linq.JArray form)
{
dynamic fbAccessToken = form[0].ToObject<ExpandoObject>(JsonHelper.GetJsonSerializer());
List<Frapid.DataAccess.Models.CustomField> customFields = form[1].ToObject<List<Frapid.DataAccess.Models.CustomField>>(JsonHelper.GetJsonSerializer());
if (fbAccessToken == null)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed));
}
try
{
return this.FbAccessTokenRepository.AddOrEdit(fbAccessToken, customFields);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Adds your instance of FbAccessToken class.
/// </summary>
/// <param name="fbAccessToken">Your instance of fb access tokens class to add.</param>
[AcceptVerbs("POST")]
[Route("add/{fbAccessToken}")]
[Route("~/api/account/fb-access-token/add/{fbAccessToken}")]
[RestAuthorize]
public void Add(Frapid.Account.Entities.FbAccessToken fbAccessToken)
{
if (fbAccessToken == null)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed));
}
try
{
this.FbAccessTokenRepository.Add(fbAccessToken);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Edits existing record with your instance of FbAccessToken class.
/// </summary>
/// <param name="fbAccessToken">Your instance of FbAccessToken class to edit.</param>
/// <param name="userId">Enter the value for UserId in order to find and edit the existing record.</param>
[AcceptVerbs("PUT")]
[Route("edit/{userId}")]
[Route("~/api/account/fb-access-token/edit/{userId}")]
[RestAuthorize]
public void Edit(int userId, [FromBody] Frapid.Account.Entities.FbAccessToken fbAccessToken)
{
if (fbAccessToken == null)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed));
}
try
{
this.FbAccessTokenRepository.Update(fbAccessToken, userId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
private List<ExpandoObject> ParseCollection(JArray collection)
{
return JsonConvert.DeserializeObject<List<ExpandoObject>>(collection.ToString(), JsonHelper.GetJsonSerializerSettings());
}
/// <summary>
/// Adds or edits multiple instances of FbAccessToken class.
/// </summary>
/// <param name="collection">Your collection of FbAccessToken class to bulk import.</param>
/// <returns>Returns list of imported userIds.</returns>
/// <exception cref="DataAccessException">Thrown when your any FbAccessToken class in the collection is invalid or malformed.</exception>
[AcceptVerbs("POST")]
[Route("bulk-import")]
[Route("~/api/account/fb-access-token/bulk-import")]
[RestAuthorize]
public List<object> BulkImport([FromBody]JArray collection)
{
List<ExpandoObject> fbAccessTokenCollection = this.ParseCollection(collection);
if (fbAccessTokenCollection == null || fbAccessTokenCollection.Count.Equals(0))
{
return null;
}
try
{
return this.FbAccessTokenRepository.BulkImport(fbAccessTokenCollection);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Deletes an existing instance of FbAccessToken class via UserId.
/// </summary>
/// <param name="userId">Enter the value for UserId in order to find and delete the existing record.</param>
[AcceptVerbs("DELETE")]
[Route("delete/{userId}")]
[Route("~/api/account/fb-access-token/delete/{userId}")]
[RestAuthorize]
public void Delete(int userId)
{
try
{
this.FbAccessTokenRepository.Delete(userId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
}
}
| |
using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;
using Microsoft.Xna.Framework.Graphics;
using System.Xml;
using System.Xml.Serialization;
using AnimationFrame = Gum.Graphics.Animation.AnimationFrame;
using AnimationChainList = Gum.Graphics.Animation.AnimationChainList;
using ToolsUtilities;
using Gum.Graphics.Animation;
using TimeMeasurementUnit = Gum.Graphics.Animation.TimeMeasurementUnit;
namespace Gum.Content.AnimationChain
{
[XmlType("AnimationChainArraySave")]
public class AnimationChainListSave : IDisposable
{
#if ANDROID || IOS
public static bool ManualDeserialization = true;
#else
public static bool ManualDeserialization = false;
#endif
#region Fields
private List<string> mToRuntimeErrors = new List<string>();
[XmlIgnore]
public string FileName
{
set { mFileName = value; }
get { return mFileName; }
}
#endregion
#region Properties
[XmlIgnore]
public List<string> ToRuntimeErrors
{
get { return mToRuntimeErrors; }
}
[XmlIgnore]
protected string mFileName;
/// <summary>
/// Whether files (usually image files) referenced by this object (and .achx) are
/// relative to the .achx itself. If false, then file references will be stored as absolute.
/// If true, then file reference,s will be stored relative to the .achx itself. This value should
/// be true so that a .achx can be moved to a different file system or computer and still
/// have valid references.
/// </summary>
public bool FileRelativeTextures = true;
public TimeMeasurementUnit TimeMeasurementUnit;
public TextureCoordinateType CoordinateType = TextureCoordinateType.UV;
[XmlElementAttribute("AnimationChain")]
public List<AnimationChainSave> AnimationChains;
#endregion
#region Methods
#region Constructor
public AnimationChainListSave()
{
AnimationChains = new List<AnimationChainSave>();
}
#endregion
public static AnimationChainListSave FromFile(string fileName)
{
AnimationChainListSave toReturn = null;
if (ManualDeserialization)
{
throw new NotImplementedException();
//toReturn = DeserializeManually(fileName);
}
else
{
toReturn =
FileManager.XmlDeserialize<AnimationChainListSave>(fileName);
}
if (FileManager.IsRelative(fileName))
fileName = FileManager.MakeAbsolute(fileName);
toReturn.mFileName = fileName;
return toReturn;
}
/// <summary>
/// Create a "save" object from a regular animation chain list
/// </summary>
//public static AnimationChainListSave FromAnimationChainList(AnimationChainList chainList)
//{
// AnimationChainListSave achlist = new AnimationChainListSave();
// achlist.FileRelativeTextures = chainList.FileRelativeTextures;
// achlist.TimeMeasurementUnit = chainList.TimeMeasurementUnit;
// achlist.mFileName = chainList.Name;
// List<AnimationChainSave> newChains = new List<AnimationChainSave>(chainList.Count);
// for (int i = 0; i < chainList.Count; i++)
// {
// AnimationChainSave ach = AnimationChainSave.FromAnimationChain(chainList[i], achlist.TimeMeasurementUnit);
// newChains.Add(ach);
// }
// achlist.AnimationChains = newChains;
// return achlist;
//}
//public List<string> GetReferencedFiles(RelativeType relativeType)
//{
// List<string> referencedFiles = new List<string>();
// foreach (AnimationChainSave acs in this.AnimationChains)
// {
// //if(acs.ParentFile
// if (acs.ParentFile != null && acs.ParentFile.EndsWith(".gif"))
// {
// referencedFiles.Add(acs.ParentFile);
// }
// else
// {
// foreach (AnimationFrameSave afs in acs.Frames)
// {
// string texture = FileManager.Standardize( afs.TextureName, null, false );
// if (FileManager.GetExtension(texture).StartsWith("gif"))
// {
// texture = FileManager.RemoveExtension(texture) + ".gif";
// }
// if (!string.IsNullOrEmpty(texture) && !referencedFiles.Contains(texture))
// {
// referencedFiles.Add(texture);
// }
// }
// }
// }
// if (relativeType == RelativeType.Absolute)
// {
// string directory = FileManager.GetDirectory(FileName);
// for (int i = 0; i < referencedFiles.Count; i++)
// {
// referencedFiles[i] = directory + referencedFiles[i];
// }
// }
// return referencedFiles;
//}
//public void Save(string fileName)
//{
// if (FileRelativeTextures)
// {
// MakeRelative(fileName);
// }
// FileManager.XmlSerialize(this, fileName);
//}
public AnimationChainList ToAnimationChainList(string contentManagerName)
{
return ToAnimationChainList(contentManagerName, true);
}
public AnimationChainList ToAnimationChainList(string contentManagerName, bool throwError)
{
mToRuntimeErrors.Clear();
AnimationChainList list = new AnimationChainList();
list.FileRelativeTextures = FileRelativeTextures;
list.TimeMeasurementUnit = TimeMeasurementUnit;
list.Name = mFileName;
string oldRelativeDirectory = FileManager.RelativeDirectory;
try
{
if (this.FileRelativeTextures)
{
FileManager.RelativeDirectory = FileManager.GetDirectory(mFileName);
}
foreach (AnimationChainSave animationChain in this.AnimationChains)
{
try
{
Gum.Graphics.Animation.AnimationChain newChain = null;
newChain = animationChain.ToAnimationChain(contentManagerName, this.TimeMeasurementUnit, this.CoordinateType);
newChain.mIndexInLoadedAchx = list.Count;
newChain.ParentAchxFileName = mFileName;
list.Add(newChain);
}
catch (Exception e)
{
mToRuntimeErrors.Add(e.ToString());
if (throwError)
{
throw new Exception("Error loading AnimationChain", e);
}
}
}
}
finally
{
FileManager.RelativeDirectory = oldRelativeDirectory;
}
return list;
}
public void Dispose()
{
// do nothing, just need this to add it to the loader manager
}
//AnimationChainList ToAnimationChainList(string contentManagerName, TextureAtlas textureAtlas, bool throwError)
//{
// mToRuntimeErrors.Clear();
// AnimationChainList list = new AnimationChainList();
// list.FileRelativeTextures = FileRelativeTextures;
// list.TimeMeasurementUnit = TimeMeasurementUnit;
// list.Name = mFileName;
// string oldRelativeDirectory = FileManager.RelativeDirectory;
// try
// {
// if (this.FileRelativeTextures)
// {
// FileManager.RelativeDirectory = FileManager.GetDirectory(mFileName);
// }
// foreach (AnimationChainSave animationChain in this.AnimationChains)
// {
// try
// {
// FlatRedBall.Graphics.Animation.AnimationChain newChain = null;
// if (textureAtlas == null)
// {
// newChain = animationChain.ToAnimationChain(contentManagerName, this.TimeMeasurementUnit, this.CoordinateType);
// }
// else
// {
// newChain = animationChain.ToAnimationChain(textureAtlas, this.TimeMeasurementUnit);
// }
// newChain.mIndexInLoadedAchx = list.Count;
// newChain.ParentAchxFileName = mFileName;
// list.Add(newChain);
// }
// catch (Exception e)
// {
// mToRuntimeErrors.Add(e.ToString());
// if (throwError)
// {
// throw new Exception("Error loading AnimationChain", e);
// }
// }
// }
// }
// finally
// {
// FileManager.RelativeDirectory = oldRelativeDirectory;
// }
// return list;
//}
//public AnimationChainList ToAnimationChainList(Graphics.Texture.TextureAtlas textureAtlas)
//{
// return ToAnimationChainList(null, textureAtlas, true);
//}
//private void MakeRelative(string fileName)
//{
// string oldRelativeDirectory = FileManager.RelativeDirectory;
// string newRelativeDirectory = FileManager.GetDirectory(fileName);
// FileManager.RelativeDirectory = newRelativeDirectory;
// foreach (AnimationChainSave acs in AnimationChains)
// {
// acs.MakeRelative();
// }
// FileManager.RelativeDirectory = oldRelativeDirectory;
//}
//private static AnimationChainListSave DeserializeManually(string fileName)
//{
// AnimationChainListSave toReturn = new AnimationChainListSave();
// System.Xml.Linq.XDocument xDocument = null;
// using (var stream = FileManager.GetStreamForFile(fileName))
// {
// xDocument = System.Xml.Linq.XDocument.Load(stream);
// }
// System.Xml.Linq.XElement foundElement = null;
// foreach (var element in xDocument.Elements())
// {
// if (element.Name.LocalName == "AnimationChainArraySave")
// {
// foundElement = element;
// break;
// }
// }
// LoadFromElement(toReturn, foundElement);
// return toReturn;
//}
#endregion
}
}
| |
using System;
using System.IO;
using System.Reflection;
using System.Text;
namespace SERFS {
using MbUnit.Framework;
[TestFixture]
class TestSerfs {
private Serfs _serfs;
[SetUp]
public void Setup() {
_serfs = new Serfs("TestTemplates");
}
[Test]
public void OpenValidFileGetsStream() {
using (Stream stream = _serfs.OpenRead("test.txt")) {
Assert.IsNotNull(stream);
}
}
[Test]
public void ReadValidFileGetsString() {
string s = _serfs.Read("test.txt");
Assert.AreEqual("Hello Serfs\r\n", s);
}
[Test]
public void ReadTextValidFileGetsString() {
string s = _serfs.ReadText("test.txt");
Assert.AreEqual("Hello Serfs\n", s);
}
[Test]
public void OpenInvalidFileGetsNull() {
using (Stream stream = _serfs.OpenRead("not_here_test.txt")) {
Assert.IsNull(stream);
}
}
[Test]
public void ReadInvalidFileGetsNull() {
string s = _serfs.Read("not test.txt");
Assert.IsNull(s);
}
[Test]
public void ReadErfStream() {
using (Stream stream = _serfs.OpenRead("test.txt")) {
StreamReader reader = new StreamReader(stream);
Assert.AreEqual("Hello Serfs", reader.ReadLine());
}
}
[Test]
public void ReadErfStreamCaseInsensitive() {
using (Stream stream = _serfs.OpenRead("TeSt.txt")) {
StreamReader reader = new StreamReader(stream);
Assert.AreEqual("Hello Serfs", reader.ReadLine());
}
}
[Test]
public void ReadPathWithDotsAndSpaces() {
using (Stream stream = _serfs.OpenRead("A folder with . and spaces/A file with . and spaces.txt")) {
StreamReader reader = new StreamReader(stream);
Assert.AreEqual("I am a file with . and spaces.txt", reader.ReadLine());
}
}
[Test]
public void ReadFolderStartingWithNumeric() {
using (Stream stream = _serfs.OpenRead("1.2.3/test.txt")) {
StreamReader reader = new StreamReader(stream);
Assert.AreEqual("A test file in a folder with numerics", reader.ReadLine());
}
}
[Test]
public void ReadFileStartingWithNumeric() {
using (Stream stream = _serfs.OpenRead("A folder with . and spaces/404.txt")) {
StreamReader reader = new StreamReader(stream);
Assert.AreEqual("This file starts with a numeric", reader.ReadLine());
}
}
[Test]
public void ReadPathUsingBackslash() {
using (Stream stream = _serfs.OpenRead("A folder with . and spaces\\A file with . and spaces.txt")) {
StreamReader reader = new StreamReader(stream);
Assert.AreEqual("I am a file with . and spaces.txt", reader.ReadLine());
}
}
[Test]
public void UnmountedFoldersAreNotFound() {
using (Stream stream = _serfs.OpenRead("moretest.txt")) {
Assert.IsNull(stream);
}
}
[Test]
public void AdditionalMountedFoldersAreFound() {
_serfs.Mount("MoreTemplates").Mount("ExtraTemplates");
using (Stream stream = _serfs.OpenRead("moretest.txt")) {
StreamReader reader = new StreamReader(stream);
Assert.AreEqual("Hello again Serfs", reader.ReadLine());
}
using (Stream stream = _serfs.OpenRead("extratest.txt")) {
StreamReader reader = new StreamReader(stream);
Assert.AreEqual("Hello again extra Serfs", reader.ReadLine());
}
}
[Test]
public void AdditionalAssembliesAreFound() {
_serfs.AddAssembly("ResourcesForSerfsTest", "ResourcesForSerfsTest").Mount("Files");
using (Stream stream = _serfs.OpenRead("HelloSerfs.txt")) {
StreamReader reader = new StreamReader(stream);
Assert.AreEqual("Hello Serfs!", reader.ReadLine());
}
}
[Test]
public void AdditionalAssembliesWithDefaultPath() {
_serfs.AddAssembly("ResourcesForSerfsTest");
using (Stream stream = _serfs.OpenRead("Files/HelloSerfs.txt")) {
StreamReader reader = new StreamReader(stream);
Assert.AreEqual("Hello Serfs!", reader.ReadLine());
}
}
[Test]
public void AdditionalAssembliesNotFound() {
Assert.IsFalse(_serfs.IgnoreMissingAssemblies);
Assert.IsNull(_serfs.AddAssembly("AnAssemblyThatDoesNotExist"));
}
[Test]
public void MissingAssembliesCanBeIgnored() {
_serfs.IgnoreMissingAssemblies = true;
Assert.IsTrue(_serfs.IgnoreMissingAssemblies);
Assert.IsNotNull(_serfs.AddAssembly("AnAssemblyThatDoesNotExist"));
}
[Test]
public void DuplicateAdditionalAssemblies() {
_serfs.AddAssembly("ResourcesForSerfsTest");
_serfs.AddAssembly("ResourcesForSerfsTest");
using (Stream stream = _serfs.OpenRead("Files/HelloSerfs.txt")) {
StreamReader reader = new StreamReader(stream);
Assert.AreEqual("Hello Serfs!", reader.ReadLine());
}
}
[Test]
public void LeadingDotSlashIsOk() {
string s = _serfs.Read("./test.txt");
Assert.AreEqual("Hello Serfs\r\n", s);
}
[Test]
public void LeadingDotBackSlashIsOk() {
string s = _serfs.Read(".\\test.txt");
Assert.AreEqual("Hello Serfs\r\n", s);
}
[Test]
public void FilesCanBeOutsideFolders() {
_serfs.Mount("/");
string s = _serfs.Read("FileOutSideFolder.txt");
Assert.StartsWith("I am FileOutSideFolder", s);
}
[Test]
public void CanSpecifyAssemblyPrefixAndFolder() {
Assembly resources = AppDomain.CurrentDomain.Load("ResourcesForSerfsTest");
_serfs = new Serfs(resources, "ResourcesForSerfsTest", "Files");
using (Stream stream = _serfs.OpenRead("HelloSerfs.txt")) {
StreamReader reader = new StreamReader(stream);
Assert.AreEqual("Hello Serfs!", reader.ReadLine());
}
}
[Test]
public void CanUseDifferentDecoderForStream() {
_serfs.Decoder = new UpCaseDecoder();
using (Stream stream = _serfs.OpenRead("Test.txt")) {
StreamReader reader = new StreamReader(stream);
Assert.AreEqual("HELLO SERFS", reader.ReadLine());
}
}
[Test]
public void CanUseDifferentDecoderForString() {
_serfs.Decoder = new UpCaseDecoder();
string s = _serfs.Read("test.txt");
Assert.AreEqual("HELLO SERFS\r\n", s);
}
private class UpCaseDecoder : IStreamDecoder {
public Stream Decode(Stream stream) {
StreamReader reader = new StreamReader(stream);
string content = reader.ReadToEnd().ToUpperInvariant();
return new MemoryStream(Encoding.UTF8.GetBytes(content));
}
}
[Test]
public void CanCheckIfFileExists() {
Assert.IsTrue(_serfs.Exists(".\\test.txt"));
Assert.IsFalse(_serfs.Exists(".\\test.text"));
Assert.IsTrue(_serfs.Exists("/test.txt"));
}
[Test]
public void CanCheckIfFolderExists() {
Assert.IsTrue(_serfs.FolderExists(".\\"));
Assert.IsFalse(_serfs.FolderExists(".\\test.txt"));
Assert.IsTrue(_serfs.FolderExists("/"));
Assert.IsFalse(_serfs.FolderExists("/test.txt"));
Assert.IsTrue(_serfs.FolderExists("/1.2.3"));
Assert.IsTrue(_serfs.FolderExists("1.2.3"));
Assert.IsTrue(_serfs.FolderExists("\\A folder with . and spaces"));
Assert.IsTrue(_serfs.FolderExists("A folder with . and spaces"));
}
[Test]
public void CanGetAllResourceNames() {
_serfs.AddAssembly("ResourcesForSerfsTest", "ResourcesForSerfsTest").Mount("Files");
string[] resources = _serfs.ResourceNames();
Assert.AreEqual(5, resources.Length);
Assert.Contains(resources, "test.txt");
Assert.Contains(resources, "HelloSerfs.txt");
Assert.Contains(resources, "_1._2._3.test.txt");
}
[Test]
public void CanGetResourceNameSubset() {
_serfs.AddAssembly("ResourcesForSerfsTest", "ResourcesForSerfsTest").Mount("Files");
string[] resources = _serfs.ResourceNames("A folder with . and spaces");
Assert.AreEqual(2, resources.Length);
Assert.Contains(resources, "404.txt");
Assert.Contains(resources, "A file with . and spaces.txt");
resources = _serfs.ResourceNames("/A folder with . and spaces");
Assert.AreEqual(2, resources.Length);
Assert.Contains(resources, "404.txt");
Assert.Contains(resources, "A file with . and spaces.txt");
resources = _serfs.ResourceNames("\\A folder with . and spaces");
Assert.AreEqual(2, resources.Length);
Assert.Contains(resources, "404.txt");
Assert.Contains(resources, "A file with . and spaces.txt");
}
}
}
| |
// 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.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.Routing.Patterns;
using Moq;
using Xunit;
namespace Microsoft.AspNetCore.Builder
{
public class RequestDelegateEndpointRouteBuilderExtensionsTest
{
private ModelEndpointDataSource GetBuilderEndpointDataSource(IEndpointRouteBuilder endpointRouteBuilder)
{
return Assert.IsType<ModelEndpointDataSource>(Assert.Single(endpointRouteBuilder.DataSources));
}
private RouteEndpointBuilder GetRouteEndpointBuilder(IEndpointRouteBuilder endpointRouteBuilder)
{
return Assert.IsType<RouteEndpointBuilder>(Assert.Single(GetBuilderEndpointDataSource(endpointRouteBuilder).EndpointBuilders));
}
public static object[][] MapMethods
{
get
{
IEndpointConventionBuilder MapGet(IEndpointRouteBuilder routes, string template, RequestDelegate action) =>
routes.MapGet(template, action);
IEndpointConventionBuilder MapPost(IEndpointRouteBuilder routes, string template, RequestDelegate action) =>
routes.MapPost(template, action);
IEndpointConventionBuilder MapPut(IEndpointRouteBuilder routes, string template, RequestDelegate action) =>
routes.MapPut(template, action);
IEndpointConventionBuilder MapDelete(IEndpointRouteBuilder routes, string template, RequestDelegate action) =>
routes.MapDelete(template, action);
IEndpointConventionBuilder Map(IEndpointRouteBuilder routes, string template, RequestDelegate action) =>
routes.Map(template, action);
return new object[][]
{
new object[] { (Func<IEndpointRouteBuilder, string, RequestDelegate, IEndpointConventionBuilder>)MapGet },
new object[] { (Func<IEndpointRouteBuilder, string, RequestDelegate, IEndpointConventionBuilder>)MapPost },
new object[] { (Func<IEndpointRouteBuilder, string, RequestDelegate, IEndpointConventionBuilder>)MapPut },
new object[] { (Func<IEndpointRouteBuilder, string, RequestDelegate, IEndpointConventionBuilder>)MapDelete },
new object[] { (Func<IEndpointRouteBuilder, string, RequestDelegate, IEndpointConventionBuilder>)Map },
};
}
}
[Fact]
public void MapEndpoint_StringPattern_BuildsEndpoint()
{
// Arrange
var builder = new DefaultEndpointRouteBuilder(Mock.Of<IApplicationBuilder>());
RequestDelegate requestDelegate = (d) => null;
// Act
var endpointBuilder = builder.Map("/", requestDelegate);
// Assert
var endpointBuilder1 = GetRouteEndpointBuilder(builder);
Assert.Equal(requestDelegate, endpointBuilder1.RequestDelegate);
Assert.Equal("/", endpointBuilder1.DisplayName);
Assert.Equal("/", endpointBuilder1.RoutePattern.RawText);
}
[Fact]
public void MapEndpoint_TypedPattern_BuildsEndpoint()
{
// Arrange
var builder = new DefaultEndpointRouteBuilder(Mock.Of<IApplicationBuilder>());
RequestDelegate requestDelegate = (d) => null;
// Act
var endpointBuilder = builder.Map(RoutePatternFactory.Parse("/"), requestDelegate);
// Assert
var endpointBuilder1 = GetRouteEndpointBuilder(builder);
Assert.Equal(requestDelegate, endpointBuilder1.RequestDelegate);
Assert.Equal("/", endpointBuilder1.DisplayName);
Assert.Equal("/", endpointBuilder1.RoutePattern.RawText);
}
[Fact]
public void MapEndpoint_AttributesCollectedAsMetadata()
{
// Arrange
var builder = new DefaultEndpointRouteBuilder(Mock.Of<IApplicationBuilder>());
// Act
var endpointBuilder = builder.Map(RoutePatternFactory.Parse("/"), Handle);
// Assert
var endpointBuilder1 = GetRouteEndpointBuilder(builder);
Assert.Equal("/", endpointBuilder1.RoutePattern.RawText);
Assert.Equal(2, endpointBuilder1.Metadata.Count);
Assert.IsType<Attribute1>(endpointBuilder1.Metadata[0]);
Assert.IsType<Attribute2>(endpointBuilder1.Metadata[1]);
}
[Fact]
public void MapEndpoint_GeneratedDelegateWorks()
{
// Arrange
var builder = new DefaultEndpointRouteBuilder(Mock.Of<IApplicationBuilder>());
Expression<RequestDelegate> handler = context => Task.CompletedTask;
// Act
var endpointBuilder = builder.Map(RoutePatternFactory.Parse("/"), handler.Compile());
// Assert
var endpointBuilder1 = GetRouteEndpointBuilder(builder);
Assert.Equal("/", endpointBuilder1.RoutePattern.RawText);
}
[Fact]
public void MapEndpoint_PrecedenceOfMetadata_BuilderMetadataReturned()
{
// Arrange
var builder = new DefaultEndpointRouteBuilder(Mock.Of<IApplicationBuilder>());
// Act
var endpointBuilder = builder.MapMethods("/", new[] { "METHOD" }, HandleHttpMetdata);
endpointBuilder.WithMetadata(new HttpMethodMetadata(new[] { "BUILDER" }));
// Assert
var dataSource = Assert.Single(builder.DataSources);
var endpoint = Assert.Single(dataSource.Endpoints);
Assert.Equal(3, endpoint.Metadata.Count);
Assert.Equal("ATTRIBUTE", GetMethod(endpoint.Metadata[0]));
Assert.Equal("METHOD", GetMethod(endpoint.Metadata[1]));
Assert.Equal("BUILDER", GetMethod(endpoint.Metadata[2]));
Assert.Equal("BUILDER", endpoint.Metadata.GetMetadata<IHttpMethodMetadata>().HttpMethods.Single());
string GetMethod(object metadata)
{
var httpMethodMetadata = Assert.IsAssignableFrom<IHttpMethodMetadata>(metadata);
return Assert.Single(httpMethodMetadata.HttpMethods);
}
}
[Theory]
[MemberData(nameof(MapMethods))]
public void Map_EndpointMetadataNotDuplicated(Func<IEndpointRouteBuilder, string, RequestDelegate, IEndpointConventionBuilder> map)
{
// Arrange
var builder = new DefaultEndpointRouteBuilder(Mock.Of<IApplicationBuilder>());
// Act
var endpointBuilder = map(builder, "/", context => Task.CompletedTask).WithMetadata(new EndpointNameMetadata("MapMe"));
// Assert
var ds = GetBuilderEndpointDataSource(builder);
_ = ds.Endpoints;
_ = ds.Endpoints;
_ = ds.Endpoints;
Assert.Single(ds.Endpoints);
var endpoint = ds.Endpoints.Single();
Assert.Single(endpoint.Metadata.GetOrderedMetadata<IEndpointNameMetadata>());
}
[Theory]
[MemberData(nameof(MapMethods))]
public void AddingMetadataAfterBuildingEndpointThrows(Func<IEndpointRouteBuilder, string, RequestDelegate, IEndpointConventionBuilder> map)
{
// Arrange
var builder = new DefaultEndpointRouteBuilder(Mock.Of<IApplicationBuilder>());
// Act
var endpointBuilder = map(builder, "/", context => Task.CompletedTask).WithMetadata(new EndpointNameMetadata("MapMe"));
// Assert
var ds = GetBuilderEndpointDataSource(builder);
var endpoint = Assert.Single(ds.Endpoints);
Assert.Single(endpoint.Metadata.GetOrderedMetadata<IEndpointNameMetadata>());
Assert.Throws<InvalidOperationException>(() => endpointBuilder.WithMetadata(new RouteNameMetadata("Foo")));
}
[Attribute1]
[Attribute2]
private static Task Handle(HttpContext context) => Task.CompletedTask;
[HttpMethod("ATTRIBUTE")]
private static Task HandleHttpMetdata(HttpContext context) => Task.CompletedTask;
private class HttpMethodAttribute : Attribute, IHttpMethodMetadata
{
public bool AcceptCorsPreflight => false;
public IReadOnlyList<string> HttpMethods { get; }
public HttpMethodAttribute(params string[] httpMethods)
{
HttpMethods = httpMethods;
}
}
private class Attribute1 : Attribute
{
}
private class Attribute2 : Attribute
{
}
}
}
| |
// Copyright (c) .NET Foundation. 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.Globalization;
using System.Linq;
using Microsoft.AspNetCore.Mvc.ApplicationModels;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.WebHooks.Metadata;
using Microsoft.AspNetCore.WebHooks.Properties;
namespace Microsoft.AspNetCore.WebHooks.ApplicationModels
{
/// <summary>
/// <para>
/// An <see cref="IApplicationModelProvider"/> implementation that adds <see cref="IWebHookMetadata"/>
/// references to <see cref="ActionModel.Properties"/> collections of WebHook actions. Later WebHook
/// <see cref="IApplicationModelProvider"/> implementations (<see cref="WebHookActionModelFilterProvider"/>,
/// <see cref="WebHookBindingInfoProvider"/> and <see cref="WebHookSelectorModelProvider"/>) use this metadata.
/// </para>
/// <para>
/// Detects duplicate, missing and invalid <see cref="IWebHookMetadata"/> attributes and services.
/// </para>
/// </summary>
public class WebHookActionModelPropertyProvider : IApplicationModelProvider
{
private readonly IReadOnlyList<IWebHookBindingMetadata> _bindingMetadata;
private readonly IReadOnlyList<IWebHookBodyTypeMetadataService> _bodyTypeMetadata;
private readonly IReadOnlyList<IWebHookEventFromBodyMetadata> _eventFromBodyMetadata;
private readonly IReadOnlyList<IWebHookEventMetadata> _eventMetadata;
private readonly IReadOnlyList<IWebHookFilterMetadata> _filterMetadata;
private readonly IReadOnlyList<IWebHookGetHeadRequestMetadata> _getHeadRequestMetadata;
private readonly IReadOnlyList<IWebHookPingRequestMetadata> _pingRequestMetadata;
private readonly IReadOnlyList<IWebHookVerifyCodeMetadata> _verifyCodeMetadata;
/// <summary>
/// Instantiates a new <see cref="WebHookActionModelPropertyProvider"/> instance with the given metadata.
/// </summary>
/// <param name="bindingMetadata">The collection of <see cref="IWebHookBindingMetadata"/> services.</param>
/// <param name="bodyTypeMetadata">
/// The collection of <see cref="IWebHookBodyTypeMetadataService"/> services.
/// </param>
/// <param name="eventFromBodyMetadata">
/// The collection of <see cref="IWebHookEventFromBodyMetadata"/> services.
/// </param>
/// <param name="eventMetadata">The collection of <see cref="IWebHookEventMetadata"/> services.</param>
/// <param name="filterMetadata">The collection of <see cref="IWebHookFilterMetadata"/> services.</param>
/// <param name="getHeadRequestMetadata">
/// The collection of <see cref="IWebHookGetHeadRequestMetadata"/> services.
/// </param>
/// <param name="pingRequestMetadata">
/// The collection of <see cref="IWebHookPingRequestMetadata"/> services.
/// </param>
/// <param name="verifyCodeMetadata">
/// The collection of <see cref="IWebHookVerifyCodeMetadata"/> services.
/// </param>
public WebHookActionModelPropertyProvider(
IEnumerable<IWebHookBindingMetadata> bindingMetadata,
IEnumerable<IWebHookBodyTypeMetadataService> bodyTypeMetadata,
IEnumerable<IWebHookEventFromBodyMetadata> eventFromBodyMetadata,
IEnumerable<IWebHookEventMetadata> eventMetadata,
IEnumerable<IWebHookFilterMetadata> filterMetadata,
IEnumerable<IWebHookGetHeadRequestMetadata> getHeadRequestMetadata,
IEnumerable<IWebHookPingRequestMetadata> pingRequestMetadata,
IEnumerable<IWebHookVerifyCodeMetadata> verifyCodeMetadata)
{
_bindingMetadata = bindingMetadata.ToArray();
_bodyTypeMetadata = bodyTypeMetadata.ToArray();
_eventFromBodyMetadata = eventFromBodyMetadata.ToArray();
_eventMetadata = eventMetadata.ToArray();
_filterMetadata = filterMetadata.ToArray();
_getHeadRequestMetadata = getHeadRequestMetadata.ToArray();
_pingRequestMetadata = pingRequestMetadata.ToArray();
_verifyCodeMetadata = verifyCodeMetadata.ToArray();
// Check for duplicate registrations in the collections tracked here.
EnsureUniqueRegistrations(_bindingMetadata);
EnsureUniqueRegistrations(_bodyTypeMetadata);
EnsureUniqueRegistrations(_eventFromBodyMetadata);
EnsureUniqueRegistrations(_eventMetadata);
EnsureUniqueRegistrations(_filterMetadata);
EnsureUniqueRegistrations(_getHeadRequestMetadata);
EnsureUniqueRegistrations(_pingRequestMetadata);
EnsureUniqueRegistrations(_verifyCodeMetadata);
EnsureValidBodyTypeMetadata(_bodyTypeMetadata);
EnsureValidEventFromBodyMetadata(_eventFromBodyMetadata, _eventMetadata);
// Confirm no incomplete receivers exist i.e. no metadata services exist for a receiver unless one
// implements IWebHookBodyTypeMetadataService.
var receiverNames = _bindingMetadata
.Cast<IWebHookReceiver>()
.Concat(_eventFromBodyMetadata)
.Concat(_eventMetadata)
.Concat(_filterMetadata)
.Concat(_getHeadRequestMetadata)
.Concat(_pingRequestMetadata)
.Concat(_verifyCodeMetadata)
.Select(metadata => metadata.ReceiverName)
.Distinct(StringComparer.OrdinalIgnoreCase);
foreach (var receiverName in receiverNames)
{
var bodyTypeMetadataService = _bodyTypeMetadata
.FirstOrDefault(metadata => metadata.IsApplicable(receiverName));
EnsureValidBodyTypeMetadata(bodyTypeMetadataService, receiverName);
}
}
/// <summary>
/// Gets the <see cref="IApplicationModelProvider.Order"/> value used in all
/// <see cref="WebHookActionModelPropertyProvider"/> instances. The WebHook
/// <see cref="IApplicationModelProvider"/> order is
/// <list type="number">
/// <item>
/// Add <see cref="IWebHookMetadata"/> references to the <see cref="ActionModel.Properties"/> collections of
/// WebHook actions and validate those <see cref="IWebHookMetadata"/> attributes and services (in this
/// provider).
/// </item>
/// <item>
/// Add routing information (<see cref="SelectorModel"/> settings) to <see cref="ActionModel"/>s of WebHook
/// actions (in <see cref="WebHookSelectorModelProvider"/>).
/// </item>
/// <item>
/// Add filters to the <see cref="ActionModel.Filters"/> collections of WebHook actions (in
/// <see cref="WebHookActionModelFilterProvider"/>).
/// </item>
/// <item>
/// Add model binding information (<see cref="BindingInfo"/> settings) to <see cref="ParameterModel"/>s of
/// WebHook actions (in <see cref="WebHookBindingInfoProvider"/>).
/// </item>
/// </list>
/// </summary>
/// <value>
/// Chosen to ensure WebHook providers run after MVC's
/// <see cref="Mvc.Internal.DefaultApplicationModelProvider"/>.
/// </value>
public static int Order => -500;
/// <inheritdoc />
int IApplicationModelProvider.Order => Order;
/// <inheritdoc />
public void OnProvidersExecuting(ApplicationModelProviderContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
for (var i = 0; i < context.Result.Controllers.Count; i++)
{
var controller = context.Result.Controllers[i];
for (var j = 0; j < controller.Actions.Count; j++)
{
var action = controller.Actions[j];
Apply(action);
}
}
}
/// <inheritdoc />
public void OnProvidersExecuted(ApplicationModelProviderContext context)
{
// No-op
}
private void Apply(ActionModel action)
{
var attribute = action.Attributes.OfType<WebHookAttribute>().FirstOrDefault();
if (attribute == null)
{
// Not a WebHook handler.
return;
}
var receiverName = attribute.ReceiverName;
if (receiverName == null)
{
// Pass along most IWebHook*Metadata instances. No need for the IWebHookFilterMetadata collection
// because WebHookFilterProvider is always registered.
if (_bindingMetadata.Count != 0)
{
action.Properties[typeof(IWebHookBindingMetadata)] = _bindingMetadata;
}
if (_eventFromBodyMetadata.Count != 0)
{
action.Properties[typeof(IWebHookEventFromBodyMetadata)] = _eventFromBodyMetadata;
}
if (_getHeadRequestMetadata.Count != 0)
{
action.Properties[typeof(IWebHookGetHeadRequestMetadata)] = _getHeadRequestMetadata;
}
if (_pingRequestMetadata.Count != 0)
{
action.Properties[typeof(IWebHookPingRequestMetadata)] = _pingRequestMetadata;
}
if (_verifyCodeMetadata.Count != 0)
{
action.Properties[typeof(IWebHookVerifyCodeMetadata)] = _verifyCodeMetadata;
}
}
else
{
var bindingMetadata = _bindingMetadata.FirstOrDefault(metadata => metadata.IsApplicable(receiverName));
if (bindingMetadata != null)
{
action.Properties[typeof(IWebHookBindingMetadata)] = bindingMetadata;
}
var eventFromBodyMetadata = _eventFromBodyMetadata
.FirstOrDefault(metadata => metadata.IsApplicable(receiverName));
if (eventFromBodyMetadata != null)
{
action.Properties[typeof(IWebHookEventFromBodyMetadata)] = eventFromBodyMetadata;
}
var filterMetadata = _filterMetadata.FirstOrDefault(metadata => metadata.IsApplicable(receiverName));
if (filterMetadata != null)
{
action.Properties[typeof(IWebHookFilterMetadata)] = filterMetadata;
}
var getHeadRequestMetadata = _getHeadRequestMetadata
.FirstOrDefault(metadata => metadata.IsApplicable(receiverName));
if (getHeadRequestMetadata != null)
{
action.Properties[typeof(IWebHookGetHeadRequestMetadata)] = getHeadRequestMetadata;
}
var pingRequestMetadata = _pingRequestMetadata
.FirstOrDefault(metadata => metadata.IsApplicable(receiverName));
if (pingRequestMetadata != null)
{
action.Properties[typeof(IWebHookPingRequestMetadata)] = pingRequestMetadata;
}
var verifyCodeMetadata = _verifyCodeMetadata
.FirstOrDefault(metadata => metadata.IsApplicable(receiverName));
if (verifyCodeMetadata != null)
{
action.Properties[typeof(IWebHookVerifyCodeMetadata)] = verifyCodeMetadata;
}
}
IWebHookEventMetadata eventMetadata;
if (receiverName == null)
{
eventMetadata = null;
if (_eventMetadata.Count != 0)
{
action.Properties[typeof(IWebHookEventMetadata)] = _eventMetadata;
}
}
else
{
eventMetadata = _eventMetadata.FirstOrDefault(metadata => metadata.IsApplicable(receiverName));
if (eventMetadata != null)
{
action.Properties[typeof(IWebHookEventMetadata)] = eventMetadata;
}
}
if (attribute is IWebHookEventSelectorMetadata eventSelector &&
eventSelector.EventName != null)
{
EnsureValidEventMetadata(eventMetadata, receiverName);
action.Properties[typeof(IWebHookEventSelectorMetadata)] = eventSelector;
}
if (receiverName == null)
{
// WebHookVerifyBodyTypeFilter should look up (and verify) the applicable
// IWebHookBodyTypeMetadataService per-request.
action.Properties[typeof(IWebHookBodyTypeMetadataService)] = _bodyTypeMetadata;
}
else
{
var bodyTypeMetadata = _bodyTypeMetadata
.FirstOrDefault(metadata => metadata.IsApplicable(receiverName));
EnsureValidBodyTypeMetadata(bodyTypeMetadata, receiverName);
action.Properties[typeof(IWebHookBodyTypeMetadataService)] = bodyTypeMetadata;
}
// Ignore IWebHookBodyTypeMetadata metadata if attribute's BodyTypes property is null or if an attribute
// other than GeneralWebHookAttribute implements this interface.
if (receiverName == null &&
attribute is IWebHookBodyTypeMetadata actionBodyTypeMetadata &&
actionBodyTypeMetadata.BodyType.HasValue)
{
EnsureValidBodyTypeMetadata(actionBodyTypeMetadata);
action.Properties[typeof(IWebHookBodyTypeMetadata)] = actionBodyTypeMetadata;
}
}
/// <summary>
/// Ensure members of given <paramref name="bodyTypeMetadataServices"/> collection are valid. That is, ensure
/// each has a valid <see cref="IWebHookBodyTypeMetadataService.BodyType"/>.
/// </summary>
/// <param name="bodyTypeMetadataServices">
/// The collection of <see cref="IWebHookBodyTypeMetadataService"/> services.
/// </param>
protected void EnsureValidBodyTypeMetadata(
IReadOnlyList<IWebHookBodyTypeMetadataService> bodyTypeMetadataServices)
{
if (bodyTypeMetadataServices == null)
{
throw new ArgumentNullException(nameof(bodyTypeMetadataServices));
}
foreach (var bodyTypeMetadata in bodyTypeMetadataServices)
{
if (!Enum.IsDefined(typeof(WebHookBodyType), bodyTypeMetadata.BodyType))
{
var message = string.Format(
CultureInfo.CurrentCulture,
Resources.General_InvalidEnumValue,
typeof(WebHookBodyType),
bodyTypeMetadata.BodyType);
throw new InvalidOperationException(message);
}
}
}
/// <summary>
/// Ensure given <paramref name="bodyTypeMetadata"/> is valid.
/// </summary>
/// <param name="bodyTypeMetadata">
/// An attribute that implements <see cref="IWebHookBodyTypeMetadata"/>.
/// </param>
protected void EnsureValidBodyTypeMetadata(IWebHookBodyTypeMetadata bodyTypeMetadata)
{
if (bodyTypeMetadata == null)
{
throw new ArgumentNullException(nameof(bodyTypeMetadata));
}
if (!bodyTypeMetadata.BodyType.HasValue)
{
return;
}
if (!Enum.IsDefined(typeof(WebHookBodyType), bodyTypeMetadata.BodyType.Value))
{
var message = string.Format(
CultureInfo.CurrentCulture,
Resources.General_InvalidEnumValue,
typeof(WebHookBodyType),
bodyTypeMetadata.BodyType.Value);
throw new InvalidOperationException(message);
}
}
/// <summary>
/// Ensure given <paramref name="bodyTypeMetadata"/> is not <see langword="null"/>.
/// An <see cref="IWebHookBodyTypeMetadataService"/> service is mandatory for every receiver.
/// </summary>
/// <param name="bodyTypeMetadata">
/// The <paramref name="receiverName"/> receiver's <see cref="IWebHookBodyTypeMetadataService"/>, if any.
/// </param>
/// <param name="receiverName">The name of an available <see cref="IWebHookReceiver"/>.</param>
/// <remarks>
/// Called to detect both incomplete receiver metadata and receiver-specific attributes for which no metadata
/// has been registered.
/// </remarks>
protected void EnsureValidBodyTypeMetadata(
IWebHookBodyTypeMetadataService bodyTypeMetadata,
string receiverName)
{
if (receiverName == null)
{
throw new ArgumentNullException(nameof(receiverName));
}
if (bodyTypeMetadata == null)
{
var message = string.Format(
CultureInfo.CurrentCulture,
Resources.PropertyProvider_MissingMetadata,
receiverName,
typeof(IWebHookBodyTypeMetadataService));
throw new InvalidOperationException(message);
}
}
/// <summary>
/// Ensure given <paramref name="eventMetadata"/> is not <see langword="null"/>. An
/// <see cref="IWebHookEventMetadata"/> service is mandatory for receivers with an attribute that implements
/// <see cref="IWebHookEventSelectorMetadata"/>.
/// </summary>
/// <param name="eventMetadata">
/// The <paramref name="receiverName"/> receiver's <see cref="IWebHookEventMetadata"/>, if any.
/// </param>
/// <param name="receiverName">The name of an available <see cref="IWebHookReceiver"/>.</param>
protected void EnsureValidEventMetadata(IWebHookEventMetadata eventMetadata, string receiverName)
{
if (receiverName == null)
{
// Unusual case likely involves a GeneralWebHookAttribute subclass that implements
// IWebHookEventSelectorMetadata. Assume developer adds runtime checks for IWebHookEventMetadata.
return;
}
if (eventMetadata == null)
{
// IWebHookEventMetadata is mandatory when performing action selection using event names.
var message = string.Format(
CultureInfo.CurrentCulture,
Resources.PropertyProvider_MissingMetadataServices,
receiverName,
typeof(IWebHookEventSelectorMetadata),
typeof(IWebHookEventMetadata));
throw new InvalidOperationException(message);
}
}
/// <summary>
/// Ensure members of given <paramref name="eventFromBodyMetadata"/> collection are valid. That is, confirm
/// no receiver provides both <see cref="IWebHookEventFromBodyMetadata"/> and
/// <see cref="IWebHookEventMetadata"/> services.
/// </summary>
/// <param name="eventFromBodyMetadata">
/// The collection of <see cref="IWebHookEventFromBodyMetadata"/> services.
/// </param>
/// <param name="eventMetadata">
/// The collection of <see cref="IWebHookEventMetadata"/> services.
/// </param>
protected void EnsureValidEventFromBodyMetadata(
IReadOnlyList<IWebHookEventFromBodyMetadata> eventFromBodyMetadata,
IReadOnlyList<IWebHookEventMetadata> eventMetadata)
{
if (eventFromBodyMetadata == null)
{
throw new ArgumentNullException(nameof(eventFromBodyMetadata));
}
if (eventMetadata == null)
{
throw new ArgumentNullException(nameof(eventMetadata));
}
var receiverWithConflictingMetadata = eventFromBodyMetadata
.FirstOrDefault(metadata => eventMetadata.Any(
innerMetadata => innerMetadata.IsApplicable(metadata.ReceiverName)));
if (receiverWithConflictingMetadata != null)
{
var message = string.Format(
CultureInfo.CurrentCulture,
Resources.PropertyProvider_ConflictingMetadataServices,
receiverWithConflictingMetadata.ReceiverName,
typeof(IWebHookEventFromBodyMetadata),
typeof(IWebHookEventMetadata));
throw new InvalidOperationException(message);
}
}
/// <summary>
/// Ensure given <paramref name="services"/> collection does not contain duplicate registrations. That is,
/// confirm the <typeparamref name="TService"/> registration for each
/// <see cref="IWebHookReceiver.ReceiverName"/> is unique.
/// </summary>
/// <typeparam name="TService">
/// The <see cref="IWebHookReceiver"/> interface of the <paramref name="services"/> to check.
/// </typeparam>
/// <param name="services">The collection of <typeparamref name="TService"/> services to check.</param>
/// <exception cref="InvalidOperationException">
/// Thrown if duplicates exist in <paramref name="services"/>.
/// </exception>
protected void EnsureUniqueRegistrations<TService>(IReadOnlyList<TService> services)
where TService : IWebHookReceiver
{
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
var duplicateMetadataGroup = services
.GroupBy(item => item.ReceiverName, StringComparer.OrdinalIgnoreCase)
.FirstOrDefault(group => group.Count() != 1);
if (duplicateMetadataGroup != null)
{
var message = string.Format(
CultureInfo.CurrentCulture,
Resources.PropertyProvider_DuplicateMetadata,
duplicateMetadataGroup.Key, // ReceiverName
typeof(TService));
throw new InvalidOperationException(message);
}
}
}
}
| |
#region Copyright
// Copyright 2014 Myrcon Pty. Ltd.
//
// 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
using Potato.Database.Shared.Builders.Equalities;
using Potato.Database.Shared.Builders.Logicals;
using Potato.Database.Shared.Builders.Methods.Data;
using Potato.Database.Shared.Builders.Modifiers;
using Potato.Database.Shared.Builders.Statements;
using Potato.Database.Shared.Builders.Values;
namespace Potato.Database.Shared.Test {
public abstract class TestSerializerFind {
#region TestSelectAllFromPlayer
protected IDatabaseObject TestSelectAllFromPlayerExplicit = new Find()
.Collection(new Collection() {
Name = "Player"
});
protected IDatabaseObject TestSelectAllFromPlayerImplicit = new Find()
.Collection("Player");
public abstract void TestSelectAllFromPlayer();
#endregion
#region TestSelectDistinctAllFromPlayer
protected IDatabaseObject TestSelectDistinctAllFromPlayerExplicit = new Find()
.Modifier(new Distinct())
.Collection(new Collection() {
Name = "Player"
});
protected IDatabaseObject TestSelectDistinctAllFromPlayerImplicit = new Find()
.Modifier(new Distinct())
.Collection("Player");
public abstract void TestSelectDistinctAllFromPlayer();
#endregion
#region TestSelectAllFromPlayerWhereNameEqualsPhogue
protected IDatabaseObject TestSelectAllFromPlayerWhereNameEqualsPhogueExplicit = new Find()
.Condition(new Equals() {
new Field() {
Name = "Name"
},
new StringValue() {
Data = "Phogue"
}
})
.Collection(new Collection() {
Name = "Player"
});
protected IDatabaseObject TestSelectAllFromPlayerWhereNameEqualsPhogueImplicit = new Find()
.Condition("Name", "Phogue")
.Collection("Player");
public abstract void TestSelectAllFromPlayerWhereNameEqualsPhogue();
#endregion
#region TestSelectAllFromPlayerWhereKdrGreaterThanEqualTo31D
protected IDatabaseObject TestSelectAllFromPlayerWhereKdrGreaterThanEqualTo31DExplicit = new Find()
.Condition(new GreaterThanEquals() {
new Field() {
Name = "Kdr"
},
new NumericValue() {
Double = 3.1D
}
})
.Collection(new Collection() {
Name = "Player"
});
protected IDatabaseObject TestSelectAllFromPlayerWhereKdrGreaterThanEqualTo31DImplicit = new Find()
.Condition("Kdr", new GreaterThanEquals(), 3.1D)
.Collection("Player");
public abstract void TestSelectAllFromPlayerWhereKdrGreaterThanEqualTo31D();
#endregion
#region TestSelectAllFromPlayerWhereKdrLessThanEqualTo31D
protected IDatabaseObject TestSelectAllFromPlayerWhereKdrLessThanEqualTo31DExplicit = new Find()
.Condition(new LessThanEquals() {
new Field() {
Name = "Kdr"
},
new NumericValue() {
Double = 3.1D
}
})
.Collection(new Collection() {
Name = "Player"
});
protected IDatabaseObject TestSelectAllFromPlayerWhereKdrLessThanEqualTo31DImplicit = new Find()
.Condition("Kdr", new LessThanEquals(), 3.1D)
.Collection("Player");
public abstract void TestSelectAllFromPlayerWhereKdrLessThanEqualTo31D();
#endregion
#region TestSelectAllFromPlayerWherePlayerNameEqualsPhogue
protected IDatabaseObject TestSelectAllFromPlayerWherePlayerNameEqualsPhogueExplicit = new Find()
.Condition(new Equals() {
new Field() {
Name = "Name"
}.Collection(
new Collection() {
Name = "Player"
}
),
new StringValue() {
Data = "Phogue"
}
})
.Collection(new Collection() {
Name = "Player"
});
protected IDatabaseObject TestSelectAllFromPlayerWherePlayerNameEqualsPhogueImplicit = new Find()
.Condition("Player", "Name", "Phogue")
.Collection("Player");
public abstract void TestSelectAllFromPlayerWherePlayerNameEqualsPhogue();
#endregion
#region TestSelectScoreFromPlayerWhereNameEqualsPhogue
protected IDatabaseObject TestSelectScoreFromPlayerWhereNameEqualsPhogueExplicit = new Find()
.Condition(new Equals() {
new Field() {
Name = "Name"
},
new StringValue() {
Data = "Phogue"
}
})
.Collection(new Collection() {
Name = "Player"
})
.Field(new Field() {
Name = "Score"
});
protected IDatabaseObject TestSelectScoreFromPlayerWhereNameEqualsPhogueImplicit = new Find()
.Condition("Name", "Phogue")
.Collection("Player")
.Field("Score");
public abstract void TestSelectScoreFromPlayerWhereNameEqualsPhogue();
#endregion
#region TestSelectScoreRankFromPlayerWhereNameEqualsPhogue
protected IDatabaseObject TestSelectScoreRankFromPlayerWhereNameEqualsPhogueExplicit = new Find()
.Condition(new Equals() {
new Field() {
Name = "Name"
},
new StringValue() {
Data = "Phogue"
}
})
.Collection(new Collection() {
Name = "Player"
})
.Field(new Field() {
Name = "Score"
})
.Field(new Field() {
Name = "Rank"
});
protected IDatabaseObject TestSelectScoreRankFromPlayerWhereNameEqualsPhogueImplicit = new Find()
.Condition("Name", "Phogue")
.Collection("Player")
.Field("Score")
.Field("Rank");
public abstract void TestSelectScoreRankFromPlayerWhereNameEqualsPhogue();
#endregion
#region TestSelectAllFromPlayerWhereNameEqualsPhogueAndScoreEqualsTen
protected IDatabaseObject TestSelectAllFromPlayerWhereNameEqualsPhogueAndScoreEqualsTenExplicit = new Find()
.Condition(new Equals() {
new Field() {
Name = "Name"
},
new StringValue() {
Data = "Phogue"
}
})
.Condition(new Equals() {
new Field() {
Name = "Score"
},
new NumericValue() {
Long = 10
}
})
.Collection(new Collection() {
Name = "Player"
});
protected IDatabaseObject TestSelectAllFromPlayerWhereNameEqualsPhogueAndScoreEqualsTenImplicit = new Find()
.Condition("Name", "Phogue")
.Condition("Score", 10)
.Collection("Player");
public abstract void TestSelectAllFromPlayerWhereNameEqualsPhogueAndScoreEqualsTen();
#endregion
#region TestSelectAllFromPlayerWhereNameEqualsPhogueOrZaeed
protected IDatabaseObject TestSelectAllFromPlayerWhereNameEqualsPhogueOrZaeedExplicit = new Find()
.Condition(new Or() {
new Equals() {
new Field() {
Name = "Name"
},
new StringValue() {
Data = "Phogue"
}
},
new Equals() {
new Field() {
Name = "Name"
},
new StringValue() {
Data = "Zaeed"
}
}
})
.Collection(new Collection() {
Name = "Player"
});
protected IDatabaseObject TestSelectAllFromPlayerWhereNameEqualsPhogueOrZaeedImplicit = new Find()
.Condition(new Or().Condition("Name", "Phogue").Condition("Name", "Zaeed"))
.Collection("Player");
public abstract void TestSelectAllFromPlayerWhereNameEqualsPhogueOrZaeed();
#endregion
#region TestSelectAllFromPlayerWhereNameEqualsPhogueOrZaeedAndScoreAbove10AndBelow20
protected IDatabaseObject TestSelectAllFromPlayerWhereNameEqualsPhogueOrZaeedAndScoreAbove10AndBelow20Explicit = new Find()
.Condition(new Or() {
new Equals() {
new Field() {
Name = "Name"
},
new StringValue() {
Data = "Phogue"
}
},
new Equals() {
new Field() {
Name = "Name"
},
new StringValue() {
Data = "Zaeed"
}
}
})
.Condition(new GreaterThan() {
new Field() {
Name = "Score"
},
new NumericValue() {
Long = 10
}
})
.Condition(new LessThan() {
new Field() {
Name = "Score"
},
new NumericValue() {
Long = 20
}
})
.Collection(new Collection() {
Name = "Player"
});
protected IDatabaseObject TestSelectAllFromPlayerWhereNameEqualsPhogueOrZaeedAndScoreAbove10AndBelow20Implicit = new Find()
.Condition(new Or().Condition("Name", "Phogue").Condition("Name", "Zaeed"))
.Condition("Score", new GreaterThan(), 10)
.Condition("Score", new LessThan(), 20)
.Collection("Player");
public abstract void TestSelectAllFromPlayerWhereNameEqualsPhogueOrZaeedAndScoreAbove10AndBelow20();
#endregion
#region TestSelectAllFromPlayerWhereNameEqualsPhogueAndScoreAbove50OrNameEqualsZaeedAndScoreBelow50
protected IDatabaseObject TestSelectAllFromPlayerWhereNameEqualsPhogueAndScoreAbove50OrNameEqualsZaeedAndScoreBelow50Explicit = new Find()
.Condition(new Or() {
new And() {
new Equals() {
new Field() {
Name = "Name"
},
new StringValue() {
Data = "Phogue"
}
},
new GreaterThan() {
new Field() {
Name = "Score"
},
new NumericValue() {
Long = 50
}
}
},
new And() {
new Equals() {
new Field() {
Name = "Name"
},
new StringValue() {
Data = "Zaeed"
}
},
new LessThan() {
new Field() {
Name = "Score"
},
new NumericValue() {
Long = 50
}
}
}
})
.Collection(new Collection() {
Name = "Player"
});
protected IDatabaseObject TestSelectAllFromPlayerWhereNameEqualsPhogueAndScoreAbove50OrNameEqualsZaeedAndScoreBelow50Implicit = new Find()
.Condition(new Or()
.Condition(
new And().Condition("Name", "Phogue").Condition("Score", new GreaterThan(), 50)
)
.Condition(
new And().Condition("Name", "Zaeed").Condition("Score", new LessThan(), 50)
)
).Collection("Player");
public abstract void TestSelectAllFromPlayerWhereNameEqualsPhogueAndScoreAbove50OrNameEqualsZaeedAndScoreBelow50();
#endregion
#region TestSelectAllFromPlayerSortByScore
protected IDatabaseObject TestSelectAllFromPlayerSortByScoreExplicit = new Find()
.Collection(new Collection() {
Name = "Player"
})
.Sort(new Sort() {
Name = "Score"
});
protected IDatabaseObject TestSelectAllFromPlayerSortByScoreImplicit = new Find()
.Collection("Player")
.Sort("Score");
public abstract void TestSelectAllFromPlayerSortByScore();
#endregion
#region TestSelectAllFromPlayerSortByNameThenScoreDescending
protected IDatabaseObject TestSelectAllFromPlayerSortByNameThenScoreDescendingExplicit = new Find()
.Collection(new Collection() {
Name = "Player"
})
.Sort(new Sort() {
Name = "Name"
})
.Sort(new Sort() {
Name = "Score"
}.Modifier(new Descending()));
protected IDatabaseObject TestSelectAllFromPlayerSortByNameThenScoreDescendingImplicit = new Find()
.Collection("Player")
.Sort("Name")
.Sort(new Sort() { Name = "Score" }.Modifier(new Descending()));
public abstract void TestSelectAllFromPlayerSortByNameThenScoreDescending();
#endregion
#region TestSelectAllFromPlayerLimit1
protected IDatabaseObject TestSelectAllFromPlayerLimit1Explicit = new Find()
.Collection(new Collection() {
Name = "Player"
})
.Limit(new Limit() {
new NumericValue() {
Long = 1
}
});
protected IDatabaseObject TestSelectAllFromPlayerLimit1Implicit = new Find()
.Collection("Player")
.Limit(1);
public abstract void TestSelectAllFromPlayerLimit1();
#endregion
#region TestSelectAllFromPlayerLimit1Skip2
protected IDatabaseObject TestSelectAllFromPlayerLimit1Skip2Explicit = new Find()
.Collection(new Collection() {
Name = "Player"
})
.Limit(new Limit() {
new NumericValue() {
Long = 1
}
})
.Limit(new Skip() {
new NumericValue() {
Long = 2
}
});
protected IDatabaseObject TestSelectAllFromPlayerLimit1Skip2Implicit = new Find()
.Collection("Player")
.Limit(1)
.Skip(2);
public abstract void TestSelectAllFromPlayerLimit1Skip2();
#endregion
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.3074
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace WebsitePanel.Portal {
public partial class SettingsLyncUserPlansPolicy {
/// <summary>
/// asyncTasks control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.EnableAsyncTasksSupport asyncTasks;
/// <summary>
/// messageBox control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.UserControls.SimpleMessageBox messageBox;
/// <summary>
/// gvPlans control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.GridView gvPlans;
/// <summary>
/// secPlan control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.CollapsiblePanel secPlan;
/// <summary>
/// Plan control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel Plan;
/// <summary>
/// txtPlan control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtPlan;
/// <summary>
/// valRequirePlan control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RequiredFieldValidator valRequirePlan;
/// <summary>
/// secPlanFeatures control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.CollapsiblePanel secPlanFeatures;
/// <summary>
/// PlanFeatures control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel PlanFeatures;
/// <summary>
/// chkIM control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkIM;
/// <summary>
/// chkMobility control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkMobility;
/// <summary>
/// chkConferencing control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkConferencing;
/// <summary>
/// chkEnterpriseVoice control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkEnterpriseVoice;
/// <summary>
/// secPlanFeaturesFederation control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.CollapsiblePanel secPlanFeaturesFederation;
/// <summary>
/// PlanFeaturesFederation control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel PlanFeaturesFederation;
/// <summary>
/// chkFederation control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkFederation;
/// <summary>
/// chkRemoteUserAccess control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkRemoteUserAccess;
/// <summary>
/// secPlanFeaturesArchiving control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.CollapsiblePanel secPlanFeaturesArchiving;
/// <summary>
/// PlanFeaturesArchiving control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel PlanFeaturesArchiving;
/// <summary>
/// locArchivingPolicy control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locArchivingPolicy;
/// <summary>
/// ddArchivingPolicy control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.DropDownList ddArchivingPolicy;
/// <summary>
/// secPlanFeaturesMeeting control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.CollapsiblePanel secPlanFeaturesMeeting;
/// <summary>
/// PlanFeaturesMeeting control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel PlanFeaturesMeeting;
/// <summary>
/// chkAllowOrganizeMeetingsWithExternalAnonymous control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkAllowOrganizeMeetingsWithExternalAnonymous;
/// <summary>
/// secPlanFeaturesTelephony control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.CollapsiblePanel secPlanFeaturesTelephony;
/// <summary>
/// PlanFeaturesTelephony control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel PlanFeaturesTelephony;
/// <summary>
/// locTelephony control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locTelephony;
/// <summary>
/// ddTelephony control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.DropDownList ddTelephony;
/// <summary>
/// pnEnterpriseVoice control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel pnEnterpriseVoice;
/// <summary>
/// locTelephonyProvider control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locTelephonyProvider;
/// <summary>
/// tbTelephoneProvider control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox tbTelephoneProvider;
/// <summary>
/// btnAccept control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnAccept;
/// <summary>
/// AcceptRequiredValidator control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RequiredFieldValidator AcceptRequiredValidator;
/// <summary>
/// locDialPlan control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locDialPlan;
/// <summary>
/// ddTelephonyDialPlanPolicy control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.DropDownList ddTelephonyDialPlanPolicy;
/// <summary>
/// locVoicePolicy control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locVoicePolicy;
/// <summary>
/// ddTelephonyVoicePolicy control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.DropDownList ddTelephonyVoicePolicy;
/// <summary>
/// pnServerURI control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel pnServerURI;
/// <summary>
/// locServerURI control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locServerURI;
/// <summary>
/// tbServerURI control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox tbServerURI;
/// <summary>
/// btnAddPlan control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnAddPlan;
/// <summary>
/// btnUpdatePlan control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnUpdatePlan;
/// <summary>
/// txtStatus control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtStatus;
}
}
| |
// 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.Diagnostics;
using System.Collections;
using System.Collections.Generic;
namespace System.DirectoryServices.AccountManagement
{
public class PrincipalValueCollection<T> : IList<T>, IList
// T must be a ValueType or immutable ref type (such as string)
{
//
// IList
//
bool IList.IsFixedSize
{
get
{
return IsFixedSize;
}
}
bool IList.IsReadOnly
{
get
{
return IsReadOnly;
}
}
int IList.Add(object value)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
_inner.Add((T)value);
return Count;
}
void IList.Clear()
{
Clear();
}
bool IList.Contains(object value)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
return _inner.Contains((T)value);
}
int IList.IndexOf(object value)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
return IndexOf((T)value);
}
void IList.Insert(int index, object value)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
Insert(index, (T)value);
}
void IList.Remove(object value)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
_inner.Remove((T)value);
}
void IList.RemoveAt(int index)
{
RemoveAt(index);
}
object IList.this[int index]
{
get
{
return this[index];
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
this[index] = (T)value;
}
}
//
// ICollection
//
void ICollection.CopyTo(Array array, int index)
{
((ICollection)_inner).CopyTo(array, index);
}
int ICollection.Count
{
get
{
return _inner.Count;
}
}
bool ICollection.IsSynchronized
{
get
{
return IsSynchronized;
}
}
object ICollection.SyncRoot
{
get
{
return SyncRoot;
}
}
public bool IsSynchronized
{
get
{
return ((ICollection)_inner).IsSynchronized;
}
}
public object SyncRoot
{
get
{
return this;
}
}
//
// IEnumerable
//
IEnumerator IEnumerable.GetEnumerator()
{
return (IEnumerator)GetEnumerator();
}
//
// IList<T>
//
public bool IsFixedSize
{
get
{
return false;
}
}
public bool IsReadOnly
{
get
{
return false;
}
}
// Adds obj to the end of the list by inserting it into insertedValues.
public void Add(T value)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
_inner.Add(value);
}
public void Clear()
{
_inner.Clear();
}
public bool Contains(T value)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
return _inner.Contains(value);
}
public int IndexOf(T value)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
int index = 0;
foreach (TrackedCollection<T>.ValueEl el in _inner.combinedValues)
{
if (el.isInserted && el.insertedValue.Equals(value))
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalValueCollection", "IndexOf: found {0} on inserted at {1}", value, index);
return index;
}
if (!el.isInserted && el.originalValue.Right.Equals(value))
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalValueCollection", "IndexOf: found {0} on original at {1}", value, index);
return index;
}
index++;
}
return -1;
}
public void Insert(int index, T value)
{
_inner.MarkChange();
if (value == null)
throw new ArgumentNullException(nameof(value));
if ((index < 0) || (index > _inner.combinedValues.Count))
{
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "PrincipalValueCollection", "Insert({0}): out of range (count={1})", index, _inner.combinedValues.Count);
throw new ArgumentOutOfRangeException(nameof(index));
}
TrackedCollection<T>.ValueEl el = new TrackedCollection<T>.ValueEl();
el.isInserted = true;
el.insertedValue = value;
_inner.combinedValues.Insert(index, el);
}
public bool Remove(T value)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
return _inner.Remove(value);
}
public void RemoveAt(int index)
{
_inner.MarkChange();
if ((index < 0) || (index >= _inner.combinedValues.Count))
{
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "PrincipalValueCollection", "RemoveAt({0}): out of range (count={1})", index, _inner.combinedValues.Count);
throw new ArgumentOutOfRangeException(nameof(index));
}
TrackedCollection<T>.ValueEl el = _inner.combinedValues[index];
if (el.isInserted)
{
// We're removing an inserted value.
GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalValueCollection", "RemoveAt({0}): removing inserted", index);
_inner.combinedValues.RemoveAt(index);
}
else
{
// We're removing an original value.
GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalValueCollection", "RemoveAt({0}): removing original", index);
Pair<T, T> pair = _inner.combinedValues[index].originalValue;
_inner.combinedValues.RemoveAt(index);
_inner.removedValues.Add(pair.Left);
}
}
public T this[int index]
{
get
{
if ((index < 0) || (index >= _inner.combinedValues.Count))
{
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "PrincipalValueCollection", "this[{0}].get: out of range (count={1})", index, _inner.combinedValues.Count);
throw new ArgumentOutOfRangeException(nameof(index));
}
TrackedCollection<T>.ValueEl el = _inner.combinedValues[index];
if (el.isInserted)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalValueCollection", "this[{0}].get: is inserted {1}", index, el.insertedValue);
return el.insertedValue;
}
else
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalValueCollection", "this[{0}].get: is original {1}", index, el.originalValue.Right);
return el.originalValue.Right; // Right == current value
}
}
set
{
_inner.MarkChange();
if ((index < 0) || (index >= _inner.combinedValues.Count))
{
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "PrincipalValueCollection", "this[{0}].set: out of range (count={1})", index, _inner.combinedValues.Count);
throw new ArgumentOutOfRangeException(nameof(index));
}
if (value == null)
throw new ArgumentNullException(nameof(value));
TrackedCollection<T>.ValueEl el = _inner.combinedValues[index];
if (el.isInserted)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalValueCollection", "this[{0}].set: is inserted {1}", index, value);
el.insertedValue = value;
}
else
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalValueCollection", "this[{0}].set: is original {1}", index, value);
el.originalValue.Right = value;
}
}
}
//
// ICollection<T>
//
public void CopyTo(T[] array, int index)
{
((ICollection)this).CopyTo((Array)array, index);
}
public int Count
{
get
{
return _inner.Count;
}
}
//
// IEnumerable<T>
//
public IEnumerator<T> GetEnumerator()
{
return new ValueCollectionEnumerator<T>(_inner, _inner.combinedValues);
}
//
// Private implementation
//
private TrackedCollection<T> _inner = new TrackedCollection<T>();
//
// Internal constructor
//
internal PrincipalValueCollection()
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalValueCollection", "Ctor");
// Nothing to do here
}
//
// Load/Store implementation
//
internal void Load(List<T> values)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalValueCollection", "Load, count={0}", values.Count);
// To support reload
_inner.combinedValues.Clear();
_inner.removedValues.Clear();
foreach (T value in values)
{
// If T was a mutable reference type, would need to make a copy of value
// for the left-side of the Pair, so that changes to the value in the
// right-side wouldn't also change the left-side value (due to aliasing).
// However, we constrain T to be either a value type or a immutable ref type (e.g., string)
// to avoid this problem.
TrackedCollection<T>.ValueEl el = new TrackedCollection<T>.ValueEl();
el.isInserted = false;
el.originalValue = new Pair<T, T>(value, value);
_inner.combinedValues.Add(el);
}
}
internal List<T> Inserted
{
get
{
return _inner.Inserted;
}
}
internal List<T> Removed
{
get
{
return _inner.Removed;
}
}
internal List<Pair<T, T>> ChangedValues
{
get
{
return _inner.ChangedValues;
}
}
internal bool Changed
{
get
{
return _inner.Changed;
}
}
// Resets the change-tracking of the collection to 'unchanged', by clearing out the removedValues,
// changing inserted values into original values, and for all Pairs<T,T> in originalValues for which
// the left-side does not equal the right-side, copying the right-side over the left-side
internal void ResetTracking()
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalValueCollection", "Entering ResetTracking");
_inner.removedValues.Clear();
foreach (TrackedCollection<T>.ValueEl el in _inner.combinedValues)
{
if (el.isInserted)
{
GlobalDebug.WriteLineIf(
GlobalDebug.Info,
"PrincipalValueCollection",
"ResetTracking: moving {0} (type {1}) from inserted to original",
el.insertedValue,
el.insertedValue.GetType());
el.isInserted = false;
el.originalValue = new Pair<T, T>(el.insertedValue, el.insertedValue);
//el.insertedValue = T.default;
}
else
{
Pair<T, T> pair = el.originalValue;
if (!pair.Left.Equals(pair.Right))
{
GlobalDebug.WriteLineIf(
GlobalDebug.Info,
"PrincipalValueCollection",
"ResetTracking: found changed original, left={0}, right={1}, type={2}",
pair.Left,
pair.Right,
pair.Left.GetType());
pair.Left = pair.Right;
}
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using SteamKit2;
using SteamTrade.Exceptions;
using Newtonsoft.Json.Linq;
using SteamTrade.TradeWebAPI;
namespace SteamTrade
{
public partial class Trade
{
#region Static Public data
public static Schema CurrentSchema = null;
#endregion
// list to store all trade events already processed
List<TradeEvent> eventList;
// current bot's sid
SteamID mySteamId;
// If the bot is ready.
bool meIsReady = false;
// If the other user is ready.
bool otherIsReady = false;
// Whether or not the trade actually started.
bool tradeStarted = false;
Dictionary<int, ulong> myOfferedItems;
List<ulong> steamMyOfferedItems;
// Internal properties needed for Steam API.
int numEvents;
private readonly TradeSession session;
internal Trade(SteamID me, SteamID other, string sessionId, string token, Inventory myInventory, Inventory otherInventory)
{
mySteamId = me;
OtherSID = other;
List<uint> InvType = new List<uint>();
session = new TradeSession(sessionId, token, other);
this.eventList = new List<TradeEvent>();
OtherOfferedItems = new List<ulong>();
myOfferedItems = new Dictionary<int, ulong>();
steamMyOfferedItems = new List<ulong>();
OtherInventory = otherInventory;
MyInventory = myInventory;
}
#region Public Properties
/// <summary>Gets the other user's steam ID.</summary>
public SteamID OtherSID { get; private set; }
/// <summary>
/// Gets the bot's Steam ID.
/// </summary>
public SteamID MySteamId
{
get { return mySteamId; }
}
/// <summary>
/// Gets the inventory of the other user.
/// </summary>
public Inventory OtherInventory { get; private set; }
/// <summary>
/// Gets the private inventory of the other user.
/// </summary>
public ForeignInventory OtherPrivateInventory { get; private set; }
/// <summary>
/// Gets the inventory of the bot.
/// </summary>
public Inventory MyInventory { get; private set; }
/// <summary>
/// Gets the items the user has offered, by itemid.
/// </summary>
/// <value>
/// The other offered items.
/// </value>
public List<ulong> OtherOfferedItems { get; private set; }
/// <summary>
/// Gets a value indicating if the other user is ready to trade.
/// </summary>
public bool OtherIsReady
{
get { return otherIsReady; }
}
/// <summary>
/// Gets a value indicating if the bot is ready to trade.
/// </summary>
public bool MeIsReady
{
get { return meIsReady; }
}
/// <summary>
/// Gets a value indicating if a trade has started.
/// </summary>
public bool TradeStarted
{
get { return tradeStarted; }
}
/// <summary>
/// Gets a value indicating if the remote trading partner cancelled the trade.
/// </summary>
public bool OtherUserCancelled { get; private set; }
/// <summary>
/// Gets a value indicating whether the trade completed normally. This
/// is independent of other flags.
/// </summary>
public bool HasTradeCompletedOk { get; private set; }
#endregion
#region Public Events
public delegate void CloseHandler ();
public delegate void ErrorHandler (string error);
public delegate void TimeoutHandler ();
public delegate void SuccessfulInit ();
public delegate void UserAddItemHandler (Schema.Item schemaItem,Inventory.Item inventoryItem);
public delegate void UserRemoveItemHandler (Schema.Item schemaItem,Inventory.Item inventoryItem);
public delegate void MessageHandler (string msg);
public delegate void UserSetReadyStateHandler (bool ready);
public delegate void UserAcceptHandler ();
/// <summary>
/// When the trade closes, this is called. It doesn't matter
/// whether or not it was a timeout or an error, this is called
/// to close the trade.
/// </summary>
public event CloseHandler OnClose;
/// <summary>
/// This is for handling errors that may occur, like inventories
/// not loading.
/// </summary>
public event ErrorHandler OnError;
/// <summary>
/// This occurs after Inventories have been loaded.
/// </summary>
public event SuccessfulInit OnAfterInit;
/// <summary>
/// This occurs when the other user adds an item to the trade.
/// </summary>
public event UserAddItemHandler OnUserAddItem;
/// <summary>
/// This occurs when the other user removes an item from the
/// trade.
/// </summary>
public event UserAddItemHandler OnUserRemoveItem;
/// <summary>
/// This occurs when the user sends a message to the bot over
/// trade.
/// </summary>
public event MessageHandler OnMessage;
/// <summary>
/// This occurs when the user sets their ready state to either
/// true or false.
/// </summary>
public event UserSetReadyStateHandler OnUserSetReady;
/// <summary>
/// This occurs when the user accepts the trade.
/// </summary>
public event UserAcceptHandler OnUserAccept;
#endregion
/// <summary>
/// Cancel the trade. This calls the OnClose handler, as well.
/// </summary>
public bool CancelTrade ()
{
bool ok = session.CancelTradeWebCmd ();
if (!ok)
throw new TradeException ("The Web command to cancel the trade failed");
if (OnClose != null)
OnClose ();
return true;
}
/// <summary>
/// Adds a specified item by its itemid.
/// </summary>
/// <returns><c>false</c> if the item was not found in the inventory.</returns>
public bool AddItem (ulong itemid)//TF2 Default
{
if (MyInventory.GetItem(itemid) == null)
{
return false;
}
else
{
return AddItem(new TradeUserAssets(){assetid=itemid,appid=440,contextid=2});
}
}
public bool AddItem(ulong itemid, int appid, int contextid)
{
return AddItem(new TradeUserAssets(){assetid=itemid,appid=appid,contextid=contextid});
}
public bool AddItem(TradeUserAssets item)
{
var slot = NextTradeSlot();
bool ok = session.AddItemWebCmd(item.assetid, slot, item.appid, item.contextid);
if (!ok)
throw new TradeException("The Web command to add the Item failed");
myOfferedItems[slot] = item.assetid;
return true;
}
/// <summary>
/// Adds a single item by its Defindex.
/// </summary>
/// <returns>
/// <c>true</c> if an item was found with the corresponding
/// defindex, <c>false</c> otherwise.
/// </returns>
public bool AddItemByDefindex (int defindex)
{
List<Inventory.Item> items = MyInventory.GetItemsByDefindex (defindex);
foreach (Inventory.Item item in items)
{
if (item != null && !myOfferedItems.ContainsValue(item.Id) && !item.IsNotTradeable)
{
return AddItem (item.Id);
}
}
return false;
}
/// <summary>
/// Adds an entire set of items by Defindex to each successive
/// slot in the trade.
/// </summary>
/// <param name="defindex">The defindex. (ex. 5022 = crates)</param>
/// <param name="numToAdd">The upper limit on amount of items to add. <c>0</c> to add all items.</param>
/// <returns>Number of items added.</returns>
public uint AddAllItemsByDefindex (int defindex, uint numToAdd = 0)
{
List<Inventory.Item> items = MyInventory.GetItemsByDefindex (defindex);
uint added = 0;
foreach (Inventory.Item item in items)
{
if (item != null && !myOfferedItems.ContainsValue(item.Id) && !item.IsNotTradeable)
{
bool success = AddItem (item.Id);
if (success)
added++;
if (numToAdd > 0 && added >= numToAdd)
return added;
}
}
return added;
}
/// <summary>
/// Removes an item by its itemid.
/// </summary>
/// <returns><c>false</c> the item was not found in the trade.</returns>
public bool RemoveItem(ulong itemid)
{
return RemoveItem(itemid,440,2);
}
public bool RemoveItem(TradeUserAssets item)
{
return RemoveItem(item.assetid, item.appid, item.contextid);
}
public bool RemoveItem (ulong itemid,int appid,int contextid)
{
int? slot = GetItemSlot (itemid);
if (!slot.HasValue)
return false;
bool ok = session.RemoveItemWebCmd(itemid, slot.Value,appid,contextid);
if (!ok)
throw new TradeException ("The web command to remove the item failed.");
myOfferedItems.Remove (slot.Value);
return true;
}
/// <summary>
/// Removes an item with the given Defindex from the trade.
/// </summary>
/// <returns>
/// Returns <c>true</c> if it found a corresponding item; <c>false</c> otherwise.
/// </returns>
public bool RemoveItemByDefindex (int defindex)
{
foreach (ulong id in myOfferedItems.Values)
{
Inventory.Item item = MyInventory.GetItem (id);
if (item.Defindex == defindex)
{
return RemoveItem (item.Id);
}
}
return false;
}
/// <summary>
/// Removes an entire set of items by Defindex.
/// </summary>
/// <param name="defindex">The defindex. (ex. 5022 = crates)</param>
/// <param name="numToRemove">The upper limit on amount of items to remove. <c>0</c> to remove all items.</param>
/// <returns>Number of items removed.</returns>
public uint RemoveAllItemsByDefindex (int defindex, uint numToRemove = 0)
{
List<Inventory.Item> items = MyInventory.GetItemsByDefindex (defindex);
uint removed = 0;
foreach (Inventory.Item item in items)
{
if (item != null && myOfferedItems.ContainsValue (item.Id))
{
bool success = RemoveItem (item.Id);
if (success)
removed++;
if (numToRemove > 0 && removed >= numToRemove)
return removed;
}
}
return removed;
}
/// <summary>
/// Removes all offered items from the trade.
/// </summary>
/// <returns>Number of items removed.</returns>
public uint RemoveAllItems()
{
uint removed = 0;
var copy = new Dictionary<int, ulong>(myOfferedItems);
foreach (var id in copy)
{
Inventory.Item item = MyInventory.GetItem(id.Value);
bool success = RemoveItem(item.Id);
if (success)
removed++;
}
return removed;
}
/// <summary>
/// Sends a message to the user over the trade chat.
/// </summary>
public bool SendMessage (string msg)
{
bool ok = session.SendMessageWebCmd(msg);
if (!ok)
throw new TradeException ("The web command to send the trade message failed.");
return true;
}
/// <summary>
/// Sets the bot to a ready status.
/// </summary>
public bool SetReady (bool ready)
{
// testing
ValidateLocalTradeItems ();
bool ok = session.SetReadyWebCmd(ready);
if (!ok)
throw new TradeException ("The web command to set trade ready state failed.");
return true;
}
/// <summary>
/// Accepts the trade from the user. Returns a deserialized
/// JSON object.
/// </summary>
public bool AcceptTrade ()
{
ValidateLocalTradeItems ();
bool ok = session.AcceptTradeWebCmd();
if (!ok)
throw new TradeException ("The web command to accept the trade failed.");
return true;
}
/// <summary>
/// This updates the trade. This is called at an interval of a
/// default of 800ms, not including the execution time of the
/// method itself.
/// </summary>
/// <returns><c>true</c> if the other trade partner performed an action; otherwise <c>false</c>.</returns>
public bool Poll ()
{
bool otherDidSomething = false;
if (!TradeStarted)
{
tradeStarted = true;
// since there is no feedback to let us know that the trade
// is fully initialized we assume that it is when we start polling.
if (OnAfterInit != null)
OnAfterInit ();
}
TradeStatus status = session.GetStatus();
if (status == null)
throw new TradeException ("The web command to get the trade status failed.");
switch (status.trade_status)
{
// Nothing happened. i.e. trade hasn't closed yet.
case 0:
break;
// Successful trade
case 1:
HasTradeCompletedOk = true;
return otherDidSomething;
// All other known values (3, 4) correspond to trades closing.
default:
if (OnError != null)
{
OnError("Trade was closed by other user. Trade status: " + status.trade_status);
}
OtherUserCancelled = true;
return otherDidSomething;
}
if (status.newversion)
{
// handle item adding and removing
session.Version = status.version;
TradeEvent trdEvent = status.GetLastEvent();
TradeEventType actionType = (TradeEventType) trdEvent.action;
HandleTradeVersionChange(status);
return true;
}
else if (status.version > session.Version)
{
// oh crap! we missed a version update abort so we don't get
// scammed. if we could get what steam thinks what's in the
// trade then this wouldn't be an issue. but we can only get
// that when we see newversion == true
throw new TradeException("The trade version does not match. Aborting.");
}
var events = status.GetAllEvents();
foreach (var tradeEvent in events)
{
if (eventList.Contains(tradeEvent))
continue;
//add event to processed list, as we are taking care of this event now
eventList.Add(tradeEvent);
bool isBot = tradeEvent.steamid == MySteamId.ConvertToUInt64().ToString();
// dont process if this is something the bot did
if (isBot)
continue;
otherDidSomething = true;
/* Trade Action ID's
* 0 = Add item (itemid = "assetid")
* 1 = remove item (itemid = "assetid")
* 2 = Toggle ready
* 3 = Toggle not ready
* 4 = ?
* 5 = ? - maybe some sort of cancel
* 6 = ?
* 7 = Chat (message = "text") */
switch ((TradeEventType) tradeEvent.action)
{
case TradeEventType.ItemAdded:
FireOnUserAddItem(tradeEvent);
break;
case TradeEventType.ItemRemoved:
FireOnUserRemoveItem(tradeEvent);
break;
case TradeEventType.UserSetReady:
otherIsReady = true;
OnUserSetReady(true);
break;
case TradeEventType.UserSetUnReady:
otherIsReady = false;
OnUserSetReady(false);
break;
case TradeEventType.UserAccept:
OnUserAccept();
break;
case TradeEventType.UserChat:
OnMessage(tradeEvent.text);
break;
default:
// Todo: add an OnWarning or similar event
if (OnError != null)
OnError("Unknown Event ID: " + tradeEvent.action);
break;
}
}
// Update Local Variables
if (status.them != null)
{
otherIsReady = status.them.ready == 1;
meIsReady = status.me.ready == 1;
}
if (status.logpos != 0)
{
session.LogPos = status.logpos;
}
return otherDidSomething;
}
void HandleTradeVersionChange(TradeStatus status)
{
CopyNewAssets(OtherOfferedItems, status.them.GetAssets());
CopyNewAssets(steamMyOfferedItems, status.me.GetAssets());
}
private void CopyNewAssets(List<ulong> dest, TradeUserAssets[] assetList)
{
if (assetList == null)
return;
//Console.WriteLine("clearing dest");
dest.Clear();
foreach (var asset in assetList)
{
dest.Add(asset.assetid);
//Console.WriteLine(asset.assetid);
}
}
/// <summary>
/// Gets an item from a TradeEvent, and passes it into the UserHandler's implemented OnUserAddItem([...]) routine.
/// Passes in null items if something went wrong.
/// </summary>
/// <param name="tradeEvent">TradeEvent to get item from</param>
/// <returns></returns>
private void FireOnUserAddItem(TradeEvent tradeEvent)
{
ulong itemID = tradeEvent.assetid;
Inventory.Item item;
if (OtherInventory != null)
{
item = OtherInventory.GetItem(itemID);
if (item != null)
{
Schema.Item schemaItem = CurrentSchema.GetItem(item.Defindex);
if (schemaItem == null)
{
Console.WriteLine("User added an unknown item to the trade.");
}
OnUserAddItem(schemaItem, item);
}
else
{
item = new Inventory.Item()
{
Id=itemID,
AppId=tradeEvent.appid,
ContextId=tradeEvent.contextid
};
//Console.WriteLine("User added a non TF2 item to the trade.");
OnUserAddItem(null, item);
}
}
else
{
var schemaItem = GetItemFromPrivateBp(tradeEvent, itemID);
if (schemaItem == null)
{
Console.WriteLine("User added an unknown item to the trade.");
}
OnUserAddItem(schemaItem, null);
// todo: figure out what to send in with Inventory item.....
}
}
private Schema.Item GetItemFromPrivateBp(TradeEvent tradeEvent, ulong itemID)
{
if (OtherPrivateInventory == null)
{
// get the foreign inventory
var f = session.GetForiegnInventory(OtherSID, tradeEvent.contextid,tradeEvent.contextid);
OtherPrivateInventory = new ForeignInventory(f);
}
ushort defindex = OtherPrivateInventory.GetDefIndex(itemID);
Schema.Item schemaItem = CurrentSchema.GetItem(defindex);
return schemaItem;
}
/// <summary>
/// Gets an item from a TradeEvent, and passes it into the UserHandler's implemented OnUserRemoveItem([...]) routine.
/// Passes in null items if something went wrong.
/// </summary>
/// <param name="tradeEvent">TradeEvent to get item from</param>
/// <returns></returns>
private void FireOnUserRemoveItem(TradeEvent tradeEvent)
{
ulong itemID = (ulong) tradeEvent.assetid;
Inventory.Item item;
if (OtherInventory != null)
{
item = OtherInventory.GetItem(itemID);
if (item != null)
{
Schema.Item schemaItem = CurrentSchema.GetItem(item.Defindex);
if (schemaItem == null)
{
// TODO: Add log (counldn't find item in CurrentSchema)
}
OnUserRemoveItem(schemaItem, item);
}
else
{
// TODO: Log this (Couldn't find item in user's inventory can't find item in CurrentSchema
item = new Inventory.Item()
{
Id = itemID,
AppId = tradeEvent.appid,
ContextId = tradeEvent.contextid
};
OnUserRemoveItem(null, item);
}
}
else
{
var schemaItem = GetItemFromPrivateBp(tradeEvent, itemID);
if (schemaItem == null)
{
// TODO: Add log (counldn't find item in CurrentSchema)
}
OnUserRemoveItem(schemaItem, null);
}
}
internal void FireOnCloseEvent()
{
var onCloseEvent = OnClose;
if (onCloseEvent != null)
onCloseEvent();
}
int NextTradeSlot ()
{
int slot = 0;
while (myOfferedItems.ContainsKey (slot))
{
slot++;
}
return slot;
}
int? GetItemSlot (ulong itemid)
{
foreach (int slot in myOfferedItems.Keys)
{
if (myOfferedItems [slot] == itemid)
{
return slot;
}
}
return null;
}
void ValidateSteamItemChanged (ulong itemid, bool wasAdded)
{
// checks to make sure that the Trade polling saw
// the correct change for the given item.
// check if the correct item was added
if (wasAdded && !myOfferedItems.ContainsValue (itemid))
throw new TradeException ("Steam Trade had an invalid item added: " + itemid);
// check if the correct item was removed
if (!wasAdded && myOfferedItems.ContainsValue (itemid))
throw new TradeException ("Steam Trade had an invalid item removed: " + itemid);
}
void ValidateLocalTradeItems ()
{
if (myOfferedItems.Count != steamMyOfferedItems.Count)
{
throw new TradeException ("Error validating local copy of items in the trade: Count mismatch");
}
foreach (ulong id in myOfferedItems.Values)
{
if (!steamMyOfferedItems.Contains (id))
throw new TradeException ("Error validating local copy of items in the trade: Item was not in the Steam Copy.");
}
}
}
}
| |
#if WITH_PATRICIA
using System;
using System.Collections;
using System.Collections.Generic;
using Volante;
namespace Volante.Impl
{
class PTrie<T> : PersistentCollection<T>, IPatriciaTrie<T> where T : class, IPersistent
{
private PTrieNode rootZero;
private PTrieNode rootOne;
private int count;
public override IEnumerator<T> GetEnumerator()
{
List<T> list = new List<T>();
fill(list, rootZero);
fill(list, rootOne);
return list.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
private static void fill(List<T> list, PTrieNode node)
{
if (null == node)
return;
list.Add(node.obj);
fill(list, node.childZero);
fill(list, node.childOne);
}
public override int Count
{
get
{
return count;
}
}
private static int firstDigit(ulong key, int keyLength)
{
return (int)(key >> (keyLength - 1)) & 1;
}
private static int getCommonPart(ulong keyA, int keyLengthA, ulong keyB, int keyLengthB)
{
// truncate the keys so they are the same size (discard low bits)
if (keyLengthA > keyLengthB)
{
keyA >>= keyLengthA - keyLengthB;
keyLengthA = keyLengthB;
}
else
{
keyB >>= keyLengthB - keyLengthA;
keyLengthB = keyLengthA;
}
// now get common part
ulong diff = keyA ^ keyB;
// finally produce common key part
int count = 0;
while (diff != 0)
{
diff >>= 1;
count += 1;
}
return keyLengthA - count;
}
public T Add(PatriciaTrieKey key, T obj)
{
Modify();
count += 1;
if (firstDigit(key.mask, key.length) == 1)
{
if (rootOne != null)
{
return rootOne.add(key.mask, key.length, obj);
}
else
{
rootOne = new PTrieNode(key.mask, key.length, obj);
return null;
}
}
else
{
if (rootZero != null)
{
return rootZero.add(key.mask, key.length, obj);
}
else
{
rootZero = new PTrieNode(key.mask, key.length, obj);
return null;
}
}
}
public T FindBestMatch(PatriciaTrieKey key)
{
if (firstDigit(key.mask, key.length) == 1)
{
if (rootOne != null)
{
return rootOne.findBestMatch(key.mask, key.length);
}
}
else
{
if (rootZero != null)
{
return rootZero.findBestMatch(key.mask, key.length);
}
}
return null;
}
public T FindExactMatch(PatriciaTrieKey key)
{
if (firstDigit(key.mask, key.length) == 1)
{
if (rootOne != null)
return rootOne.findExactMatch(key.mask, key.length);
}
else
{
if (rootZero != null)
return rootZero.findExactMatch(key.mask, key.length);
}
return null;
}
public T Remove(PatriciaTrieKey key)
{
T obj;
if (firstDigit(key.mask, key.length) == 1)
{
if (rootOne != null)
{
obj = rootOne.remove(key.mask, key.length);
if (obj != null)
{
Modify();
count -= 1;
if (rootOne.isNotUsed())
{
rootOne.Deallocate();
rootOne = null;
}
return obj;
}
}
}
else
{
if (rootZero != null)
{
obj = rootZero.remove(key.mask, key.length);
if (obj != null)
{
Modify();
count -= 1;
if (rootZero.isNotUsed())
{
rootZero.Deallocate();
rootZero = null;
}
return obj;
}
}
}
return null;
}
public override void Clear()
{
if (rootOne != null)
{
rootOne.Deallocate();
rootOne = null;
}
if (rootZero != null)
{
rootZero.Deallocate();
rootZero = null;
}
count = 0;
}
class PTrieNode : Persistent
{
internal ulong key;
internal int keyLength;
internal T obj;
internal PTrieNode childZero;
internal PTrieNode childOne;
internal PTrieNode(ulong key, int keyLength, T obj)
{
this.obj = obj;
this.key = key;
this.keyLength = keyLength;
}
PTrieNode() { }
internal T add(ulong key, int keyLength, T obj)
{
T prevObj;
if (key == this.key && keyLength == this.keyLength)
{
Modify();
// the new is matched exactly by this node's key, so just replace the node object
prevObj = this.obj;
this.obj = obj;
return prevObj;
}
int keyLengthCommon = getCommonPart(key, keyLength, this.key, this.keyLength);
int keyLengthDiff = this.keyLength - keyLengthCommon;
ulong keyCommon = key >> (keyLength - keyLengthCommon);
ulong keyDiff = this.key - (keyCommon << keyLengthDiff);
// process diff with this node's key, if any
if (keyLengthDiff > 0)
{
Modify();
// create a new node with the diff
PTrieNode newNode = new PTrieNode(keyDiff, keyLengthDiff, this.obj);
// transfer infos of this node to the new node
newNode.childZero = childZero;
newNode.childOne = childOne;
// update this node to hold common part
this.key = keyCommon;
this.keyLength = keyLengthCommon;
this.obj = null;
// and set the new node as child of this node
if (firstDigit(keyDiff, keyLengthDiff) == 1)
{
childZero = null;
childOne = newNode;
}
else
{
childZero = newNode;
childOne = null;
}
}
// process diff with the new key, if any
if (keyLength > keyLengthCommon)
{
// get diff with the new key
keyLengthDiff = keyLength - keyLengthCommon;
keyDiff = key - (keyCommon << keyLengthDiff);
// get which child we use as insertion point and do insertion (recursive)
if (firstDigit(keyDiff, keyLengthDiff) == 1)
{
if (childOne != null)
{
return childOne.add(keyDiff, keyLengthDiff, obj);
}
else
{
Modify();
childOne = new PTrieNode(keyDiff, keyLengthDiff, obj);
return null;
}
}
else
{
if (childZero != null)
{
return childZero.add(keyDiff, keyLengthDiff, obj);
}
else
{
Modify();
childZero = new PTrieNode(keyDiff, keyLengthDiff, obj);
return null;
}
}
}
else
{ // the new key was containing within this node's original key, so just set this node as terminator
prevObj = this.obj;
this.obj = obj;
return prevObj;
}
}
internal T findBestMatch(ulong key, int keyLength)
{
if (keyLength > this.keyLength)
{
int keyLengthCommon = getCommonPart(key, keyLength, this.key, this.keyLength);
int keyLengthDiff = keyLength - keyLengthCommon;
ulong keyCommon = key >> keyLengthDiff;
ulong keyDiff = key - (keyCommon << keyLengthDiff);
if (firstDigit(keyDiff, keyLengthDiff) == 1)
{
if (childOne != null)
return childOne.findBestMatch(keyDiff, keyLengthDiff);
}
else
{
if (childZero != null)
return childZero.findBestMatch(keyDiff, keyLengthDiff);
}
}
return obj;
}
internal T findExactMatch(ulong key, int keyLength)
{
if (keyLength >= this.keyLength)
{
if (key == this.key && keyLength == this.keyLength)
{
return obj;
}
else
{
int keyLengthCommon = getCommonPart(key, keyLength, this.key, this.keyLength);
int keyLengthDiff = keyLength - keyLengthCommon;
ulong keyCommon = key >> keyLengthDiff;
ulong keyDiff = key - (keyCommon << keyLengthDiff);
if (firstDigit(keyDiff, keyLengthDiff) == 1)
{
if (childOne != null)
return childOne.findBestMatch(keyDiff, keyLengthDiff);
}
else
{
if (childZero != null)
return childZero.findBestMatch(keyDiff, keyLengthDiff);
}
}
}
return null;
}
internal bool isNotUsed()
{
return obj == null && childOne == null && childZero == null;
}
internal T remove(ulong key, int keyLength)
{
T obj;
if (keyLength < this.keyLength)
return null;
if (key == this.key && keyLength == this.keyLength)
{
obj = this.obj;
this.obj = null;
return obj;
}
int keyLengthCommon = getCommonPart(key, keyLength, this.key, this.keyLength);
int keyLengthDiff = keyLength - keyLengthCommon;
ulong keyCommon = key >> keyLengthDiff;
ulong keyDiff = key - (keyCommon << keyLengthDiff);
if (firstDigit(keyDiff, keyLengthDiff) == 1)
{
if (childOne == null)
return null;
obj = childOne.findBestMatch(keyDiff, keyLengthDiff);
if (obj == null)
return null;
if (childOne.isNotUsed())
{
Modify();
childOne.Deallocate();
childOne = null;
}
return obj;
}
if (childZero == null)
return null;
obj = childZero.findBestMatch(keyDiff, keyLengthDiff);
if (obj == null)
return null;
if (childZero.isNotUsed())
{
Modify();
childZero.Deallocate();
childZero = null;
}
return obj;
}
public override void Deallocate()
{
if (childOne != null)
childOne.Deallocate();
if (childZero != null)
childZero.Deallocate();
base.Deallocate();
}
}
}
}
#endif
| |
using System;
using System.Collections.Generic;
// ReSharper disable once CheckNamespace
namespace GameDevWare.Serialization.MessagePack
{
public sealed class DefaultMessagePackExtensionTypeHandler : MessagePackExtensionTypeHandler
{
public const int EXTENSION_TYPE_TIMESTAMP = -1;
public const int EXTENSION_TYPE_DATE_TIME = 40;
public const int EXTENSION_TYPE_DATE_TIME_OFFSET = 41;
public const int EXTENSION_TYPE_DECIMAL = 42;
public const int EXTENSION_TYPE_GUID = 43;
public const int GUID_SIZE = 16;
public const int DECIMAL_SIZE = 16;
public const int DATE_TIME_SIZE = 16;
public const int DATE_TIME_OFFSET_SIZE = 16;
private static readonly Type[] DefaultExtensionTypes = new[] { typeof(decimal), typeof(DateTime), typeof(DateTimeOffset), typeof(Guid), typeof(DateTimeOffset), typeof(MessagePackTimestamp) };
public static DefaultMessagePackExtensionTypeHandler Instance = new DefaultMessagePackExtensionTypeHandler(EndianBitConverter.Little);
private readonly EndianBitConverter bitConverter;
public override IEnumerable<Type> ExtensionTypes
{
get { return DefaultExtensionTypes; }
}
internal DefaultMessagePackExtensionTypeHandler(EndianBitConverter bitConverter)
{
if (bitConverter == null) throw new ArgumentNullException("bitConverter");
this.bitConverter = bitConverter;
}
/// <inheritdoc />
public override bool TryRead(sbyte type, ArraySegment<byte> data, out object value)
{
if (data.Array == null) throw new ArgumentNullException("data");
value = default(object);
switch (type)
{
case EXTENSION_TYPE_TIMESTAMP:
unchecked
{
var seconds = 0L;
var nanoSeconds = 0u;
switch (data.Count)
{
case 4:
seconds = this.bitConverter.ToInt32(data.Array, data.Offset);
value = new MessagePackTimestamp(seconds, nanoSeconds);
return true;
case 8:
var data64 = this.bitConverter.ToUInt64(data.Array, data.Offset);
seconds = (int)(data64 & 0x00000003ffffffffL);
nanoSeconds = (uint)(data64 >> 34 & uint.MaxValue);
value = new MessagePackTimestamp(seconds, nanoSeconds);
return true;
case 12:
nanoSeconds = this.bitConverter.ToUInt32(data.Array, data.Offset);
seconds = this.bitConverter.ToInt64(data.Array, data.Offset + 4);
value = new MessagePackTimestamp(seconds, nanoSeconds);
return true;
default:
return false;
}
}
case EXTENSION_TYPE_DATE_TIME:
if (data.Count != DATE_TIME_SIZE)
return false;
var dateTime = new DateTime(this.bitConverter.ToInt64(data.Array, data.Offset + 1), (DateTimeKind)data.Array[data.Offset]);
value = dateTime;
return true;
case EXTENSION_TYPE_DATE_TIME_OFFSET:
if (data.Count != DATE_TIME_OFFSET_SIZE)
return false;
var offset = new TimeSpan(this.bitConverter.ToInt64(data.Array, data.Offset + 8));
var ticks = this.bitConverter.ToInt64(data.Array, data.Offset);
var dateTimeOffset = new DateTimeOffset(ticks, offset);
value = dateTimeOffset;
return true;
case EXTENSION_TYPE_DECIMAL:
if (data.Count != DECIMAL_SIZE)
return false;
var decimalValue = this.bitConverter.ToDecimal(data.Array, data.Offset);
value = decimalValue;
return true;
case EXTENSION_TYPE_GUID:
if (data.Count != GUID_SIZE)
return false;
var buffer = data.Array;
unchecked
{
var guidValue = new Guid
(
(uint)(buffer[data.Offset + 3] << 24 | buffer[data.Offset + 2] << 16 | buffer[data.Offset + 1] << 8 | buffer[data.Offset + 0]),
(ushort)(buffer[data.Offset + 5] << 8 | buffer[data.Offset + 4]),
(ushort)(buffer[data.Offset + 7] << 8 | buffer[data.Offset + 6]),
buffer[data.Offset + 8],
buffer[data.Offset + 9],
buffer[data.Offset + 10],
buffer[data.Offset + 11],
buffer[data.Offset + 12],
buffer[data.Offset + 13],
buffer[data.Offset + 14],
buffer[data.Offset + 15]
);
value = guidValue;
return true;
}
default:
return false;
}
}
/// <inheritdoc />
public override bool TryWrite(object value, out sbyte type, ref ArraySegment<byte> data)
{
if (value == null)
{
type = 0;
return false;
}
else if (value is DateTime)
{
type = EXTENSION_TYPE_DATE_TIME;
if (data.Array == null || data.Count < DATE_TIME_SIZE)
data = new ArraySegment<byte>(new byte[DATE_TIME_SIZE]);
var dateTime = (DateTime)(object)value;
Array.Clear(data.Array, data.Offset, DATE_TIME_SIZE);
this.bitConverter.CopyBytes(dateTime.Ticks, data.Array, data.Offset + 1);
data.Array[data.Offset] = (byte)dateTime.Kind;
if (data.Count != DATE_TIME_SIZE)
data = new ArraySegment<byte>(data.Array, data.Offset, DATE_TIME_SIZE);
return true;
}
else if (value is DateTimeOffset)
{
type = EXTENSION_TYPE_DATE_TIME_OFFSET;
if (data.Array == null || data.Count < DATE_TIME_OFFSET_SIZE)
data = new ArraySegment<byte>(new byte[DATE_TIME_OFFSET_SIZE]);
var dateTimeOffset = (DateTimeOffset)(object)value;
this.bitConverter.CopyBytes(dateTimeOffset.DateTime.Ticks, data.Array, data.Offset);
this.bitConverter.CopyBytes(dateTimeOffset.Offset.Ticks, data.Array, data.Offset + 8);
if (data.Count != DATE_TIME_OFFSET_SIZE)
data = new ArraySegment<byte>(data.Array, data.Offset, DATE_TIME_OFFSET_SIZE);
return true;
}
else if (value is decimal)
{
type = EXTENSION_TYPE_DECIMAL;
if (data.Array == null || data.Count < DECIMAL_SIZE)
data = new ArraySegment<byte>(new byte[DECIMAL_SIZE]);
var number = (decimal)(object)value;
this.bitConverter.CopyBytes(number, data.Array, data.Offset);
if (data.Count != DECIMAL_SIZE)
data = new ArraySegment<byte>(data.Array, data.Offset, DECIMAL_SIZE);
return true;
}
else if (value is Guid)
{
type = EXTENSION_TYPE_GUID;
var guid = (Guid)(object)value;
data = new ArraySegment<byte>(guid.ToByteArray());
return true;
}
else if (value is MessagePackTimestamp)
{
type = EXTENSION_TYPE_TIMESTAMP;
var timestamp = (MessagePackTimestamp)(object)value;
unchecked
{
if (timestamp.Seconds <= int.MaxValue && timestamp.Seconds >= int.MinValue)
{
if (timestamp.NanoSeconds == 0)
{
const int TIMESTAMP_SIZE = 4;
if (data.Array == null || data.Count < TIMESTAMP_SIZE)
data = new ArraySegment<byte>(new byte[TIMESTAMP_SIZE]);
// timestamp 32
this.bitConverter.CopyBytes((int)timestamp.Seconds, data.Array, data.Offset);
if (data.Count != TIMESTAMP_SIZE)
data = new ArraySegment<byte>(data.Array, data.Offset, TIMESTAMP_SIZE);
}
else
{
const int TIMESTAMP_SIZE = 8;
if (data.Array == null || data.Count < TIMESTAMP_SIZE)
data = new ArraySegment<byte>(new byte[TIMESTAMP_SIZE]);
var data64 = ((ulong)timestamp.NanoSeconds << 34) | ((ulong)timestamp.Seconds & uint.MaxValue);
// timestamp 64
this.bitConverter.CopyBytes(data64, data.Array, data.Offset);
if (data.Count != TIMESTAMP_SIZE)
data = new ArraySegment<byte>(data.Array, data.Offset, TIMESTAMP_SIZE);
}
}
else
{
const int TIMESTAMP_SIZE = 12;
if (data.Array == null || data.Count < TIMESTAMP_SIZE)
data = new ArraySegment<byte>(new byte[TIMESTAMP_SIZE]);
// timestamp 96
this.bitConverter.CopyBytes(timestamp.NanoSeconds, data.Array, data.Offset);
this.bitConverter.CopyBytes(timestamp.Seconds, data.Array, data.Offset + 4);
if (data.Count != TIMESTAMP_SIZE)
data = new ArraySegment<byte>(data.Array, data.Offset, TIMESTAMP_SIZE);
}
}
return true;
}
else
{
type = default(sbyte);
return false;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Data.Common;
using System.Data.ProviderBase;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics.CodeAnalysis;
using System.Transactions;
using Microsoft.SqlServer.Server;
using System.Reflection;
using System.IO;
using System.Globalization;
using System.Security;
namespace System.Data.SqlClient
{
public sealed partial class SqlConnection : DbConnection, ICloneable
{
private bool _AsyncCommandInProgress;
// SQLStatistics support
internal SqlStatistics _statistics;
private bool _collectstats;
private bool _fireInfoMessageEventOnUserErrors; // False by default
// root task associated with current async invocation
private Tuple<TaskCompletionSource<DbConnectionInternal>, Task> _currentCompletion;
private SqlCredential _credential;
private string _connectionString;
private int _connectRetryCount;
private string _accessToken; // Access Token to be used for token based authententication
// connection resiliency
private object _reconnectLock = new object();
internal Task _currentReconnectionTask;
private Task _asyncWaitingForReconnection; // current async task waiting for reconnection in non-MARS connections
private Guid _originalConnectionId = Guid.Empty;
private CancellationTokenSource _reconnectionCancellationSource;
internal SessionData _recoverySessionData;
internal bool _suppressStateChangeForReconnection;
private int _reconnectCount;
// diagnostics listener
private static readonly DiagnosticListener s_diagnosticListener = new DiagnosticListener(SqlClientDiagnosticListenerExtensions.DiagnosticListenerName);
// Transient Fault handling flag. This is needed to convey to the downstream mechanism of connection establishment, if Transient Fault handling should be used or not
// The downstream handling of Connection open is the same for idle connection resiliency. Currently we want to apply transient fault handling only to the connections opened
// using SqlConnection.Open() method.
internal bool _applyTransientFaultHandling = false;
public SqlConnection(string connectionString) : this()
{
ConnectionString = connectionString; // setting connection string first so that ConnectionOption is available
CacheConnectionStringProperties();
}
public SqlConnection(string connectionString, SqlCredential credential) : this()
{
ConnectionString = connectionString;
if (credential != null)
{
// The following checks are necessary as setting Credential property will call CheckAndThrowOnInvalidCombinationOfConnectionStringAndSqlCredential
// CheckAndThrowOnInvalidCombinationOfConnectionStringAndSqlCredential it will throw InvalidOperationException rather than Arguemtn exception
// Need to call setter on Credential property rather than setting _credential directly as pool groups need to be checked
SqlConnectionString connectionOptions = (SqlConnectionString)ConnectionOptions;
if (UsesClearUserIdOrPassword(connectionOptions))
{
throw ADP.InvalidMixedArgumentOfSecureAndClearCredential();
}
if (UsesIntegratedSecurity(connectionOptions))
{
throw ADP.InvalidMixedArgumentOfSecureCredentialAndIntegratedSecurity();
}
Credential = credential;
}
// else
// credential == null: we should not set "Credential" as this will do additional validation check and
// checking pool groups which is not necessary. All necessary operation is already done by calling "ConnectionString = connectionString"
CacheConnectionStringProperties();
}
private SqlConnection(SqlConnection connection)
{
GC.SuppressFinalize(this);
CopyFrom(connection);
_connectionString = connection._connectionString;
if (connection._credential != null)
{
SecureString password = connection._credential.Password.Copy();
password.MakeReadOnly();
_credential = new SqlCredential(connection._credential.UserId, password);
}
_accessToken = connection._accessToken;
CacheConnectionStringProperties();
}
// This method will be called once connection string is set or changed.
private void CacheConnectionStringProperties()
{
SqlConnectionString connString = ConnectionOptions as SqlConnectionString;
if (connString != null)
{
_connectRetryCount = connString.ConnectRetryCount;
}
}
//
// PUBLIC PROPERTIES
//
// used to start/stop collection of statistics data and do verify the current state
//
// devnote: start/stop should not performed using a property since it requires execution of code
//
// start statistics
// set the internal flag (_statisticsEnabled) to true.
// Create a new SqlStatistics object if not already there.
// connect the parser to the object.
// if there is no parser at this time we need to connect it after creation.
//
public bool StatisticsEnabled
{
get
{
return (_collectstats);
}
set
{
{
if (value)
{
// start
if (ConnectionState.Open == State)
{
if (null == _statistics)
{
_statistics = new SqlStatistics();
ADP.TimerCurrent(out _statistics._openTimestamp);
}
// set statistics on the parser
// update timestamp;
Debug.Assert(Parser != null, "Where's the parser?");
Parser.Statistics = _statistics;
}
}
else
{
// stop
if (null != _statistics)
{
if (ConnectionState.Open == State)
{
// remove statistics from parser
// update timestamp;
TdsParser parser = Parser;
Debug.Assert(parser != null, "Where's the parser?");
parser.Statistics = null;
ADP.TimerCurrent(out _statistics._closeTimestamp);
}
}
}
_collectstats = value;
}
}
}
internal bool AsyncCommandInProgress
{
get => _AsyncCommandInProgress;
set => _AsyncCommandInProgress = value;
}
// Does this connection use Integrated Security?
private bool UsesIntegratedSecurity(SqlConnectionString opt)
{
return opt != null ? opt.IntegratedSecurity : false;
}
// Does this connection use old style of clear userID or Password in connection string?
private bool UsesClearUserIdOrPassword(SqlConnectionString opt)
{
bool result = false;
if (null != opt)
{
result = (!string.IsNullOrEmpty(opt.UserID) || !string.IsNullOrEmpty(opt.Password));
}
return result;
}
internal SqlConnectionString.TransactionBindingEnum TransactionBinding
{
get => ((SqlConnectionString)ConnectionOptions).TransactionBinding;
}
internal SqlConnectionString.TypeSystem TypeSystem
{
get => ((SqlConnectionString)ConnectionOptions).TypeSystemVersion;
}
internal Version TypeSystemAssemblyVersion
{
get => ((SqlConnectionString)ConnectionOptions).TypeSystemAssemblyVersion;
}
internal int ConnectRetryInterval
{
get => ((SqlConnectionString)ConnectionOptions).ConnectRetryInterval;
}
public override string ConnectionString
{
get
{
return ConnectionString_Get();
}
set
{
if (_credential != null || _accessToken != null)
{
SqlConnectionString connectionOptions = new SqlConnectionString(value);
if (_credential != null)
{
CheckAndThrowOnInvalidCombinationOfConnectionStringAndSqlCredential(connectionOptions);
}
else
{
CheckAndThrowOnInvalidCombinationOfConnectionOptionAndAccessToken(connectionOptions);
}
}
ConnectionString_Set(new SqlConnectionPoolKey(value, _credential, _accessToken));
_connectionString = value; // Change _connectionString value only after value is validated
CacheConnectionStringProperties();
}
}
public override int ConnectionTimeout
{
get
{
SqlConnectionString constr = (SqlConnectionString)ConnectionOptions;
return ((null != constr) ? constr.ConnectTimeout : SqlConnectionString.DEFAULT.Connect_Timeout);
}
}
// AccessToken: To be used for token based authentication
public string AccessToken
{
get
{
string result = _accessToken;
// When a connection is connecting or is ever opened, make AccessToken available only if "Persist Security Info" is set to true
// otherwise, return null
SqlConnectionString connectionOptions = (SqlConnectionString)UserConnectionOptions;
return InnerConnection.ShouldHidePassword && connectionOptions != null && !connectionOptions.PersistSecurityInfo ? null : _accessToken;
}
set
{
// If a connection is connecting or is ever opened, AccessToken cannot be set
if (!InnerConnection.AllowSetConnectionString)
{
throw ADP.OpenConnectionPropertySet("AccessToken", InnerConnection.State);
}
if (value != null)
{
// Check if the usage of AccessToken has any conflict with the keys used in connection string and credential
CheckAndThrowOnInvalidCombinationOfConnectionOptionAndAccessToken((SqlConnectionString)ConnectionOptions);
}
// Need to call ConnectionString_Set to do proper pool group check
ConnectionString_Set(new SqlConnectionPoolKey(_connectionString, credential: _credential, accessToken: value));
_accessToken = value;
}
}
public override string Database
{
// if the connection is open, we need to ask the inner connection what it's
// current catalog is because it may have gotten changed, otherwise we can
// just return what the connection string had.
get
{
SqlInternalConnection innerConnection = (InnerConnection as SqlInternalConnection);
string result;
if (null != innerConnection)
{
result = innerConnection.CurrentDatabase;
}
else
{
SqlConnectionString constr = (SqlConnectionString)ConnectionOptions;
result = ((null != constr) ? constr.InitialCatalog : SqlConnectionString.DEFAULT.Initial_Catalog);
}
return result;
}
}
public override string DataSource
{
get
{
SqlInternalConnection innerConnection = (InnerConnection as SqlInternalConnection);
string result;
if (null != innerConnection)
{
result = innerConnection.CurrentDataSource;
}
else
{
SqlConnectionString constr = (SqlConnectionString)ConnectionOptions;
result = ((null != constr) ? constr.DataSource : SqlConnectionString.DEFAULT.Data_Source);
}
return result;
}
}
public int PacketSize
{
// if the connection is open, we need to ask the inner connection what it's
// current packet size is because it may have gotten changed, otherwise we
// can just return what the connection string had.
get
{
SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds);
int result;
if (null != innerConnection)
{
result = innerConnection.PacketSize;
}
else
{
SqlConnectionString constr = (SqlConnectionString)ConnectionOptions;
result = ((null != constr) ? constr.PacketSize : SqlConnectionString.DEFAULT.Packet_Size);
}
return result;
}
}
public Guid ClientConnectionId
{
get
{
SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds);
if (null != innerConnection)
{
return innerConnection.ClientConnectionId;
}
else
{
Task reconnectTask = _currentReconnectionTask;
if (reconnectTask != null && !reconnectTask.IsCompleted)
{
return _originalConnectionId;
}
return Guid.Empty;
}
}
}
public override string ServerVersion
{
get => GetOpenTdsConnection().ServerVersion;
}
public override ConnectionState State
{
get
{
Task reconnectTask = _currentReconnectionTask;
if (reconnectTask != null && !reconnectTask.IsCompleted)
{
return ConnectionState.Open;
}
return InnerConnection.State;
}
}
internal SqlStatistics Statistics
{
get => _statistics;
}
public string WorkstationId
{
get
{
// If not supplied by the user, the default value is the MachineName
// Note: In Longhorn you'll be able to rename a machine without
// rebooting. Therefore, don't cache this machine name.
SqlConnectionString constr = (SqlConnectionString)ConnectionOptions;
string result = constr?.WorkstationId ?? Environment.MachineName;
return result;
}
}
public SqlCredential Credential
{
get
{
SqlCredential result = _credential;
// When a connection is connecting or is ever opened, make credential available only if "Persist Security Info" is set to true
// otherwise, return null
SqlConnectionString connectionOptions = (SqlConnectionString)UserConnectionOptions;
if (InnerConnection.ShouldHidePassword && connectionOptions != null && !connectionOptions.PersistSecurityInfo)
{
result = null;
}
return result;
}
set
{
// If a connection is connecting or is ever opened, user id/password cannot be set
if (!InnerConnection.AllowSetConnectionString)
{
throw ADP.OpenConnectionPropertySet(nameof(Credential), InnerConnection.State);
}
// check if the usage of credential has any conflict with the keys used in connection string
if (value != null)
{
CheckAndThrowOnInvalidCombinationOfConnectionStringAndSqlCredential((SqlConnectionString)ConnectionOptions);
if (_accessToken != null)
{
throw ADP.InvalidMixedUsageOfCredentialAndAccessToken();
}
}
_credential = value;
// Need to call ConnectionString_Set to do proper pool group check
ConnectionString_Set(new SqlConnectionPoolKey(_connectionString, _credential, accessToken: _accessToken));
}
}
// CheckAndThrowOnInvalidCombinationOfConnectionStringAndSqlCredential: check if the usage of credential has any conflict
// with the keys used in connection string
// If there is any conflict, it throws InvalidOperationException
// This is used in the setter of ConnectionString and Credential properties.
private void CheckAndThrowOnInvalidCombinationOfConnectionStringAndSqlCredential(SqlConnectionString connectionOptions)
{
if (UsesClearUserIdOrPassword(connectionOptions))
{
throw ADP.InvalidMixedUsageOfSecureAndClearCredential();
}
if (UsesIntegratedSecurity(connectionOptions))
{
throw ADP.InvalidMixedUsageOfSecureCredentialAndIntegratedSecurity();
}
}
// CheckAndThrowOnInvalidCombinationOfConnectionOptionAndAccessToken: check if the usage of AccessToken has any conflict
// with the keys used in connection string and credential
// If there is any conflict, it throws InvalidOperationException
// This is to be used setter of ConnectionString and AccessToken properties
private void CheckAndThrowOnInvalidCombinationOfConnectionOptionAndAccessToken(SqlConnectionString connectionOptions)
{
if (UsesClearUserIdOrPassword(connectionOptions))
{
throw ADP.InvalidMixedUsageOfAccessTokenAndUserIDPassword();
}
if (UsesIntegratedSecurity(connectionOptions))
{
throw ADP.InvalidMixedUsageOfAccessTokenAndIntegratedSecurity();
}
// Check if the usage of AccessToken has the conflict with credential
if (_credential != null)
{
throw ADP.InvalidMixedUsageOfCredentialAndAccessToken();
}
}
protected override DbProviderFactory DbProviderFactory
{
get => SqlClientFactory.Instance;
}
// SqlCredential: Pair User Id and password in SecureString which are to be used for SQL authentication
//
// PUBLIC EVENTS
//
public event SqlInfoMessageEventHandler InfoMessage;
public bool FireInfoMessageEventOnUserErrors
{
get => _fireInfoMessageEventOnUserErrors;
set => _fireInfoMessageEventOnUserErrors = value;
}
// Approx. number of times that the internal connection has been reconnected
internal int ReconnectCount
{
get => _reconnectCount;
}
internal bool ForceNewConnection { get; set; }
protected override void OnStateChange(StateChangeEventArgs stateChange)
{
if (!_suppressStateChangeForReconnection)
{
base.OnStateChange(stateChange);
}
}
//
// PUBLIC METHODS
//
new public SqlTransaction BeginTransaction()
{
// this is just a delegate. The actual method tracks executiontime
return BeginTransaction(IsolationLevel.Unspecified, null);
}
new public SqlTransaction BeginTransaction(IsolationLevel iso)
{
// this is just a delegate. The actual method tracks executiontime
return BeginTransaction(iso, null);
}
public SqlTransaction BeginTransaction(string transactionName)
{
// Use transaction names only on the outermost pair of nested
// BEGIN...COMMIT or BEGIN...ROLLBACK statements. Transaction names
// are ignored for nested BEGIN's. The only way to rollback a nested
// transaction is to have a save point from a SAVE TRANSACTION call.
return BeginTransaction(IsolationLevel.Unspecified, transactionName);
}
[SuppressMessage("Microsoft.Reliability", "CA2004:RemoveCallsToGCKeepAlive")]
override protected DbTransaction BeginDbTransaction(IsolationLevel isolationLevel)
{
DbTransaction transaction = BeginTransaction(isolationLevel);
// InnerConnection doesn't maintain a ref on the outer connection (this) and
// subsequently leaves open the possibility that the outer connection could be GC'ed before the SqlTransaction
// is fully hooked up (leaving a DbTransaction with a null connection property). Ensure that this is reachable
// until the completion of BeginTransaction with KeepAlive
GC.KeepAlive(this);
return transaction;
}
public SqlTransaction BeginTransaction(IsolationLevel iso, string transactionName)
{
WaitForPendingReconnection();
SqlStatistics statistics = null;
try
{
statistics = SqlStatistics.StartTimer(Statistics);
SqlTransaction transaction;
bool isFirstAttempt = true;
do
{
transaction = GetOpenTdsConnection().BeginSqlTransaction(iso, transactionName, isFirstAttempt); // do not reconnect twice
Debug.Assert(isFirstAttempt || !transaction.InternalTransaction.ConnectionHasBeenRestored, "Restored connection on non-first attempt");
isFirstAttempt = false;
} while (transaction.InternalTransaction.ConnectionHasBeenRestored);
// The GetOpenConnection line above doesn't keep a ref on the outer connection (this),
// and it could be collected before the inner connection can hook it to the transaction, resulting in
// a transaction with a null connection property. Use GC.KeepAlive to ensure this doesn't happen.
GC.KeepAlive(this);
return transaction;
}
finally
{
SqlStatistics.StopTimer(statistics);
}
}
public override void ChangeDatabase(string database)
{
SqlStatistics statistics = null;
RepairInnerConnection();
try
{
statistics = SqlStatistics.StartTimer(Statistics);
InnerConnection.ChangeDatabase(database);
}
finally
{
SqlStatistics.StopTimer(statistics);
}
}
public static void ClearAllPools()
{
SqlConnectionFactory.SingletonInstance.ClearAllPools();
}
public static void ClearPool(SqlConnection connection)
{
ADP.CheckArgumentNull(connection, nameof(connection));
DbConnectionOptions connectionOptions = connection.UserConnectionOptions;
if (null != connectionOptions)
{
SqlConnectionFactory.SingletonInstance.ClearPool(connection);
}
}
private void CloseInnerConnection()
{
// CloseConnection() now handles the lock
// The SqlInternalConnectionTds is set to OpenBusy during close, once this happens the cast below will fail and
// the command will no longer be cancelable. It might be desirable to be able to cancel the close operation, but this is
// outside of the scope of Whidbey RTM. See (SqlCommand::Cancel) for other lock.
InnerConnection.CloseConnection(this, ConnectionFactory);
}
public override void Close()
{
ConnectionState previousState = State;
Guid operationId = default(Guid);
Guid clientConnectionId = default(Guid);
// during the call to Dispose() there is a redundant call to
// Close(). because of this, the second time Close() is invoked the
// connection is already in a closed state. this doesn't seem to be a
// problem except for logging, as we'll get duplicate Before/After/Error
// log entries
if (previousState != ConnectionState.Closed)
{
operationId = s_diagnosticListener.WriteConnectionCloseBefore(this);
// we want to cache the ClientConnectionId for After/Error logging, as when the connection
// is closed then we will lose this identifier
//
// note: caching this is only for diagnostics logging purposes
clientConnectionId = ClientConnectionId;
}
SqlStatistics statistics = null;
Exception e = null;
try
{
statistics = SqlStatistics.StartTimer(Statistics);
Task reconnectTask = _currentReconnectionTask;
if (reconnectTask != null && !reconnectTask.IsCompleted)
{
CancellationTokenSource cts = _reconnectionCancellationSource;
if (cts != null)
{
cts.Cancel();
}
AsyncHelper.WaitForCompletion(reconnectTask, 0, null, rethrowExceptions: false); // we do not need to deal with possible exceptions in reconnection
if (State != ConnectionState.Open)
{// if we cancelled before the connection was opened
OnStateChange(DbConnectionInternal.StateChangeClosed);
}
}
CancelOpenAndWait();
CloseInnerConnection();
GC.SuppressFinalize(this);
if (null != Statistics)
{
ADP.TimerCurrent(out _statistics._closeTimestamp);
}
}
catch (Exception ex)
{
e = ex;
throw;
}
finally
{
SqlStatistics.StopTimer(statistics);
// we only want to log this if the previous state of the
// connection is open, as that's the valid use-case
if (previousState != ConnectionState.Closed)
{
if (e != null)
{
s_diagnosticListener.WriteConnectionCloseError(operationId, clientConnectionId, this, e);
}
else
{
s_diagnosticListener.WriteConnectionCloseAfter(operationId, clientConnectionId, this);
}
}
}
}
new public SqlCommand CreateCommand()
{
return new SqlCommand(null, this);
}
private void DisposeMe(bool disposing)
{
_credential = null;
_accessToken = null;
if (!disposing)
{
// For non-pooled connections we need to make sure that if the SqlConnection was not closed,
// then we release the GCHandle on the stateObject to allow it to be GCed
// For pooled connections, we will rely on the pool reclaiming the connection
var innerConnection = (InnerConnection as SqlInternalConnectionTds);
if ((innerConnection != null) && (!innerConnection.ConnectionOptions.Pooling))
{
var parser = innerConnection.Parser;
if ((parser != null) && (parser._physicalStateObj != null))
{
parser._physicalStateObj.DecrementPendingCallbacks(release: false);
}
}
}
}
public override void Open()
{
Guid operationId = s_diagnosticListener.WriteConnectionOpenBefore(this);
PrepareStatisticsForNewConnection();
SqlStatistics statistics = null;
Exception e = null;
try
{
statistics = SqlStatistics.StartTimer(Statistics);
if (!TryOpen(null))
{
throw ADP.InternalError(ADP.InternalErrorCode.SynchronousConnectReturnedPending);
}
}
catch (Exception ex)
{
e = ex;
throw;
}
finally
{
SqlStatistics.StopTimer(statistics);
if (e != null)
{
s_diagnosticListener.WriteConnectionOpenError(operationId, this, e);
}
else
{
s_diagnosticListener.WriteConnectionOpenAfter(operationId, this);
}
}
}
internal void RegisterWaitingForReconnect(Task waitingTask)
{
if (((SqlConnectionString)ConnectionOptions).MARS)
{
return;
}
Interlocked.CompareExchange(ref _asyncWaitingForReconnection, waitingTask, null);
if (_asyncWaitingForReconnection != waitingTask)
{ // somebody else managed to register
throw SQL.MARSUnspportedOnConnection();
}
}
private async Task ReconnectAsync(int timeout)
{
try
{
long commandTimeoutExpiration = 0;
if (timeout > 0)
{
commandTimeoutExpiration = ADP.TimerCurrent() + ADP.TimerFromSeconds(timeout);
}
CancellationTokenSource cts = new CancellationTokenSource();
_reconnectionCancellationSource = cts;
CancellationToken ctoken = cts.Token;
int retryCount = _connectRetryCount; // take a snapshot: could be changed by modifying the connection string
for (int attempt = 0; attempt < retryCount; attempt++)
{
if (ctoken.IsCancellationRequested)
{
return;
}
try
{
try
{
ForceNewConnection = true;
await OpenAsync(ctoken).ConfigureAwait(false);
// On success, increment the reconnect count - we don't really care if it rolls over since it is approx.
_reconnectCount = unchecked(_reconnectCount + 1);
#if DEBUG
Debug.Assert(_recoverySessionData._debugReconnectDataApplied, "Reconnect data was not applied !");
#endif
}
finally
{
ForceNewConnection = false;
}
return;
}
catch (SqlException e)
{
if (attempt == retryCount - 1)
{
throw SQL.CR_AllAttemptsFailed(e, _originalConnectionId);
}
if (timeout > 0 && ADP.TimerRemaining(commandTimeoutExpiration) < ADP.TimerFromSeconds(ConnectRetryInterval))
{
throw SQL.CR_NextAttemptWillExceedQueryTimeout(e, _originalConnectionId);
}
}
await Task.Delay(1000 * ConnectRetryInterval, ctoken).ConfigureAwait(false);
}
}
finally
{
_recoverySessionData = null;
_suppressStateChangeForReconnection = false;
}
Debug.Assert(false, "Should not reach this point");
}
internal Task ValidateAndReconnect(Action beforeDisconnect, int timeout)
{
Task runningReconnect = _currentReconnectionTask;
// This loop in the end will return not completed reconnect task or null
while (runningReconnect != null && runningReconnect.IsCompleted)
{
// clean current reconnect task (if it is the same one we checked
Interlocked.CompareExchange<Task>(ref _currentReconnectionTask, null, runningReconnect);
// make sure nobody started new task (if which case we did not clean it)
runningReconnect = _currentReconnectionTask;
}
if (runningReconnect == null)
{
if (_connectRetryCount > 0)
{
SqlInternalConnectionTds tdsConn = GetOpenTdsConnection();
if (tdsConn._sessionRecoveryAcknowledged)
{
TdsParserStateObject stateObj = tdsConn.Parser._physicalStateObj;
if (!stateObj.ValidateSNIConnection())
{
if (tdsConn.Parser._sessionPool != null)
{
if (tdsConn.Parser._sessionPool.ActiveSessionsCount > 0)
{
// >1 MARS session
if (beforeDisconnect != null)
{
beforeDisconnect();
}
OnError(SQL.CR_UnrecoverableClient(ClientConnectionId), true, null);
}
}
SessionData cData = tdsConn.CurrentSessionData;
cData.AssertUnrecoverableStateCountIsCorrect();
if (cData._unrecoverableStatesCount == 0)
{
bool callDisconnect = false;
lock (_reconnectLock)
{
tdsConn.CheckEnlistedTransactionBinding();
runningReconnect = _currentReconnectionTask; // double check after obtaining the lock
if (runningReconnect == null)
{
if (cData._unrecoverableStatesCount == 0)
{ // could change since the first check, but now is stable since connection is know to be broken
_originalConnectionId = ClientConnectionId;
_recoverySessionData = cData;
if (beforeDisconnect != null)
{
beforeDisconnect();
}
try
{
_suppressStateChangeForReconnection = true;
tdsConn.DoomThisConnection();
}
catch (SqlException)
{
}
runningReconnect = Task.Run(() => ReconnectAsync(timeout));
// if current reconnect is not null, somebody already started reconnection task - some kind of race condition
Debug.Assert(_currentReconnectionTask == null, "Duplicate reconnection tasks detected");
_currentReconnectionTask = runningReconnect;
}
}
else
{
callDisconnect = true;
}
}
if (callDisconnect && beforeDisconnect != null)
{
beforeDisconnect();
}
}
else
{
if (beforeDisconnect != null)
{
beforeDisconnect();
}
OnError(SQL.CR_UnrecoverableServer(ClientConnectionId), true, null);
}
} // ValidateSNIConnection
} // sessionRecoverySupported
} // connectRetryCount>0
}
else
{ // runningReconnect = null
if (beforeDisconnect != null)
{
beforeDisconnect();
}
}
return runningReconnect;
}
// this is straightforward, but expensive method to do connection resiliency - it take locks and all preparations as for TDS request
partial void RepairInnerConnection()
{
WaitForPendingReconnection();
if (_connectRetryCount == 0)
{
return;
}
SqlInternalConnectionTds tdsConn = InnerConnection as SqlInternalConnectionTds;
if (tdsConn != null)
{
tdsConn.ValidateConnectionForExecute(null);
tdsConn.GetSessionAndReconnectIfNeeded((SqlConnection)this);
}
}
private void WaitForPendingReconnection()
{
Task reconnectTask = _currentReconnectionTask;
if (reconnectTask != null && !reconnectTask.IsCompleted)
{
AsyncHelper.WaitForCompletion(reconnectTask, 0, null, rethrowExceptions: false);
}
}
private void CancelOpenAndWait()
{
// copy from member to avoid changes by background thread
var completion = _currentCompletion;
if (completion != null)
{
completion.Item1.TrySetCanceled();
((IAsyncResult)completion.Item2).AsyncWaitHandle.WaitOne();
}
Debug.Assert(_currentCompletion == null, "After waiting for an async call to complete, there should be no completion source");
}
public override Task OpenAsync(CancellationToken cancellationToken)
{
Guid operationId = s_diagnosticListener.WriteConnectionOpenBefore(this);
PrepareStatisticsForNewConnection();
SqlStatistics statistics = null;
try
{
statistics = SqlStatistics.StartTimer(Statistics);
System.Transactions.Transaction transaction = ADP.GetCurrentTransaction();
TaskCompletionSource<DbConnectionInternal> completion = new TaskCompletionSource<DbConnectionInternal>(transaction);
TaskCompletionSource<object> result = new TaskCompletionSource<object>();
if (s_diagnosticListener.IsEnabled(SqlClientDiagnosticListenerExtensions.SqlAfterOpenConnection) ||
s_diagnosticListener.IsEnabled(SqlClientDiagnosticListenerExtensions.SqlErrorOpenConnection))
{
result.Task.ContinueWith((t) =>
{
if (t.Exception != null)
{
s_diagnosticListener.WriteConnectionOpenError(operationId, this, t.Exception);
}
else
{
s_diagnosticListener.WriteConnectionOpenAfter(operationId, this);
}
}, TaskScheduler.Default);
}
if (cancellationToken.IsCancellationRequested)
{
result.SetCanceled();
return result.Task;
}
bool completed;
try
{
completed = TryOpen(completion);
}
catch (Exception e)
{
s_diagnosticListener.WriteConnectionOpenError(operationId, this, e);
result.SetException(e);
return result.Task;
}
if (completed)
{
result.SetResult(null);
}
else
{
CancellationTokenRegistration registration = new CancellationTokenRegistration();
if (cancellationToken.CanBeCanceled)
{
registration = cancellationToken.Register(s => ((TaskCompletionSource<DbConnectionInternal>)s).TrySetCanceled(), completion);
}
OpenAsyncRetry retry = new OpenAsyncRetry(this, completion, result, registration);
_currentCompletion = new Tuple<TaskCompletionSource<DbConnectionInternal>, Task>(completion, result.Task);
completion.Task.ContinueWith(retry.Retry, TaskScheduler.Default);
return result.Task;
}
return result.Task;
}
catch (Exception ex)
{
s_diagnosticListener.WriteConnectionOpenError(operationId, this, ex);
throw;
}
finally
{
SqlStatistics.StopTimer(statistics);
}
}
public override DataTable GetSchema()
{
return GetSchema(DbMetaDataCollectionNames.MetaDataCollections, null);
}
public override DataTable GetSchema(string collectionName)
{
return GetSchema(collectionName, null);
}
public override DataTable GetSchema(string collectionName, string[] restrictionValues)
{
return InnerConnection.GetSchema(ConnectionFactory, PoolGroup, this, collectionName, restrictionValues);
}
private class OpenAsyncRetry
{
private SqlConnection _parent;
private TaskCompletionSource<DbConnectionInternal> _retry;
private TaskCompletionSource<object> _result;
private CancellationTokenRegistration _registration;
public OpenAsyncRetry(SqlConnection parent, TaskCompletionSource<DbConnectionInternal> retry, TaskCompletionSource<object> result, CancellationTokenRegistration registration)
{
_parent = parent;
_retry = retry;
_result = result;
_registration = registration;
}
internal void Retry(Task<DbConnectionInternal> retryTask)
{
_registration.Dispose();
try
{
SqlStatistics statistics = null;
try
{
statistics = SqlStatistics.StartTimer(_parent.Statistics);
if (retryTask.IsFaulted)
{
Exception e = retryTask.Exception.InnerException;
_parent.CloseInnerConnection();
_parent._currentCompletion = null;
_result.SetException(retryTask.Exception.InnerException);
}
else if (retryTask.IsCanceled)
{
_parent.CloseInnerConnection();
_parent._currentCompletion = null;
_result.SetCanceled();
}
else
{
bool result;
// protect continuation from races with close and cancel
lock (_parent.InnerConnection)
{
result = _parent.TryOpen(_retry);
}
if (result)
{
_parent._currentCompletion = null;
_result.SetResult(null);
}
else
{
_parent.CloseInnerConnection();
_parent._currentCompletion = null;
_result.SetException(ADP.ExceptionWithStackTrace(ADP.InternalError(ADP.InternalErrorCode.CompletedConnectReturnedPending)));
}
}
}
finally
{
SqlStatistics.StopTimer(statistics);
}
}
catch (Exception e)
{
_parent.CloseInnerConnection();
_parent._currentCompletion = null;
_result.SetException(e);
}
}
}
private void PrepareStatisticsForNewConnection()
{
if (StatisticsEnabled ||
s_diagnosticListener.IsEnabled(SqlClientDiagnosticListenerExtensions.SqlAfterExecuteCommand) ||
s_diagnosticListener.IsEnabled(SqlClientDiagnosticListenerExtensions.SqlAfterOpenConnection))
{
if (null == _statistics)
{
_statistics = new SqlStatistics();
}
else
{
_statistics.ContinueOnNewConnection();
}
}
}
private bool TryOpen(TaskCompletionSource<DbConnectionInternal> retry)
{
SqlConnectionString connectionOptions = (SqlConnectionString)ConnectionOptions;
_applyTransientFaultHandling = (retry == null && connectionOptions != null && connectionOptions.ConnectRetryCount > 0);
if (ForceNewConnection)
{
if (!InnerConnection.TryReplaceConnection(this, ConnectionFactory, retry, UserConnectionOptions))
{
return false;
}
}
else
{
if (!InnerConnection.TryOpenConnection(this, ConnectionFactory, retry, UserConnectionOptions))
{
return false;
}
}
// does not require GC.KeepAlive(this) because of ReRegisterForFinalize below.
var tdsInnerConnection = (SqlInternalConnectionTds)InnerConnection;
Debug.Assert(tdsInnerConnection.Parser != null, "Where's the parser?");
if (!tdsInnerConnection.ConnectionOptions.Pooling)
{
// For non-pooled connections, we need to make sure that the finalizer does actually run to avoid leaking SNI handles
GC.ReRegisterForFinalize(this);
}
// The _statistics can change with StatisticsEnabled. Copying to a local variable before checking for a null value.
SqlStatistics statistics = _statistics;
if (StatisticsEnabled ||
(s_diagnosticListener.IsEnabled(SqlClientDiagnosticListenerExtensions.SqlAfterExecuteCommand) && statistics != null))
{
ADP.TimerCurrent(out _statistics._openTimestamp);
tdsInnerConnection.Parser.Statistics = _statistics;
}
else
{
tdsInnerConnection.Parser.Statistics = null;
_statistics = null; // in case of previous Open/Close/reset_CollectStats sequence
}
return true;
}
//
// INTERNAL PROPERTIES
//
internal bool HasLocalTransaction
{
get
{
return GetOpenTdsConnection().HasLocalTransaction;
}
}
internal bool HasLocalTransactionFromAPI
{
get
{
Task reconnectTask = _currentReconnectionTask;
if (reconnectTask != null && !reconnectTask.IsCompleted)
{
return false; //we will not go into reconnection if we are inside the transaction
}
return GetOpenTdsConnection().HasLocalTransactionFromAPI;
}
}
internal bool IsKatmaiOrNewer
{
get
{
if (_currentReconnectionTask != null)
{ // holds true even if task is completed
return true; // if CR is enabled, connection, if established, will be Katmai+
}
return GetOpenTdsConnection().IsKatmaiOrNewer;
}
}
internal TdsParser Parser
{
get
{
SqlInternalConnectionTds tdsConnection = GetOpenTdsConnection();
return tdsConnection.Parser;
}
}
//
// INTERNAL METHODS
//
internal void ValidateConnectionForExecute(string method, SqlCommand command)
{
Task asyncWaitingForReconnection = _asyncWaitingForReconnection;
if (asyncWaitingForReconnection != null)
{
if (!asyncWaitingForReconnection.IsCompleted)
{
throw SQL.MARSUnspportedOnConnection();
}
else
{
Interlocked.CompareExchange(ref _asyncWaitingForReconnection, null, asyncWaitingForReconnection);
}
}
if (_currentReconnectionTask != null)
{
Task currentReconnectionTask = _currentReconnectionTask;
if (currentReconnectionTask != null && !currentReconnectionTask.IsCompleted)
{
return; // execution will wait for this task later
}
}
SqlInternalConnectionTds innerConnection = GetOpenTdsConnection(method);
innerConnection.ValidateConnectionForExecute(command);
}
// Surround name in brackets and then escape any end bracket to protect against SQL Injection.
// NOTE: if the user escapes it themselves it will not work, but this was the case in V1 as well
// as native OleDb and Odbc.
internal static string FixupDatabaseTransactionName(string name)
{
if (!string.IsNullOrEmpty(name))
{
return SqlServerEscapeHelper.EscapeIdentifier(name);
}
else
{
return name;
}
}
// If wrapCloseInAction is defined, then the action it defines will be run with the connection close action passed in as a parameter
// The close action also supports being run asynchronously
internal void OnError(SqlException exception, bool breakConnection, Action<Action> wrapCloseInAction)
{
Debug.Assert(exception != null && exception.Errors.Count != 0, "SqlConnection: OnError called with null or empty exception!");
if (breakConnection && (ConnectionState.Open == State))
{
if (wrapCloseInAction != null)
{
int capturedCloseCount = _closeCount;
Action closeAction = () =>
{
if (capturedCloseCount == _closeCount)
{
Close();
}
};
wrapCloseInAction(closeAction);
}
else
{
Close();
}
}
if (exception.Class >= TdsEnums.MIN_ERROR_CLASS)
{
// It is an error, and should be thrown. Class of TdsEnums.MIN_ERROR_CLASS or above is an error,
// below TdsEnums.MIN_ERROR_CLASS denotes an info message.
throw exception;
}
else
{
// If it is a class < TdsEnums.MIN_ERROR_CLASS, it is a warning collection - so pass to handler
this.OnInfoMessage(new SqlInfoMessageEventArgs(exception));
}
}
//
// PRIVATE METHODS
//
internal SqlInternalConnectionTds GetOpenTdsConnection()
{
SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds);
if (null == innerConnection)
{
throw ADP.ClosedConnectionError();
}
return innerConnection;
}
internal SqlInternalConnectionTds GetOpenTdsConnection(string method)
{
SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds);
if (null == innerConnection)
{
throw ADP.OpenConnectionRequired(method, InnerConnection.State);
}
return innerConnection;
}
internal void OnInfoMessage(SqlInfoMessageEventArgs imevent)
{
bool notified;
OnInfoMessage(imevent, out notified);
}
internal void OnInfoMessage(SqlInfoMessageEventArgs imevent, out bool notified)
{
SqlInfoMessageEventHandler handler = InfoMessage;
if (null != handler)
{
notified = true;
try
{
handler(this, imevent);
}
catch (Exception e)
{
if (!ADP.IsCatchableOrSecurityExceptionType(e))
{
throw;
}
}
}
else
{
notified = false;
}
}
public static void ChangePassword(string connectionString, string newPassword)
{
if (string.IsNullOrEmpty(connectionString))
{
throw SQL.ChangePasswordArgumentMissing(nameof(newPassword));
}
if (string.IsNullOrEmpty(newPassword))
{
throw SQL.ChangePasswordArgumentMissing(nameof(newPassword));
}
if (TdsEnums.MAXLEN_NEWPASSWORD < newPassword.Length)
{
throw ADP.InvalidArgumentLength(nameof(newPassword), TdsEnums.MAXLEN_NEWPASSWORD);
}
SqlConnectionPoolKey key = new SqlConnectionPoolKey(connectionString, credential: null, accessToken: null);
SqlConnectionString connectionOptions = SqlConnectionFactory.FindSqlConnectionOptions(key);
if (connectionOptions.IntegratedSecurity)
{
throw SQL.ChangePasswordConflictsWithSSPI();
}
if (!string.IsNullOrEmpty(connectionOptions.AttachDBFilename))
{
throw SQL.ChangePasswordUseOfUnallowedKey(SqlConnectionString.KEY.AttachDBFilename);
}
ChangePassword(connectionString, connectionOptions, null, newPassword, null);
}
public static void ChangePassword(string connectionString, SqlCredential credential, SecureString newSecurePassword)
{
if (string.IsNullOrEmpty(connectionString))
{
throw SQL.ChangePasswordArgumentMissing(nameof(connectionString));
}
// check credential; not necessary to check the length of password in credential as the check is done by SqlCredential class
if (credential == null)
{
throw SQL.ChangePasswordArgumentMissing(nameof(credential));
}
if (newSecurePassword == null || newSecurePassword.Length == 0)
{
throw SQL.ChangePasswordArgumentMissing(nameof(newSecurePassword));
}
if (!newSecurePassword.IsReadOnly())
{
throw ADP.MustBeReadOnly(nameof(newSecurePassword));
}
if (TdsEnums.MAXLEN_NEWPASSWORD < newSecurePassword.Length)
{
throw ADP.InvalidArgumentLength(nameof(newSecurePassword), TdsEnums.MAXLEN_NEWPASSWORD);
}
SqlConnectionPoolKey key = new SqlConnectionPoolKey(connectionString, credential: null, accessToken: null);
SqlConnectionString connectionOptions = SqlConnectionFactory.FindSqlConnectionOptions(key);
// Check for connection string values incompatible with SqlCredential
if (!string.IsNullOrEmpty(connectionOptions.UserID) || !string.IsNullOrEmpty(connectionOptions.Password))
{
throw ADP.InvalidMixedArgumentOfSecureAndClearCredential();
}
if (connectionOptions.IntegratedSecurity)
{
throw SQL.ChangePasswordConflictsWithSSPI();
}
if (!string.IsNullOrEmpty(connectionOptions.AttachDBFilename))
{
throw SQL.ChangePasswordUseOfUnallowedKey(SqlConnectionString.KEY.AttachDBFilename);
}
ChangePassword(connectionString, connectionOptions, credential, null, newSecurePassword);
}
private static void ChangePassword(string connectionString, SqlConnectionString connectionOptions, SqlCredential credential, string newPassword, SecureString newSecurePassword)
{
// note: This is the only case where we directly construct the internal connection, passing in the new password.
// Normally we would simply create a regular connection and open it, but there is no other way to pass the
// new password down to the constructor. This would have an unwanted impact on the connection pool.
SqlInternalConnectionTds con = null;
try
{
con = new SqlInternalConnectionTds(null, connectionOptions, credential, null, newPassword, newSecurePassword, false);
}
finally
{
if (con != null)
con.Dispose();
}
SqlConnectionPoolKey key = new SqlConnectionPoolKey(connectionString, credential: null, accessToken: null);
SqlConnectionFactory.SingletonInstance.ClearPool(key);
}
//
// SQL DEBUGGING SUPPORT
//
// this only happens once per connection
// SxS: using named file mapping APIs
internal void RegisterForConnectionCloseNotification<T>(ref Task<T> outerTask, object value, int tag)
{
// Connection exists, schedule removal, will be added to ref collection after calling ValidateAndReconnect
outerTask = outerTask.ContinueWith(task =>
{
RemoveWeakReference(value);
return task;
}, TaskScheduler.Default).Unwrap();
}
public void ResetStatistics()
{
if (null != Statistics)
{
Statistics.Reset();
if (ConnectionState.Open == State)
{
// update timestamp;
ADP.TimerCurrent(out _statistics._openTimestamp);
}
}
}
public IDictionary RetrieveStatistics()
{
if (null != Statistics)
{
UpdateStatistics();
return Statistics.GetDictionary();
}
else
{
return new SqlStatistics().GetDictionary();
}
}
private void UpdateStatistics()
{
if (ConnectionState.Open == State)
{
// update timestamp
ADP.TimerCurrent(out _statistics._closeTimestamp);
}
// delegate the rest of the work to the SqlStatistics class
Statistics.UpdateStatistics();
}
object ICloneable.Clone() => new SqlConnection(this);
private void CopyFrom(SqlConnection connection)
{
ADP.CheckArgumentNull(connection, nameof(connection));
_userConnectionOptions = connection.UserConnectionOptions;
_poolGroup = connection.PoolGroup;
if (DbConnectionClosedNeverOpened.SingletonInstance == connection._innerConnection)
{
_innerConnection = DbConnectionClosedNeverOpened.SingletonInstance;
}
else
{
_innerConnection = DbConnectionClosedPreviouslyOpened.SingletonInstance;
}
}
// UDT SUPPORT
private Assembly ResolveTypeAssembly(AssemblyName asmRef, bool throwOnError)
{
Debug.Assert(TypeSystemAssemblyVersion != null, "TypeSystemAssembly should be set !");
if (string.Equals(asmRef.Name, "Microsoft.SqlServer.Types", StringComparison.OrdinalIgnoreCase))
{
asmRef.Version = TypeSystemAssemblyVersion;
}
try
{
return Assembly.Load(asmRef);
}
catch (Exception e)
{
if (throwOnError || !ADP.IsCatchableExceptionType(e))
{
throw;
}
else
{
return null;
};
}
}
internal void CheckGetExtendedUDTInfo(SqlMetaDataPriv metaData, bool fThrow)
{
if (metaData.udtType == null)
{ // If null, we have not obtained extended info.
Debug.Assert(!string.IsNullOrEmpty(metaData.udtAssemblyQualifiedName), "Unexpected state on GetUDTInfo");
// Parameter throwOnError determines whether exception from Assembly.Load is thrown.
metaData.udtType =
Type.GetType(typeName: metaData.udtAssemblyQualifiedName, assemblyResolver: asmRef => ResolveTypeAssembly(asmRef, fThrow), typeResolver: null, throwOnError: fThrow);
if (fThrow && metaData.udtType == null)
{
throw SQL.UDTUnexpectedResult(metaData.udtAssemblyQualifiedName);
}
}
}
internal object GetUdtValue(object value, SqlMetaDataPriv metaData, bool returnDBNull)
{
if (returnDBNull && ADP.IsNull(value))
{
return DBNull.Value;
}
object o = null;
// Since the serializer doesn't handle nulls...
if (ADP.IsNull(value))
{
Type t = metaData.udtType;
Debug.Assert(t != null, "Unexpected null of udtType on GetUdtValue!");
o = t.InvokeMember("Null", BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.Static, null, null, Array.Empty<object>(), CultureInfo.InvariantCulture);
Debug.Assert(o != null);
return o;
}
else
{
MemoryStream stm = new MemoryStream((byte[])value);
o = SerializationHelperSql9.Deserialize(stm, metaData.udtType);
Debug.Assert(o != null, "object could NOT be created");
return o;
}
}
internal byte[] GetBytes(object o)
{
Format format = Format.Native;
return GetBytes(o, out format, out int maxSize);
}
internal byte[] GetBytes(object o, out Format format, out int maxSize)
{
SqlUdtInfo attr = GetInfoFromType(o.GetType());
maxSize = attr.MaxByteSize;
format = attr.SerializationFormat;
if (maxSize < -1 || maxSize >= ushort.MaxValue)
{
throw new InvalidOperationException(o.GetType() + ": invalid Size");
}
byte[] retval;
using (MemoryStream stm = new MemoryStream(maxSize < 0 ? 0 : maxSize))
{
SerializationHelperSql9.Serialize(stm, o);
retval = stm.ToArray();
}
return retval;
}
private SqlUdtInfo GetInfoFromType(Type t)
{
Debug.Assert(t != null, "Type object cant be NULL");
Type orig = t;
do
{
SqlUdtInfo attr = SqlUdtInfo.TryGetFromType(t);
if (attr != null)
{
return attr;
}
else
{
t = t.BaseType;
}
}
while (t != null);
throw SQL.UDTInvalidSqlType(orig.AssemblyQualifiedName);
}
}
}
| |
using System;
using System.Collections;
using System.IO;
using System.Text;
using Raksha.Utilities;
using Raksha.Utilities.Encoders;
namespace Raksha.Asn1.Utilities
{
public sealed class Asn1Dump
{
private static readonly string NewLine = Platform.NewLine;
private Asn1Dump()
{
}
private const string Tab = " ";
private const int SampleSize = 32;
/**
* dump a Der object as a formatted string with indentation
*
* @param obj the Asn1Object to be dumped out.
*/
private static void AsString(
string indent,
bool verbose,
Asn1Object obj,
StringBuilder buf)
{
if (obj is Asn1Sequence)
{
string tab = indent + Tab;
buf.Append(indent);
if (obj is BerSequence)
{
buf.Append("BER Sequence");
}
else if (obj is DerSequence)
{
buf.Append("DER Sequence");
}
else
{
buf.Append("Sequence");
}
buf.Append(NewLine);
foreach (Asn1Encodable o in ((Asn1Sequence)obj))
{
if (o == null || o is Asn1Null)
{
buf.Append(tab);
buf.Append("NULL");
buf.Append(NewLine);
}
else
{
AsString(tab, verbose, o.ToAsn1Object(), buf);
}
}
}
else if (obj is DerTaggedObject)
{
string tab = indent + Tab;
buf.Append(indent);
if (obj is BerTaggedObject)
{
buf.Append("BER Tagged [");
}
else
{
buf.Append("Tagged [");
}
DerTaggedObject o = (DerTaggedObject)obj;
buf.Append(((int)o.TagNo).ToString());
buf.Append(']');
if (!o.IsExplicit())
{
buf.Append(" IMPLICIT ");
}
buf.Append(NewLine);
if (o.IsEmpty())
{
buf.Append(tab);
buf.Append("EMPTY");
buf.Append(NewLine);
}
else
{
AsString(tab, verbose, o.GetObject(), buf);
}
}
else if (obj is BerSet)
{
string tab = indent + Tab;
buf.Append(indent);
buf.Append("BER Set");
buf.Append(NewLine);
foreach (Asn1Encodable o in ((Asn1Set)obj))
{
if (o == null)
{
buf.Append(tab);
buf.Append("NULL");
buf.Append(NewLine);
}
else
{
AsString(tab, verbose, o.ToAsn1Object(), buf);
}
}
}
else if (obj is DerSet)
{
string tab = indent + Tab;
buf.Append(indent);
buf.Append("DER Set");
buf.Append(NewLine);
foreach (Asn1Encodable o in ((Asn1Set)obj))
{
if (o == null)
{
buf.Append(tab);
buf.Append("NULL");
buf.Append(NewLine);
}
else
{
AsString(tab, verbose, o.ToAsn1Object(), buf);
}
}
}
else if (obj is DerObjectIdentifier)
{
buf.Append(indent + "ObjectIdentifier(" + ((DerObjectIdentifier)obj).Id + ")" + NewLine);
}
else if (obj is DerBoolean)
{
buf.Append(indent + "Boolean(" + ((DerBoolean)obj).IsTrue + ")" + NewLine);
}
else if (obj is DerInteger)
{
buf.Append(indent + "Integer(" + ((DerInteger)obj).Value + ")" + NewLine);
}
else if (obj is BerOctetString)
{
byte[] octets = ((Asn1OctetString)obj).GetOctets();
string extra = verbose ? dumpBinaryDataAsString(indent, octets) : "";
buf.Append(indent + "BER Octet String" + "[" + octets.Length + "] " + extra + NewLine);
}
else if (obj is DerOctetString)
{
byte[] octets = ((Asn1OctetString)obj).GetOctets();
string extra = verbose ? dumpBinaryDataAsString(indent, octets) : "";
buf.Append(indent + "DER Octet String" + "[" + octets.Length + "] " + extra + NewLine);
}
else if (obj is DerBitString)
{
DerBitString bt = (DerBitString)obj;
byte[] bytes = bt.GetBytes();
string extra = verbose ? dumpBinaryDataAsString(indent, bytes) : "";
buf.Append(indent + "DER Bit String" + "[" + bytes.Length + ", " + bt.PadBits + "] " + extra + NewLine);
}
else if (obj is DerIA5String)
{
buf.Append(indent + "IA5String(" + ((DerIA5String)obj).GetString() + ") " + NewLine);
}
else if (obj is DerUtf8String)
{
buf.Append(indent + "UTF8String(" + ((DerUtf8String)obj).GetString() + ") " + NewLine);
}
else if (obj is DerPrintableString)
{
buf.Append(indent + "PrintableString(" + ((DerPrintableString)obj).GetString() + ") " + NewLine);
}
else if (obj is DerVisibleString)
{
buf.Append(indent + "VisibleString(" + ((DerVisibleString)obj).GetString() + ") " + NewLine);
}
else if (obj is DerBmpString)
{
buf.Append(indent + "BMPString(" + ((DerBmpString)obj).GetString() + ") " + NewLine);
}
else if (obj is DerT61String)
{
buf.Append(indent + "T61String(" + ((DerT61String)obj).GetString() + ") " + NewLine);
}
else if (obj is DerUtcTime)
{
buf.Append(indent + "UTCTime(" + ((DerUtcTime)obj).TimeString + ") " + NewLine);
}
else if (obj is DerGeneralizedTime)
{
buf.Append(indent + "GeneralizedTime(" + ((DerGeneralizedTime)obj).GetTime() + ") " + NewLine);
}
else if (obj is DerUnknownTag)
{
string hex = Hex.ToHexString(((DerUnknownTag)obj).GetData());
buf.Append(indent + "Unknown " + ((int)((DerUnknownTag)obj).Tag).ToString("X") + " " + hex + NewLine);
}
else if (obj is BerApplicationSpecific)
{
buf.Append(outputApplicationSpecific("BER", indent, verbose, (BerApplicationSpecific)obj));
}
else if (obj is DerApplicationSpecific)
{
buf.Append(outputApplicationSpecific("DER", indent, verbose, (DerApplicationSpecific)obj));
}
else if (obj is DerEnumerated)
{
DerEnumerated en = (DerEnumerated)obj;
buf.Append(indent + "DER Enumerated(" + en.Value + ")" + NewLine);
}
else if (obj is DerExternal)
{
DerExternal ext = (DerExternal)obj;
buf.Append(indent + "External " + NewLine);
string tab = indent + Tab;
if (ext.DirectReference != null)
{
buf.Append(tab + "Direct Reference: " + ext.DirectReference.Id + NewLine);
}
if (ext.IndirectReference != null)
{
buf.Append(tab + "Indirect Reference: " + ext.IndirectReference.ToString() + NewLine);
}
if (ext.DataValueDescriptor != null)
{
AsString(tab, verbose, ext.DataValueDescriptor, buf);
}
buf.Append(tab + "Encoding: " + ext.Encoding + NewLine);
AsString(tab, verbose, ext.ExternalContent, buf);
}
else
{
buf.Append(indent + obj.ToString() + NewLine);
}
}
private static string outputApplicationSpecific(
string type,
string indent,
bool verbose,
DerApplicationSpecific app)
{
StringBuilder buf = new StringBuilder();
if (app.IsConstructed())
{
try
{
Asn1Sequence s = Asn1Sequence.GetInstance(app.GetObject(Asn1Tags.Sequence));
buf.Append(indent + type + " ApplicationSpecific[" + app.ApplicationTag + "]" + NewLine);
foreach (Asn1Encodable ae in s)
{
AsString(indent + Tab, verbose, ae.ToAsn1Object(), buf);
}
}
catch (IOException e)
{
buf.Append(e);
}
return buf.ToString();
}
return indent + type + " ApplicationSpecific[" + app.ApplicationTag + "] ("
+ Hex.ToHexString(app.GetContents()) + ")" + NewLine;
}
[Obsolete("Use version accepting Asn1Encodable")]
public static string DumpAsString(
object obj)
{
if (obj is Asn1Encodable)
{
StringBuilder buf = new StringBuilder();
AsString("", false, ((Asn1Encodable)obj).ToAsn1Object(), buf);
return buf.ToString();
}
return "unknown object type " + obj.ToString();
}
/**
* dump out a DER object as a formatted string, in non-verbose mode
*
* @param obj the Asn1Encodable to be dumped out.
* @return the resulting string.
*/
public static string DumpAsString(
Asn1Encodable obj)
{
return DumpAsString(obj, false);
}
/**
* Dump out the object as a string
*
* @param obj the Asn1Encodable to be dumped out.
* @param verbose if true, dump out the contents of octet and bit strings.
* @return the resulting string.
*/
public static string DumpAsString(
Asn1Encodable obj,
bool verbose)
{
StringBuilder buf = new StringBuilder();
AsString("", verbose, obj.ToAsn1Object(), buf);
return buf.ToString();
}
private static string dumpBinaryDataAsString(string indent, byte[] bytes)
{
indent += Tab;
StringBuilder buf = new StringBuilder(NewLine);
for (int i = 0; i < bytes.Length; i += SampleSize)
{
if (bytes.Length - i > SampleSize)
{
buf.Append(indent);
buf.Append(Hex.ToHexString(bytes, i, SampleSize));
buf.Append(Tab);
buf.Append(calculateAscString(bytes, i, SampleSize));
buf.Append(NewLine);
}
else
{
buf.Append(indent);
buf.Append(Hex.ToHexString(bytes, i, bytes.Length - i));
for (int j = bytes.Length - i; j != SampleSize; j++)
{
buf.Append(" ");
}
buf.Append(Tab);
buf.Append(calculateAscString(bytes, i, bytes.Length - i));
buf.Append(NewLine);
}
}
return buf.ToString();
}
private static string calculateAscString(
byte[] bytes,
int off,
int len)
{
StringBuilder buf = new StringBuilder();
for (int i = off; i != off + len; i++)
{
char c = (char)bytes[i];
if (c >= ' ' && c <= '~')
{
buf.Append(c);
}
}
return buf.ToString();
}
}
}
| |
#region Copyright notice and license
// Copyright 2015 gRPC 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.
#endregion
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core.Internal;
using Grpc.Core.Logging;
using Grpc.Core.Profiling;
using Grpc.Core.Utils;
namespace Grpc.Core.Internal
{
/// <summary>
/// Base for handling both client side and server side calls.
/// Manages native call lifecycle and provides convenience methods.
/// </summary>
internal abstract class AsyncCallBase<TWrite, TRead> : IReceivedMessageCallback, ISendCompletionCallback
{
static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<AsyncCallBase<TWrite, TRead>>();
protected static readonly Status DeserializeResponseFailureStatus = new Status(StatusCode.Internal, "Failed to deserialize response message.");
readonly Action<TWrite, SerializationContext> serializer;
readonly Func<DeserializationContext, TRead> deserializer;
protected readonly object myLock = new object();
protected INativeCall call;
protected bool disposed;
protected bool started;
protected bool cancelRequested;
protected TaskCompletionSource<TRead> streamingReadTcs; // Completion of a pending streaming read if not null.
protected TaskCompletionSource<object> streamingWriteTcs; // Completion of a pending streaming write or send close from client if not null.
protected TaskCompletionSource<object> sendStatusFromServerTcs;
protected bool isStreamingWriteCompletionDelayed; // Only used for the client side.
protected bool readingDone; // True if last read (i.e. read with null payload) was already received.
protected bool halfcloseRequested; // True if send close have been initiated.
protected bool finished; // True if close has been received from the peer.
protected bool initialMetadataSent;
protected long streamingWritesCounter; // Number of streaming send operations started so far.
public AsyncCallBase(Action<TWrite, SerializationContext> serializer, Func<DeserializationContext, TRead> deserializer)
{
this.serializer = GrpcPreconditions.CheckNotNull(serializer);
this.deserializer = GrpcPreconditions.CheckNotNull(deserializer);
}
/// <summary>
/// Requests cancelling the call.
/// </summary>
public void Cancel()
{
lock (myLock)
{
GrpcPreconditions.CheckState(started);
cancelRequested = true;
if (!disposed)
{
call.Cancel();
}
}
}
/// <summary>
/// Requests cancelling the call with given status.
/// </summary>
protected void CancelWithStatus(Status status)
{
lock (myLock)
{
cancelRequested = true;
if (!disposed)
{
call.CancelWithStatus(status);
}
}
}
protected void InitializeInternal(INativeCall call)
{
lock (myLock)
{
this.call = call;
}
}
/// <summary>
/// Initiates sending a message. Only one send operation can be active at a time.
/// </summary>
protected Task SendMessageInternalAsync(TWrite msg, WriteFlags writeFlags)
{
byte[] payload = UnsafeSerialize(msg);
lock (myLock)
{
GrpcPreconditions.CheckState(started);
var earlyResult = CheckSendAllowedOrEarlyResult();
if (earlyResult != null)
{
return earlyResult;
}
call.StartSendMessage(SendCompletionCallback, payload, writeFlags, !initialMetadataSent);
initialMetadataSent = true;
streamingWritesCounter++;
streamingWriteTcs = new TaskCompletionSource<object>();
return streamingWriteTcs.Task;
}
}
/// <summary>
/// Initiates reading a message. Only one read operation can be active at a time.
/// </summary>
protected Task<TRead> ReadMessageInternalAsync()
{
lock (myLock)
{
GrpcPreconditions.CheckState(started);
if (readingDone)
{
// the last read that returns null or throws an exception is idempotent
// and maintains its state.
GrpcPreconditions.CheckState(streamingReadTcs != null, "Call does not support streaming reads.");
return streamingReadTcs.Task;
}
GrpcPreconditions.CheckState(streamingReadTcs == null, "Only one read can be pending at a time");
GrpcPreconditions.CheckState(!disposed);
call.StartReceiveMessage(ReceivedMessageCallback);
streamingReadTcs = new TaskCompletionSource<TRead>();
return streamingReadTcs.Task;
}
}
/// <summary>
/// If there are no more pending actions and no new actions can be started, releases
/// the underlying native resources.
/// </summary>
protected bool ReleaseResourcesIfPossible()
{
if (!disposed && call != null)
{
bool noMoreSendCompletions = streamingWriteTcs == null && (halfcloseRequested || cancelRequested || finished);
if (noMoreSendCompletions && readingDone && finished)
{
ReleaseResources();
return true;
}
}
return false;
}
protected abstract bool IsClient
{
get;
}
/// <summary>
/// Returns an exception to throw for a failed send operation.
/// It is only allowed to call this method for a call that has already finished.
/// </summary>
protected abstract Exception GetRpcExceptionClientOnly();
protected void ReleaseResources()
{
if (call != null)
{
call.Dispose();
}
disposed = true;
OnAfterReleaseResourcesLocked();
}
protected virtual void OnAfterReleaseResourcesLocked()
{
}
protected virtual void OnAfterReleaseResourcesUnlocked()
{
}
/// <summary>
/// Checks if sending is allowed and possibly returns a Task that allows short-circuiting the send
/// logic by directly returning the write operation result task. Normally, null is returned.
/// </summary>
protected abstract Task CheckSendAllowedOrEarlyResult();
protected byte[] UnsafeSerialize(TWrite msg)
{
DefaultSerializationContext context = null;
try
{
context = DefaultSerializationContext.GetInitializedThreadLocal();
serializer(msg, context);
return context.GetPayload();
}
finally
{
context?.Reset();
}
}
protected Exception TryDeserialize(IBufferReader reader, out TRead msg)
{
DefaultDeserializationContext context = null;
try
{
context = DefaultDeserializationContext.GetInitializedThreadLocal(reader);
msg = deserializer(context);
return null;
}
catch (Exception e)
{
msg = default(TRead);
return e;
}
finally
{
context?.Reset();
}
}
/// <summary>
/// Handles send completion (including SendCloseFromClient).
/// </summary>
protected void HandleSendFinished(bool success)
{
bool delayCompletion = false;
TaskCompletionSource<object> origTcs = null;
bool releasedResources;
lock (myLock)
{
if (!success && !finished && IsClient) {
// We should be setting this only once per call, following writes will be short circuited
// because they cannot start until the entire call finishes.
GrpcPreconditions.CheckState(!isStreamingWriteCompletionDelayed);
// leave streamingWriteTcs set, it will be completed once call finished.
isStreamingWriteCompletionDelayed = true;
delayCompletion = true;
}
else
{
origTcs = streamingWriteTcs;
streamingWriteTcs = null;
}
releasedResources = ReleaseResourcesIfPossible();
}
if (releasedResources)
{
OnAfterReleaseResourcesUnlocked();
}
if (!success)
{
if (!delayCompletion)
{
if (IsClient)
{
GrpcPreconditions.CheckState(finished); // implied by !success && !delayCompletion && IsClient
origTcs.SetException(GetRpcExceptionClientOnly());
}
else
{
origTcs.SetException (new IOException("Error sending from server."));
}
}
// if delayCompletion == true, postpone SetException until call finishes.
}
else
{
origTcs.SetResult(null);
}
}
/// <summary>
/// Handles send status from server completion.
/// </summary>
protected void HandleSendStatusFromServerFinished(bool success)
{
bool releasedResources;
lock (myLock)
{
releasedResources = ReleaseResourcesIfPossible();
}
if (releasedResources)
{
OnAfterReleaseResourcesUnlocked();
}
if (!success)
{
sendStatusFromServerTcs.SetException(new IOException("Error sending status from server."));
}
else
{
sendStatusFromServerTcs.SetResult(null);
}
}
/// <summary>
/// Handles streaming read completion.
/// </summary>
protected void HandleReadFinished(bool success, IBufferReader receivedMessageReader)
{
// if success == false, the message reader will report null payload. It that case we will
// treat this completion as the last read an rely on C core to handle the failed
// read (e.g. deliver approriate statusCode on the clientside).
TRead msg = default(TRead);
var deserializeException = (success && receivedMessageReader.TotalLength.HasValue) ? TryDeserialize(receivedMessageReader, out msg) : null;
TaskCompletionSource<TRead> origTcs = null;
bool releasedResources;
lock (myLock)
{
origTcs = streamingReadTcs;
if (!receivedMessageReader.TotalLength.HasValue)
{
// This was the last read.
readingDone = true;
}
if (deserializeException != null && IsClient)
{
readingDone = true;
// TODO(jtattermusch): it might be too late to set the status
CancelWithStatus(DeserializeResponseFailureStatus);
}
if (!readingDone)
{
streamingReadTcs = null;
}
releasedResources = ReleaseResourcesIfPossible();
}
if (releasedResources)
{
OnAfterReleaseResourcesUnlocked();
}
if (deserializeException != null && !IsClient)
{
origTcs.SetException(new IOException("Failed to deserialize request message.", deserializeException));
return;
}
origTcs.SetResult(msg);
}
protected ISendCompletionCallback SendCompletionCallback => this;
void ISendCompletionCallback.OnSendCompletion(bool success)
{
HandleSendFinished(success);
}
IReceivedMessageCallback ReceivedMessageCallback => this;
void IReceivedMessageCallback.OnReceivedMessage(bool success, IBufferReader receivedMessageReader)
{
HandleReadFinished(success, receivedMessageReader);
}
internal CancellationTokenRegistration RegisterCancellationCallbackForToken(CancellationToken cancellationToken)
{
if (cancellationToken.CanBeCanceled) return cancellationToken.Register(CancelCallFromToken, this);
return default(CancellationTokenRegistration);
}
private static readonly Action<object> CancelCallFromToken = state => ((AsyncCallBase<TWrite, TRead>)state).Cancel();
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using Microsoft.Build.Construction;
using Microsoft.Build.Evaluation;
using Mono.Cecil;
using Xamarin.Android.Tools;
namespace Embeddinator
{
/// <summary>
/// Contains everything MSBuild-related for Xamarin.Android
/// </summary>
static class XamarinAndroidBuild
{
public const string IntermediateDir = "obj";
public const string ResourcePaths = "resourcepaths.cache";
const string LibraryProjectDir = "lp";
const string ImportsDirectory = "jl";
const string LinkMode = "SdkOnly";
static ProjectRootElement CreateProject()
{
var monoDroidPath = XamarinAndroid.Path;
var msBuildPath = Path.Combine(monoDroidPath, "lib", "xbuild", "Xamarin", "Android");
if (!msBuildPath.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.OrdinalIgnoreCase))
msBuildPath = msBuildPath + Path.DirectorySeparatorChar;
var project = ProjectRootElement.Create();
project.AddProperty("Configuration", "Release");
project.AddProperty("Platform", "AnyCPU");
project.AddProperty("PlatformTarget", "AnyCPU");
project.AddProperty("OutputPath", "bin\\Release");
project.AddProperty("TargetFrameworkDirectory", string.Join(";", XamarinAndroid.TargetFrameworkDirectories));
project.AddImport(ProjectCollection.Escape(Path.Combine(msBuildPath, "Xamarin.Android.CSharp.targets")));
return project;
}
static void ResolveAssemblies(ProjectTargetElement target, List<IKVM.Reflection.Assembly> assemblies)
{
var resolveAssemblies = target.AddTask("ResolveAssemblies");
var assemblyPaths = assemblies.Select(a => a.Location).ToList();
//NOTE: [Export] requires Mono.Android.Export.dll
assemblyPaths.Add(XamarinAndroid.FindAssembly("Mono.Android.Export.dll"));
resolveAssemblies.SetParameter("Assemblies", string.Join(";", assemblyPaths));
resolveAssemblies.SetParameter("LinkMode", LinkMode);
resolveAssemblies.SetParameter("ReferenceAssembliesDirectory", "$(TargetFrameworkDirectory)");
resolveAssemblies.AddOutputItem("ResolvedAssemblies", "ResolvedAssemblies");
resolveAssemblies.AddOutputItem("ResolvedUserAssemblies", "ResolvedUserAssemblies");
resolveAssemblies.AddOutputItem("ResolvedFrameworkAssemblies", "ResolvedFrameworkAssemblies");
}
/// <summary>
/// Generates a Package.proj file for MSBuild to invoke
/// - Generates Resource.designer.dll for rewiring resource values from the final Java project
/// - Links .NET assemblies and places output into /android/assets/assemblies
/// - Extracts assets and resources from Android library projects into /obj/
/// - Copies assets and resources into AAR
/// - Invokes aapt to generate R.txt
/// - One day I would like to get rid of the temp files, but I could not get the MSBuild APIs to work in-process
/// </summary>
public static string GeneratePackageProject(List<IKVM.Reflection.Assembly> assemblies, Options options)
{
var mainAssembly = assemblies[0].Location;
var outputDirectory = Path.GetFullPath(options.OutputDir);
var assembliesDirectory = Path.Combine(outputDirectory, "android", "assets", "assemblies");
var androidDir = Path.Combine(outputDirectory, "android");
var assetsDir = Path.Combine(androidDir, "assets");
var resourceDir = Path.Combine(androidDir, "res");
var manifestPath = Path.Combine(androidDir, "AndroidManifest.xml");
var packageName = Generators.JavaGenerator.GetNativeLibPackageName(mainAssembly);
var project = CreateProject();
var target = project.AddTarget("Build");
//ResolveAssemblies Task
ResolveAssemblies(target, assemblies);
//LinkAssemblies Task
var linkAssemblies = target.AddTask("LinkAssemblies");
linkAssemblies.SetParameter("UseSharedRuntime", "False");
linkAssemblies.SetParameter("LinkMode", LinkMode);
linkAssemblies.SetParameter("LinkDescriptions", "@(LinkDescription)");
linkAssemblies.SetParameter("DumpDependencies", "True");
linkAssemblies.SetParameter("ResolvedAssemblies", "@(ResolvedAssemblies);" + Path.Combine(outputDirectory, "Resource.designer.dll"));
linkAssemblies.SetParameter("MainAssembly", mainAssembly);
linkAssemblies.SetParameter("OutputDirectory", assembliesDirectory);
//If not Debug, delete our PDB files
if (!options.Compilation.DebugMode)
{
var itemGroup = target.AddItemGroup();
itemGroup.AddItem("PdbFilesToDelete", Path.Combine(assembliesDirectory, "*.pdb"));
var delete = target.AddTask("Delete");
delete.SetParameter("Files", "@(PdbFilesToDelete)");
}
//Aapt Task to generate R.txt
var aapt = target.AddTask("Aapt");
aapt.Condition = $"Exists('{resourceDir}')";
aapt.SetParameter("ImportsDirectory", outputDirectory);
aapt.SetParameter("OutputImportDirectory", outputDirectory);
aapt.SetParameter("ManifestFiles", manifestPath);
aapt.SetParameter("ApplicationName", packageName);
aapt.SetParameter("JavaPlatformJarPath", Path.Combine(XamarinAndroid.PlatformDirectory, "android.jar"));
aapt.SetParameter("JavaDesignerOutputDirectory", outputDirectory);
aapt.SetParameter("AssetDirectory", assetsDir);
aapt.SetParameter("ResourceDirectory", resourceDir);
aapt.SetParameter("ToolPath", XamarinAndroid.AndroidSdk.GetBuildToolsPaths().First());
aapt.SetParameter("ToolExe", "aapt");
aapt.SetParameter("ApiLevel", XamarinAndroid.TargetSdkVersion.ToString());
aapt.SetParameter("ExtraArgs", "--output-text-symbols " + androidDir);
//There is an extra /manifest/AndroidManifest.xml file created
var removeDir = target.AddTask("RemoveDir");
removeDir.SetParameter("Directories", Path.Combine(androidDir, "manifest"));
//NOTE: might avoid the temp file later
var projectFile = Path.Combine(outputDirectory, "Package.proj");
project.Save(projectFile);
return projectFile;
}
/// <summary>
/// Generates AndroidManifest.xml
/// </summary>
public static void GenerateAndroidManifest(IList<IKVM.Reflection.Assembly> assemblies, string path, bool includeProvider = true)
{
var mainAssembly = assemblies[0].Location;
var packageName = Generators.JavaGenerator.GetNativeLibPackageName(mainAssembly);
var className = Generators.JavaNative.GetNativeLibClassName(mainAssembly);
string provider = string.Empty;
if (includeProvider)
{
provider = $"<provider android:name=\"mono.embeddinator.AndroidRuntimeProvider\" android:exported=\"false\" android:initOrder=\"{int.MaxValue}\" android:authorities=\"${{applicationId}}.mono.embeddinator.AndroidRuntimeProvider.__mono_init__\" />";
}
File.WriteAllText(path,
$@"<?xml version=""1.0"" encoding=""utf-8""?>
<manifest xmlns:android=""http://schemas.android.com/apk/res/android"" package=""{packageName}"">
<uses-sdk android:minSdkVersion=""{XamarinAndroid.MinSdkVersion}"" android:targetSdkVersion=""{XamarinAndroid.TargetSdkVersion}"" />
<application>
<meta-data android:name=""mono.embeddinator.classname"" android:value=""{packageName}.{className}"" />
{provider}
</application>
</manifest>");
}
/// <summary>
/// Generates a GenerateJavaStubs.proj file for MSBuild to invoke
/// - Generates Java source code for each C# class that subclasses Java.Lang.Object
/// - Generates AndroidManifest.xml
/// - One day I would like to get rid of the temp files, but I could not get the MSBuild APIs to work in-process
/// </summary>
public static string GenerateJavaStubsProject(List<IKVM.Reflection.Assembly> assemblies, string outputDirectory)
{
var mainAssembly = assemblies[0].Location;
outputDirectory = Path.GetFullPath(outputDirectory);
var intermediateDir = Path.Combine(outputDirectory, IntermediateDir);
var androidDir = Path.Combine(outputDirectory, "android");
var javaSourceDir = Path.Combine(outputDirectory, "src");
var assetsDir = Path.Combine(androidDir, "assets");
var resourceDir = Path.Combine(androidDir, "res");
var manifestPath = Path.Combine(androidDir, "AndroidManifest.xml");
var packageName = Generators.JavaGenerator.GetNativeLibPackageName(mainAssembly);
if (!Directory.Exists(androidDir))
Directory.CreateDirectory(androidDir);
//AndroidManifest.xml template
GenerateAndroidManifest(assemblies, manifestPath, false);
var project = CreateProject();
var target = project.AddTarget("Build");
//ResolveAssemblies Task
ResolveAssemblies(target, assemblies);
//GenerateJavaStubs Task
var generateJavaStubs = target.AddTask("GenerateJavaStubs");
generateJavaStubs.SetParameter("ResolvedAssemblies", "@(ResolvedAssemblies)");
generateJavaStubs.SetParameter("ResolvedUserAssemblies", "@(ResolvedUserAssemblies)");
generateJavaStubs.SetParameter("ManifestTemplate", manifestPath);
generateJavaStubs.SetParameter("MergedAndroidManifestOutput", manifestPath);
generateJavaStubs.SetParameter("AndroidSdkPlatform", XamarinAndroid.TargetSdkVersion.ToString()); //TODO: should be an option
generateJavaStubs.SetParameter("AndroidSdkDir", XamarinAndroid.AndroidSdk.AndroidSdkPath);
generateJavaStubs.SetParameter("OutputDirectory", outputDirectory);
generateJavaStubs.SetParameter("ResourceDirectory", "$(MonoAndroidResDirIntermediate)");
generateJavaStubs.SetParameter("AcwMapFile", "$(MonoAndroidIntermediate)acw-map.txt");
//ResolveLibraryProjectImports Task, extracts Android resources
var resolveLibraryProject = target.AddTask("ResolveLibraryProjectImports");
resolveLibraryProject.SetParameter("Assemblies", "@(ResolvedUserAssemblies)");
resolveLibraryProject.SetParameter("AssemblyIdentityMapFile", Path.Combine(intermediateDir, LibraryProjectDir, "map.cache"));
resolveLibraryProject.SetParameter("CacheFile", Path.Combine(intermediateDir, "libraryprojectimports.cache"));
resolveLibraryProject.SetParameter("UseShortFileNames", "False");
resolveLibraryProject.SetParameter("ImportsDirectory", ImportsDirectory);
resolveLibraryProject.SetParameter("OutputDirectory", intermediateDir);
resolveLibraryProject.SetParameter("OutputImportDirectory", Path.Combine(intermediateDir, LibraryProjectDir));
resolveLibraryProject.AddOutputItem("ResolvedAssetDirectories", "ResolvedAssetDirectories");
resolveLibraryProject.AddOutputItem("ResolvedResourceDirectories", "ResolvedResourceDirectories");
//GetAdditionalResourcesFromAssemblies Task, for JavaLibraryReferenceAttribute, etc.
var getAdditionalResources = target.AddTask("GetAdditionalResourcesFromAssemblies");
getAdditionalResources.SetParameter("AndroidSdkDirectory", XamarinAndroid.AndroidSdk.AndroidSdkPath);
getAdditionalResources.SetParameter("AndroidNdkDirectory", XamarinAndroid.AndroidSdk.AndroidNdkPath);
getAdditionalResources.SetParameter("Assemblies", "@(ResolvedUserAssemblies)");
getAdditionalResources.SetParameter("CacheFile", Path.Combine(intermediateDir, ResourcePaths));
getAdditionalResources.SetParameter("DesignTimeBuild", "False");
//Create ItemGroup of Android files
var androidResources = target.AddItemGroup();
foreach (var assembly in assemblies)
{
var assemblyName = assembly.GetName().Name;
androidResources.AddItem("AndroidAsset", Path.Combine(intermediateDir, LibraryProjectDir, assemblyName, ImportsDirectory, "assets", "**", "*"));
androidResources.AddItem("AndroidJavaSource", Path.Combine(intermediateDir, LibraryProjectDir, assemblyName, ImportsDirectory, "java", "**", "*.java"));
androidResources.AddItem("AndroidResource", Path.Combine(intermediateDir, LibraryProjectDir, assemblyName, ImportsDirectory, "res", "**", "*"));
}
//Copy Task, to copy AndroidAsset files
var copy = target.AddTask("Copy");
copy.SetParameter("SourceFiles", "@(AndroidAsset)");
copy.SetParameter("DestinationFiles", $"@(AndroidAsset->'{assetsDir + Path.DirectorySeparatorChar}%(RecursiveDir)%(Filename)%(Extension)')");
//Copy Task, to copy AndroidResource files
copy = target.AddTask("Copy");
copy.SetParameter("SourceFiles", "@(AndroidResource)");
copy.SetParameter("DestinationFiles", $"@(AndroidResource->'{resourceDir + Path.DirectorySeparatorChar}%(RecursiveDir)%(Filename)%(Extension)')");
//Copy Task, to copy AndroidJavaSource files
copy = target.AddTask("Copy");
copy.SetParameter("SourceFiles", "@(AndroidJavaSource)");
copy.SetParameter("DestinationFiles", $"@(AndroidJavaSource->'{javaSourceDir + Path.DirectorySeparatorChar}%(RecursiveDir)%(Filename)%(Extension)')");
//XmlPoke to fix up AndroidManifest
var xmlPoke = target.AddTask("XmlPoke");
xmlPoke.SetParameter("XmlInputPath", manifestPath);
xmlPoke.SetParameter("Query", "/manifest/@package");
xmlPoke.SetParameter("Value", packageName);
//android:name
xmlPoke = target.AddTask("XmlPoke");
xmlPoke.SetParameter("XmlInputPath", manifestPath);
xmlPoke.SetParameter("Namespaces", "<Namespace Prefix='android' Uri='http://schemas.android.com/apk/res/android' />");
xmlPoke.SetParameter("Query", "/manifest/application/provider/@android:name");
xmlPoke.SetParameter("Value", "mono.embeddinator.AndroidRuntimeProvider");
//android:authorities
xmlPoke = target.AddTask("XmlPoke");
xmlPoke.SetParameter("XmlInputPath", manifestPath);
xmlPoke.SetParameter("Namespaces", "<Namespace Prefix='android' Uri='http://schemas.android.com/apk/res/android' />");
xmlPoke.SetParameter("Query", "/manifest/application/provider/@android:authorities");
xmlPoke.SetParameter("Value", "${applicationId}.mono.embeddinator.AndroidRuntimeProvider.__mono_init__");
//NOTE: might avoid the temp file later
var projectFile = Path.Combine(outputDirectory, "GenerateJavaStubs.proj");
project.Save(projectFile);
return projectFile;
}
/// <summary>
/// For each linked assembly:
/// - We need to extract __AndroidNativeLibraries__.zip into the AAR directory
/// - We need to strip __AndroidLibraryProjects__.zip and __AndroidNativeLibraries__.zip
/// </summary>
public static void ProcessAssemblies(string outputDirectory)
{
var assembliesDir = Path.Combine(outputDirectory, "android", "assets", "assemblies");
var jniDir = Path.Combine(outputDirectory, "android", "jni");
var resolver = new DefaultAssemblyResolver();
resolver.AddSearchDirectory(assembliesDir);
foreach (var assemblyFile in Directory.GetFiles(assembliesDir, "*.dll"))
{
var assemblyModified = false;
var assembly = AssemblyDefinition.ReadAssembly(assemblyFile, new ReaderParameters { AssemblyResolver = resolver });
foreach (var module in assembly.Modules)
{
//NOTE: ToArray() so foreach does not get InvalidOperationException
foreach (EmbeddedResource resource in module.Resources.ToArray())
{
if (resource.Name == "__AndroidNativeLibraries__.zip")
{
var data = resource.GetResourceData();
using (var resourceStream = new MemoryStream(data))
{
using (var zip = new ZipArchive(resourceStream))
{
foreach (var entry in zip.Entries)
{
//Skip directories
if (string.IsNullOrEmpty(entry.Name))
continue;
var fileName = entry.Name;
var abi = Path.GetFileName(Path.GetDirectoryName(entry.FullName));
using (var zipStream = entry.Open())
using (var fileStream = File.Create(Path.Combine(jniDir, abi, fileName)))
{
zipStream.CopyTo(fileStream);
}
}
}
}
module.Resources.Remove(resource);
assemblyModified = true;
}
else if (resource.Name == "__AndroidLibraryProjects__.zip")
{
module.Resources.Remove(resource);
assemblyModified = true;
}
}
}
//Only write the assembly if we removed a resource
if (assemblyModified)
{
assembly.Write(assemblyFile);
}
}
}
/// <summary>
/// Takes an existing JAR file and extracts it to be included withing a single JAR/AAR
/// </summary>
public static void ExtractJar(string jar, string classesDir, Func<ZipArchiveEntry, bool> filter = null)
{
using (var stream = File.OpenRead(jar))
using (var zip = new ZipArchive(stream))
{
foreach (var entry in zip.Entries)
{
//Skip META-INF
if (entry.FullName.StartsWith("META-INF", StringComparison.Ordinal))
continue;
//Filter to optionally skip
if (filter != null && !filter(entry))
continue;
var entryPath = Path.Combine(classesDir, entry.FullName);
if (string.IsNullOrEmpty(entry.Name))
{
if (!Directory.Exists(entryPath))
Directory.CreateDirectory(entryPath);
}
else
{
//NOTE: not all JAR files have directory entries such as FormsViewGroup.jar
var directoryPath = Path.GetDirectoryName(entryPath);
if (!Directory.Exists(directoryPath))
Directory.CreateDirectory(directoryPath);
using (var zipEntryStream = entry.Open())
using (var fileStream = File.Create(entryPath))
{
zipEntryStream.CopyTo(fileStream);
}
}
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Nest;
using Purchasing.Core.Domain;
using Purchasing.Core.Queries;
namespace Purchasing.Core.Services
{
public class ElasticSearchService : ISearchService
{
private readonly IIndexService _indexService;
private ElasticClient _client;
private const int MaxSeachResults = 1000;
public ElasticSearchService(IIndexService indexService)
{
_indexService = indexService;
_client = indexService.GetIndexClient();
}
public IList<SearchResults.OrderResult> SearchOrders(string searchTerm, int[] allowedIds)
{
if (allowedIds.Length == 0) // no results if you aren't allowed to see anything
{
return new List<SearchResults.OrderResult>();
}
var index = IndexHelper.GetIndexName(Indexes.OrderHistory);
var results = _client.Search<OrderHistory>(
s =>
s.Index(index)
.Query(
q => q.QueryString(qs => qs.Query(searchTerm))
)
.PostFilter(f => f.ConstantScore(c => c.Filter(x => x.Terms(t => t.Field(q => q.OrderId).Terms(allowedIds)))))
.Sort(sort => sort.Descending(d => d.LastActionDate))
.Size(MaxSeachResults));
return results.Hits.Select(h => AutoMapper.Mapper.Map<SearchResults.OrderResult>(h.Source)).ToList();
}
public IList<SearchResults.LineResult> SearchLineItems(string searchTerm, int[] allowedIds)
{
if (allowedIds.Length == 0) // no results if you aren't allowed to see anything
{
return new List<SearchResults.LineResult>();
}
var index = IndexHelper.GetIndexName(Indexes.LineItems);
var results = _client.Search<SearchResults.LineResult>(
s =>
s.Index(index)
.Query(
q => q.QueryString(qs => qs.Query(searchTerm))
)
.PostFilter(f => f.ConstantScore(c => c.Filter(x => x.Terms(t => t.Field(q => q.OrderId).Terms(allowedIds)))))
.Sort(sort => sort.Descending(d => d.OrderId))
.Size(MaxSeachResults));
return results.Hits.Select(h => h.Source).ToList();
}
public IList<SearchResults.CustomFieldResult> SearchCustomFieldAnswers(string searchTerm, int[] allowedIds)
{
if (allowedIds.Length == 0) // no results if you aren't allowed to see anything
{
return new List<SearchResults.CustomFieldResult>();
}
var index = IndexHelper.GetIndexName(Indexes.CustomAnswers);
var results = _client.Search<SearchResults.CustomFieldResult>(
s =>
s.Index(index)
.Query(
q => q.QueryString(qs => qs.Query(searchTerm))
)
.PostFilter(f => f.ConstantScore(c => c.Filter(x => x.Terms(t => t.Field(q => q.OrderId).Terms(allowedIds)))))
.Sort(sort => sort.Descending(d => d.OrderId))
.Size(MaxSeachResults));
return results.Hits.Select(h => h.Source).ToList();
}
public IList<SearchResults.CommentResult> SearchComments(string searchTerm, int[] allowedIds)
{
if (allowedIds.Length == 0) // no results if you aren't allowed to see anything
{
return new List<SearchResults.CommentResult>();
}
var index = IndexHelper.GetIndexName(Indexes.Comments);
var results = _client.Search<SearchResults.CommentResult>(
s =>
s.Index(index)
.Query(
q => q.QueryString(qs => qs.Query(searchTerm))
)
.PostFilter(f=>f.ConstantScore(c=>c.Filter(x=>x.Terms(t=>t.Field(q=>q.OrderId).Terms(allowedIds)))))
.Sort(sort => sort.Descending(d => d.DateCreated))
.Size(MaxSeachResults));
return results.Hits.Select(h => h.Source).ToList();
}
public IList<SearchResults.CommentResult> GetLatestComments(int count, int[] allowedIds)
{
if (allowedIds.Length == 0) // no results if you aren't allowed to see anything
{
return new List<SearchResults.CommentResult>();
}
var index = IndexHelper.GetIndexName(Indexes.Comments);
var results = _client.Search<SearchResults.CommentResult>(
s =>
s.Index(index)
.PostFilter(f => f.ConstantScore(c => c.Filter(x => x.Terms(t => t.Field(q => q.OrderId).Terms(allowedIds)))))
.Sort(sort => sort.Descending(d => d.DateCreated))
.Size(count));
return results.Hits.Select(h => h.Source).ToList();
}
public IList<IdAndName> SearchCommodities(string searchTerm)
{
var index = IndexHelper.GetIndexName(Indexes.Commodities);
var results = _client.Search<Commodity>(
s => s.Index(index).Query(q => q.QueryString(qs => qs.Query(searchTerm))));
return results.Hits.Select(h => new IdAndName(h.Source.Id, h.Source.Name)).ToList();
}
public IList<IdAndName> SearchVendors(string searchTerm)
{
var index = IndexHelper.GetIndexName(Indexes.Vendors);
var results = _client.Search<Vendor>(
s => s.Index(index).Query(q => q.QueryString(qs => qs.Query(searchTerm))));
return results.Hits.Select(h => new IdAndName(h.Source.Id, h.Source.Name)).ToList();
}
public IList<IdAndName> SearchAccounts(string searchTerm)
{
var index = IndexHelper.GetIndexName(Indexes.Accounts);
var results = _client.Search<Account>(
s => s.Index(index).Query(q => q.QueryString(qs => qs.Query(searchTerm))));
return results.Hits.Select(h => new IdAndName(h.Source.Id, h.Source.Name)).ToList();
}
public IList<IdAndName> SearchBuildings(string searchTerm)
{
var index = IndexHelper.GetIndexName(Indexes.Buildings);
var results = _client.Search<Building>(
s => s.Index(index).Query(q => q.QueryString(qs => qs.Query(searchTerm))));
return results.Hits.Select(h => new IdAndName(h.Source.Id, h.Source.BuildingName)).ToList();
}
public IList<OrderHistory> GetOrdersByWorkgroups(IEnumerable<Workgroup> workgroups, DateTime createdAfter, DateTime createdBefore, int size = 1000)
{
var index = IndexHelper.GetIndexName(Indexes.OrderHistory);
var workgroupIds = workgroups.Select(w => w.Id).ToArray();
var results = _client.Search<OrderHistory>(
s =>
s.Index(index)
.Size(size)
.Query(f => f.DateRange(r => r.Field(o => o.DateCreated).GreaterThan(createdAfter).LessThan(createdBefore))
&& f.Terms(o => o.Field(field => field.WorkgroupId).Terms(workgroupIds)))
);
return results.Hits.Select(h => h.Source).ToList();
}
public OrderTrackingAggregation GetOrderTrackingEntities(IEnumerable<Workgroup> workgroups,
DateTime createdAfter, DateTime createBefore, int size = 1000)
{
var index = IndexHelper.GetIndexName(Indexes.OrderTracking);
var workgroupIds = workgroups.Select(w => w.Id).ToArray();
var results = _client.Search<OrderTrackingEntity>(
s => s.Index(index)
.Size(size)
.Query(f => f.DateRange(r => r.Field(o => o.OrderCreated).GreaterThan(createdAfter).LessThan(createBefore))
&& f.Term(x => x.IsComplete, true)
&& f.Terms(o => o.Field(field => field.WorkgroupId).Terms(workgroupIds)))
.Aggregations(
a =>
a.Average("AverageTimeToCompletion", avg => avg.Field(x => x.MinutesToCompletion))
.Average("AverageTimeToRoleComplete", avg => avg.Field(x => x.MinutesToApprove))
.Average("AverageTimeToAccountManagers",
avg => avg.Field(x => x.MinutesToAccountManagerComplete))
.Average("AverageTimeToPurchaser", avg => avg.Field(x => x.MinutesToPurchaserComplete)))
);
return new OrderTrackingAggregation
{
OrderTrackingEntities = results.Hits.Select(h => h.Source).ToList(),
AverageTimeToAccountManagers = results.Aggregations.Average("AverageTimeToAccountManagers").Value,
AverageTimeToApprover = results.Aggregations.Average("AverageTimeToRoleComplete").Value,
AverageTimeToCompletion = results.Aggregations.Average("AverageTimeToCompletion").Value,
AverageTimeToPurchaser = results.Aggregations.Average("AverageTimeToPurchaser").Value
};
}
public OrderTrackingAggregationByRole GetOrderTrackingEntitiesByRole(IEnumerable<Workgroup> workgroups,
DateTime createdAfter, DateTime createBefore, string role, int size)
{
var index = IndexHelper.GetIndexName(Indexes.OrderTracking);
var workgroupIds = workgroups.Select(w => w.Id).ToArray();
string roleNames = "purchaserId";
string timeField = "minutesToPurchaserComplete";
if (role == "Approver")
{
roleNames = "approverId";
timeField = "minutesToApprove";
}
if (role == "AccountManager")
{
roleNames = "accountManagerId";
timeField = "minutesToAccountManagerComplete";
}
// get the .keyword version of the index, for aggregates (since we aren't full text searching against the field)
roleNames = roleNames + ".keyword";
var results = _client.Search<OrderTrackingEntity>(
s => s.Index(index)
.Size(size)
.Query(f => f.DateRange(r => r.Field(o => o.OrderCreated).GreaterThan(createdAfter).LessThan(createBefore))
&& f.Term(x => x.Status, "complete")
&& f.Terms(o => o.Field(field => field.WorkgroupId).Terms(workgroupIds)))
.Aggregations(
a =>
a.Terms("RolePercentiles", t => t.Field(roleNames)
.Aggregations(b=> b.Percentiles("PercentileTimes", p=> p.Field(timeField)
.Percents(new double[] {0,25,50,75,100})))
)
.Average("AverageTimeToRoleComplete", avg => avg.Field(timeField)))
);
var names = results.Aggregations.Terms("RolePercentiles").Buckets.Select(n => n.Key + "; n=" + n.DocCount.ToString()).ToArray();
var percentilesInRole =
results.Aggregations.Terms("RolePercentiles")
.Buckets.Select(user => user.PercentilesBucket("PercentileTimes"))
.Select(
uservalue => uservalue.Items.OrderBy(o => o.Percentile).Select(a => (a.Value.HasValue ? a.Value.Value : 0) / 1440).ToArray() // converted to days to help with scale
)
.ToList();
return new OrderTrackingAggregationByRole
{
OrderTrackingEntities = results.Hits.Select(h => h.Source).ToList(),
AverageTimeToRoleComplete = results.Aggregations.Average("AverageTimeToRoleComplete").Value / 1440,
NamesInRole = names,
PercentilesForRole = percentilesInRole
};
}
}
}
| |
// 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.Collections {
using System;
using System.Diagnostics.Contracts;
// Useful base class for typed read/write collections where items derive from object
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class CollectionBase : IList {
ArrayList list;
protected CollectionBase() {
list = new ArrayList();
}
protected CollectionBase(int capacity) {
list = new ArrayList(capacity);
}
protected ArrayList InnerList {
get {
if (list == null)
list = new ArrayList();
return list;
}
}
protected IList List {
get { return (IList)this; }
}
[System.Runtime.InteropServices.ComVisible(false)]
public int Capacity {
get {
return InnerList.Capacity;
}
set {
InnerList.Capacity = value;
}
}
public int Count {
get {
return list == null ? 0 : list.Count;
}
}
public void Clear() {
OnClear();
InnerList.Clear();
OnClearComplete();
}
public void RemoveAt(int index) {
if (index < 0 || index >= Count)
throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
Contract.EndContractBlock();
Object temp = InnerList[index];
OnValidate(temp);
OnRemove(index, temp);
InnerList.RemoveAt(index);
try {
OnRemoveComplete(index, temp);
}
catch {
InnerList.Insert(index, temp);
throw;
}
}
bool IList.IsReadOnly {
get { return InnerList.IsReadOnly; }
}
bool IList.IsFixedSize {
get { return InnerList.IsFixedSize; }
}
bool ICollection.IsSynchronized {
get { return InnerList.IsSynchronized; }
}
Object ICollection.SyncRoot {
get { return InnerList.SyncRoot; }
}
void ICollection.CopyTo(Array array, int index) {
InnerList.CopyTo(array, index);
}
Object IList.this[int index] {
get {
if (index < 0 || index >= Count)
throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
Contract.EndContractBlock();
return InnerList[index];
}
set {
if (index < 0 || index >= Count)
throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
Contract.EndContractBlock();
OnValidate(value);
Object temp = InnerList[index];
OnSet(index, temp, value);
InnerList[index] = value;
try {
OnSetComplete(index, temp, value);
}
catch {
InnerList[index] = temp;
throw;
}
}
}
bool IList.Contains(Object value) {
return InnerList.Contains(value);
}
int IList.Add(Object value) {
OnValidate(value);
OnInsert(InnerList.Count, value);
int index = InnerList.Add(value);
try {
OnInsertComplete(index, value);
}
catch {
InnerList.RemoveAt(index);
throw;
}
return index;
}
void IList.Remove(Object value) {
OnValidate(value);
int index = InnerList.IndexOf(value);
if (index < 0) throw new ArgumentException(Environment.GetResourceString("Arg_RemoveArgNotFound"));
OnRemove(index, value);
InnerList.RemoveAt(index);
try{
OnRemoveComplete(index, value);
}
catch {
InnerList.Insert(index, value);
throw;
}
}
int IList.IndexOf(Object value) {
return InnerList.IndexOf(value);
}
void IList.Insert(int index, Object value) {
if (index < 0 || index > Count)
throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
Contract.EndContractBlock();
OnValidate(value);
OnInsert(index, value);
InnerList.Insert(index, value);
try {
OnInsertComplete(index, value);
}
catch {
InnerList.RemoveAt(index);
throw;
}
}
public IEnumerator GetEnumerator() {
return InnerList.GetEnumerator();
}
protected virtual void OnSet(int index, Object oldValue, Object newValue) {
}
protected virtual void OnInsert(int index, Object value) {
}
protected virtual void OnClear() {
}
protected virtual void OnRemove(int index, Object value) {
}
protected virtual void OnValidate(Object value) {
if (value == null) throw new ArgumentNullException("value");
Contract.EndContractBlock();
}
protected virtual void OnSetComplete(int index, Object oldValue, Object newValue) {
}
protected virtual void OnInsertComplete(int index, Object value) {
}
protected virtual void OnClearComplete() {
}
protected virtual void OnRemoveComplete(int index, Object value) {
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace SimpleBackgroundUploadWebAPI.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Channels
{
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Runtime;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Diagnostics;
using System.ServiceModel.Dispatcher;
using System.Threading;
using System.Xml;
public abstract class Message : IDisposable
{
MessageState state;
SeekableMessageNavigator messageNavigator;
internal const int InitialBufferSize = 1024;
public abstract MessageHeaders Headers { get; } // must never return null
protected bool IsDisposed
{
get { return state == MessageState.Closed; }
}
public virtual bool IsFault
{
get
{
if (IsDisposed)
#pragma warning suppress 56503 // [....], Invalid State after dispose
throw TraceUtility.ThrowHelperError(CreateMessageDisposedException(), this);
return false;
}
}
public virtual bool IsEmpty
{
get
{
if (IsDisposed)
#pragma warning suppress 56503 // [....], Invalid State after dispose
throw TraceUtility.ThrowHelperError(CreateMessageDisposedException(), this);
return false;
}
}
public abstract MessageProperties Properties { get; }
public abstract MessageVersion Version { get; } // must never return null
internal virtual RecycledMessageState RecycledMessageState
{
get { return null; }
}
public MessageState State
{
get { return state; }
}
internal void BodyToString(XmlDictionaryWriter writer)
{
OnBodyToString(writer);
}
public void Close()
{
if (state != MessageState.Closed)
{
state = MessageState.Closed;
OnClose();
if (DiagnosticUtility.ShouldTraceVerbose)
{
TraceUtility.TraceEvent(TraceEventType.Verbose, TraceCode.MessageClosed,
SR.GetString(SR.TraceCodeMessageClosed), this);
}
}
else
{
if (DiagnosticUtility.ShouldTraceVerbose)
{
TraceUtility.TraceEvent(TraceEventType.Verbose, TraceCode.MessageClosedAgain,
SR.GetString(SR.TraceCodeMessageClosedAgain), this);
}
}
}
public MessageBuffer CreateBufferedCopy(int maxBufferSize)
{
if (maxBufferSize < 0)
throw TraceUtility.ThrowHelperError(new ArgumentOutOfRangeException("maxBufferSize", maxBufferSize,
SR.GetString(SR.ValueMustBeNonNegative)), this);
switch (state)
{
case MessageState.Created:
state = MessageState.Copied;
if (DiagnosticUtility.ShouldTraceVerbose)
{
TraceUtility.TraceEvent(TraceEventType.Verbose, TraceCode.MessageCopied,
SR.GetString(SR.TraceCodeMessageCopied), this, this);
}
break;
case MessageState.Closed:
throw TraceUtility.ThrowHelperError(CreateMessageDisposedException(), this);
case MessageState.Copied:
throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.MessageHasBeenCopied)), this);
case MessageState.Read:
throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.MessageHasBeenRead)), this);
case MessageState.Written:
throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.MessageHasBeenWritten)), this);
default:
Fx.Assert(SR.GetString(SR.InvalidMessageState));
throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.InvalidMessageState)), this);
}
return OnCreateBufferedCopy(maxBufferSize);
}
static Type GetObjectType(object value)
{
return (value == null) ? typeof(object) : value.GetType();
}
static public Message CreateMessage(MessageVersion version, string action, object body)
{
return CreateMessage(version, action, body, DataContractSerializerDefaults.CreateSerializer(GetObjectType(body), int.MaxValue/*maxItems*/));
}
static public Message CreateMessage(MessageVersion version, string action, object body, XmlObjectSerializer serializer)
{
if (version == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("version"));
if (serializer == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("serializer"));
return new BodyWriterMessage(version, action, new XmlObjectSerializerBodyWriter(body, serializer));
}
static public Message CreateMessage(MessageVersion version, string action, XmlReader body)
{
return CreateMessage(version, action, XmlDictionaryReader.CreateDictionaryReader(body));
}
static public Message CreateMessage(MessageVersion version, string action, XmlDictionaryReader body)
{
if (body == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("body");
if (version == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("version");
return CreateMessage(version, action, new XmlReaderBodyWriter(body, version.Envelope));
}
static public Message CreateMessage(MessageVersion version, string action, BodyWriter body)
{
if (version == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("version"));
if (body == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("body"));
return new BodyWriterMessage(version, action, body);
}
static internal Message CreateMessage(MessageVersion version, ActionHeader actionHeader, BodyWriter body)
{
if (version == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("version"));
if (body == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("body"));
return new BodyWriterMessage(version, actionHeader, body);
}
static public Message CreateMessage(MessageVersion version, string action)
{
if (version == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("version"));
return new BodyWriterMessage(version, action, EmptyBodyWriter.Value);
}
static internal Message CreateMessage(MessageVersion version, ActionHeader actionHeader)
{
if (version == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("version"));
return new BodyWriterMessage(version, actionHeader, EmptyBodyWriter.Value);
}
static public Message CreateMessage(XmlReader envelopeReader, int maxSizeOfHeaders, MessageVersion version)
{
return CreateMessage(XmlDictionaryReader.CreateDictionaryReader(envelopeReader), maxSizeOfHeaders, version);
}
static public Message CreateMessage(XmlDictionaryReader envelopeReader, int maxSizeOfHeaders, MessageVersion version)
{
if (envelopeReader == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("envelopeReader"));
if (version == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("version"));
Message message = new StreamedMessage(envelopeReader, maxSizeOfHeaders, version);
return message;
}
static public Message CreateMessage(MessageVersion version, FaultCode faultCode, string reason, string action)
{
if (version == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("version"));
if (faultCode == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("faultCode"));
if (reason == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("reason"));
return CreateMessage(version, MessageFault.CreateFault(faultCode, reason), action);
}
static public Message CreateMessage(MessageVersion version, FaultCode faultCode, string reason, object detail, string action)
{
if (version == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("version"));
if (faultCode == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("faultCode"));
if (reason == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("reason"));
return CreateMessage(version, MessageFault.CreateFault(faultCode, new FaultReason(reason), detail), action);
}
static public Message CreateMessage(MessageVersion version, MessageFault fault, string action)
{
if (fault == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("fault"));
if (version == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("version"));
return new BodyWriterMessage(version, action, new FaultBodyWriter(fault, version.Envelope));
}
internal Exception CreateMessageDisposedException()
{
return new ObjectDisposedException("", SR.GetString(SR.MessageClosed));
}
void IDisposable.Dispose()
{
Close();
}
public T GetBody<T>()
{
XmlDictionaryReader reader = GetReaderAtBodyContents(); // This call will change the message state to Read.
return OnGetBody<T>(reader);
}
protected virtual T OnGetBody<T>(XmlDictionaryReader reader)
{
return this.GetBodyCore<T>(reader, DataContractSerializerDefaults.CreateSerializer(typeof(T), int.MaxValue/*maxItems*/));
}
public T GetBody<T>(XmlObjectSerializer serializer)
{
if (serializer == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("serializer"));
return this.GetBodyCore<T>(GetReaderAtBodyContents(), serializer);
}
T GetBodyCore<T>(XmlDictionaryReader reader, XmlObjectSerializer serializer)
{
T value;
using (reader)
{
value = (T)serializer.ReadObject(reader);
this.ReadFromBodyContentsToEnd(reader);
}
return value;
}
internal virtual XmlDictionaryReader GetReaderAtHeader()
{
XmlBuffer buffer = new XmlBuffer(int.MaxValue);
XmlDictionaryWriter writer = buffer.OpenSection(XmlDictionaryReaderQuotas.Max);
WriteStartEnvelope(writer);
MessageHeaders headers = this.Headers;
for (int i = 0; i < headers.Count; i++)
headers.WriteHeader(i, writer);
writer.WriteEndElement();
writer.WriteEndElement();
buffer.CloseSection();
buffer.Close();
XmlDictionaryReader reader = buffer.GetReader(0);
reader.ReadStartElement();
reader.MoveToStartElement();
return reader;
}
public XmlDictionaryReader GetReaderAtBodyContents()
{
EnsureReadMessageState();
if (IsEmpty)
throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.MessageIsEmpty)), this);
return OnGetReaderAtBodyContents();
}
internal void EnsureReadMessageState()
{
switch (state)
{
case MessageState.Created:
state = MessageState.Read;
if (DiagnosticUtility.ShouldTraceVerbose)
{
TraceUtility.TraceEvent(TraceEventType.Verbose, TraceCode.MessageRead, SR.GetString(SR.TraceCodeMessageRead), this);
}
break;
case MessageState.Copied:
throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.MessageHasBeenCopied)), this);
case MessageState.Read:
throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.MessageHasBeenRead)), this);
case MessageState.Written:
throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.MessageHasBeenWritten)), this);
case MessageState.Closed:
throw TraceUtility.ThrowHelperError(CreateMessageDisposedException(), this);
default:
Fx.Assert(SR.GetString(SR.InvalidMessageState));
throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.InvalidMessageState)), this);
}
}
internal SeekableMessageNavigator GetNavigator(bool navigateBody, int maxNodes)
{
if (IsDisposed)
throw TraceUtility.ThrowHelperError(CreateMessageDisposedException(), this);
if (null == this.messageNavigator)
{
this.messageNavigator = new SeekableMessageNavigator(this, maxNodes, XmlSpace.Default, navigateBody, false);
}
else
{
this.messageNavigator.ForkNodeCount(maxNodes);
}
return this.messageNavigator;
}
internal void InitializeReply(Message request)
{
UniqueId requestMessageID = request.Headers.MessageId;
if (requestMessageID == null)
throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.RequestMessageDoesNotHaveAMessageID)), request);
Headers.RelatesTo = requestMessageID;
}
static internal bool IsFaultStartElement(XmlDictionaryReader reader, EnvelopeVersion version)
{
return reader.IsStartElement(XD.MessageDictionary.Fault, version.DictionaryNamespace);
}
protected virtual void OnBodyToString(XmlDictionaryWriter writer)
{
writer.WriteString(SR.GetString(SR.MessageBodyIsUnknown));
}
protected virtual MessageBuffer OnCreateBufferedCopy(int maxBufferSize)
{
return OnCreateBufferedCopy(maxBufferSize, XmlDictionaryReaderQuotas.Max);
}
internal MessageBuffer OnCreateBufferedCopy(int maxBufferSize, XmlDictionaryReaderQuotas quotas)
{
XmlBuffer msgBuffer = new XmlBuffer(maxBufferSize);
XmlDictionaryWriter writer = msgBuffer.OpenSection(quotas);
OnWriteMessage(writer);
msgBuffer.CloseSection();
msgBuffer.Close();
return new DefaultMessageBuffer(this, msgBuffer);
}
protected virtual void OnClose()
{
}
protected virtual XmlDictionaryReader OnGetReaderAtBodyContents()
{
XmlBuffer bodyBuffer = new XmlBuffer(int.MaxValue);
XmlDictionaryWriter writer = bodyBuffer.OpenSection(XmlDictionaryReaderQuotas.Max);
if (this.Version.Envelope != EnvelopeVersion.None)
{
OnWriteStartEnvelope(writer);
OnWriteStartBody(writer);
}
OnWriteBodyContents(writer);
if (this.Version.Envelope != EnvelopeVersion.None)
{
writer.WriteEndElement();
writer.WriteEndElement();
}
bodyBuffer.CloseSection();
bodyBuffer.Close();
XmlDictionaryReader reader = bodyBuffer.GetReader(0);
if (this.Version.Envelope != EnvelopeVersion.None)
{
reader.ReadStartElement();
reader.ReadStartElement();
}
reader.MoveToContent();
return reader;
}
protected virtual void OnWriteStartBody(XmlDictionaryWriter writer)
{
MessageDictionary messageDictionary = XD.MessageDictionary;
writer.WriteStartElement(messageDictionary.Prefix.Value, messageDictionary.Body, Version.Envelope.DictionaryNamespace);
}
public void WriteBodyContents(XmlDictionaryWriter writer)
{
EnsureWriteMessageState(writer);
OnWriteBodyContents(writer);
}
public IAsyncResult BeginWriteBodyContents(XmlDictionaryWriter writer, AsyncCallback callback, object state)
{
EnsureWriteMessageState(writer);
return this.OnBeginWriteBodyContents(writer, callback, state);
}
public void EndWriteBodyContents(IAsyncResult result)
{
this.OnEndWriteBodyContents(result);
}
protected abstract void OnWriteBodyContents(XmlDictionaryWriter writer);
protected virtual IAsyncResult OnBeginWriteBodyContents(XmlDictionaryWriter writer, AsyncCallback callback, object state)
{
return new OnWriteBodyContentsAsyncResult(writer, this, callback, state);
}
protected virtual void OnEndWriteBodyContents(IAsyncResult result)
{
OnWriteBodyContentsAsyncResult.End(result);
}
public void WriteStartEnvelope(XmlDictionaryWriter writer)
{
if (writer == null)
throw TraceUtility.ThrowHelperError(new ArgumentNullException("writer"), this);
OnWriteStartEnvelope(writer);
}
protected virtual void OnWriteStartEnvelope(XmlDictionaryWriter writer)
{
EnvelopeVersion envelopeVersion = Version.Envelope;
if (envelopeVersion != EnvelopeVersion.None)
{
MessageDictionary messageDictionary = XD.MessageDictionary;
writer.WriteStartElement(messageDictionary.Prefix.Value, messageDictionary.Envelope, envelopeVersion.DictionaryNamespace);
WriteSharedHeaderPrefixes(writer);
}
}
protected virtual void OnWriteStartHeaders(XmlDictionaryWriter writer)
{
EnvelopeVersion envelopeVersion = Version.Envelope;
if (envelopeVersion != EnvelopeVersion.None)
{
MessageDictionary messageDictionary = XD.MessageDictionary;
writer.WriteStartElement(messageDictionary.Prefix.Value, messageDictionary.Header, envelopeVersion.DictionaryNamespace);
}
}
public override string ToString()
{
if (IsDisposed)
{
return base.ToString();
}
StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture);
EncodingFallbackAwareXmlTextWriter textWriter = new EncodingFallbackAwareXmlTextWriter(stringWriter);
textWriter.Formatting = Formatting.Indented;
XmlDictionaryWriter writer = XmlDictionaryWriter.CreateDictionaryWriter(textWriter);
try
{
ToString(writer);
writer.Flush();
return stringWriter.ToString();
}
catch (XmlException e)
{
return SR.GetString(SR.MessageBodyToStringError, e.GetType().ToString(), e.Message);
}
}
internal void ToString(XmlDictionaryWriter writer)
{
if (IsDisposed)
{
throw TraceUtility.ThrowHelperError(CreateMessageDisposedException(), this);
}
if (this.Version.Envelope != EnvelopeVersion.None)
{
WriteStartEnvelope(writer);
WriteStartHeaders(writer);
MessageHeaders headers = this.Headers;
for (int i = 0; i < headers.Count; i++)
{
headers.WriteHeader(i, writer);
}
writer.WriteEndElement();
MessageDictionary messageDictionary = XD.MessageDictionary;
WriteStartBody(writer);
}
BodyToString(writer);
if (this.Version.Envelope != EnvelopeVersion.None)
{
writer.WriteEndElement();
writer.WriteEndElement();
}
}
public string GetBodyAttribute(string localName, string ns)
{
if (localName == null)
throw TraceUtility.ThrowHelperError(new ArgumentNullException("localName"), this);
if (ns == null)
throw TraceUtility.ThrowHelperError(new ArgumentNullException("ns"), this);
switch (state)
{
case MessageState.Created:
break;
case MessageState.Copied:
throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.MessageHasBeenCopied)), this);
case MessageState.Read:
throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.MessageHasBeenRead)), this);
case MessageState.Written:
throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.MessageHasBeenWritten)), this);
case MessageState.Closed:
throw TraceUtility.ThrowHelperError(CreateMessageDisposedException(), this);
default:
Fx.Assert(SR.GetString(SR.InvalidMessageState));
throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.InvalidMessageState)), this);
}
return OnGetBodyAttribute(localName, ns);
}
protected virtual string OnGetBodyAttribute(string localName, string ns)
{
return null;
}
internal void ReadFromBodyContentsToEnd(XmlDictionaryReader reader)
{
Message.ReadFromBodyContentsToEnd(reader, this.Version.Envelope);
}
static void ReadFromBodyContentsToEnd(XmlDictionaryReader reader, EnvelopeVersion envelopeVersion)
{
if (envelopeVersion != EnvelopeVersion.None)
{
reader.ReadEndElement(); // </Body>
reader.ReadEndElement(); // </Envelope>
}
reader.MoveToContent();
}
internal static bool ReadStartBody(XmlDictionaryReader reader, EnvelopeVersion envelopeVersion, out bool isFault, out bool isEmpty)
{
if (reader.IsEmptyElement)
{
reader.Read();
isEmpty = true;
isFault = false;
reader.ReadEndElement();
return false;
}
else
{
reader.Read();
if (reader.NodeType != XmlNodeType.Element)
reader.MoveToContent();
if (reader.NodeType == XmlNodeType.Element)
{
isFault = IsFaultStartElement(reader, envelopeVersion);
isEmpty = false;
}
else if (reader.NodeType == XmlNodeType.EndElement)
{
isEmpty = true;
isFault = false;
Message.ReadFromBodyContentsToEnd(reader, envelopeVersion);
return false;
}
else
{
isEmpty = false;
isFault = false;
}
return true;
}
}
public void WriteBody(XmlWriter writer)
{
WriteBody(XmlDictionaryWriter.CreateDictionaryWriter(writer));
}
public void WriteBody(XmlDictionaryWriter writer)
{
WriteStartBody(writer);
WriteBodyContents(writer);
writer.WriteEndElement();
}
public void WriteStartBody(XmlWriter writer)
{
WriteStartBody(XmlDictionaryWriter.CreateDictionaryWriter(writer));
}
public void WriteStartBody(XmlDictionaryWriter writer)
{
if (writer == null)
throw TraceUtility.ThrowHelperError(new ArgumentNullException("writer"), this);
OnWriteStartBody(writer);
}
internal void WriteStartHeaders(XmlDictionaryWriter writer)
{
OnWriteStartHeaders(writer);
}
public void WriteMessage(XmlWriter writer)
{
WriteMessage(XmlDictionaryWriter.CreateDictionaryWriter(writer));
}
public void WriteMessage(XmlDictionaryWriter writer)
{
EnsureWriteMessageState(writer);
OnWriteMessage(writer);
}
void EnsureWriteMessageState(XmlDictionaryWriter writer)
{
if (writer == null)
throw TraceUtility.ThrowHelperError(new ArgumentNullException("writer"), this);
switch (state)
{
case MessageState.Created:
state = MessageState.Written;
if (DiagnosticUtility.ShouldTraceVerbose)
{
TraceUtility.TraceEvent(TraceEventType.Verbose, TraceCode.MessageWritten, SR.GetString(SR.TraceCodeMessageWritten), this);
}
break;
case MessageState.Copied:
throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.MessageHasBeenCopied)), this);
case MessageState.Read:
throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.MessageHasBeenRead)), this);
case MessageState.Written:
throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.MessageHasBeenWritten)), this);
case MessageState.Closed:
throw TraceUtility.ThrowHelperError(CreateMessageDisposedException(), this);
default:
Fx.Assert(SR.GetString(SR.InvalidMessageState));
throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.InvalidMessageState)), this);
}
}
public IAsyncResult BeginWriteMessage(XmlDictionaryWriter writer, AsyncCallback callback, object state)
{
EnsureWriteMessageState(writer);
return OnBeginWriteMessage(writer, callback, state);
}
public void EndWriteMessage(IAsyncResult result)
{
OnEndWriteMessage(result);
}
protected virtual void OnWriteMessage(XmlDictionaryWriter writer)
{
WriteMessagePreamble(writer);
OnWriteBodyContents(writer);
WriteMessagePostamble(writer);
}
internal void WriteMessagePreamble(XmlDictionaryWriter writer)
{
if (this.Version.Envelope != EnvelopeVersion.None)
{
OnWriteStartEnvelope(writer);
MessageHeaders headers = this.Headers;
int headersCount = headers.Count;
if (headersCount > 0)
{
OnWriteStartHeaders(writer);
for (int i = 0; i < headersCount; i++)
{
headers.WriteHeader(i, writer);
}
writer.WriteEndElement();
}
OnWriteStartBody(writer);
}
}
internal void WriteMessagePostamble(XmlDictionaryWriter writer)
{
if (this.Version.Envelope != EnvelopeVersion.None)
{
writer.WriteEndElement();
writer.WriteEndElement();
}
}
protected virtual IAsyncResult OnBeginWriteMessage(XmlDictionaryWriter writer, AsyncCallback callback, object state)
{
return new OnWriteMessageAsyncResult(writer, this, callback, state);
}
protected virtual void OnEndWriteMessage(IAsyncResult result)
{
OnWriteMessageAsyncResult.End(result);
}
void WriteSharedHeaderPrefixes(XmlDictionaryWriter writer)
{
MessageHeaders headers = Headers;
int count = headers.Count;
int prefixesWritten = 0;
for (int i = 0; i < count; i++)
{
if (this.Version.Addressing == AddressingVersion.None && headers[i].Namespace == AddressingVersion.None.Namespace)
{
continue;
}
IMessageHeaderWithSharedNamespace headerWithSharedNamespace = headers[i] as IMessageHeaderWithSharedNamespace;
if (headerWithSharedNamespace != null)
{
XmlDictionaryString prefix = headerWithSharedNamespace.SharedPrefix;
string prefixString = prefix.Value;
if (!((prefixString.Length == 1)))
{
Fx.Assert("Message.WriteSharedHeaderPrefixes: (prefixString.Length == 1) -- IMessageHeaderWithSharedNamespace must use a single lowercase letter prefix.");
throw TraceUtility.ThrowHelperError(new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, "IMessageHeaderWithSharedNamespace must use a single lowercase letter prefix.")), this);
}
int prefixIndex = prefixString[0] - 'a';
if (!((prefixIndex >= 0 && prefixIndex < 26)))
{
Fx.Assert("Message.WriteSharedHeaderPrefixes: (prefixIndex >= 0 && prefixIndex < 26) -- IMessageHeaderWithSharedNamespace must use a single lowercase letter prefix.");
throw TraceUtility.ThrowHelperError(new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, "IMessageHeaderWithSharedNamespace must use a single lowercase letter prefix.")), this);
}
int prefixBit = 1 << prefixIndex;
if ((prefixesWritten & prefixBit) == 0)
{
writer.WriteXmlnsAttribute(prefixString, headerWithSharedNamespace.SharedNamespace);
prefixesWritten |= prefixBit;
}
}
}
}
class OnWriteBodyContentsAsyncResult : ScheduleActionItemAsyncResult
{
Message message;
XmlDictionaryWriter writer;
public OnWriteBodyContentsAsyncResult(XmlDictionaryWriter writer, Message message, AsyncCallback callback, object state)
: base(callback, state)
{
Fx.Assert(message != null, "message should never be null");
this.message = message;
this.writer = writer;
Schedule();
}
protected override void OnDoWork()
{
this.message.OnWriteBodyContents(this.writer);
}
}
class OnWriteMessageAsyncResult : ScheduleActionItemAsyncResult
{
Message message;
XmlDictionaryWriter writer;
public OnWriteMessageAsyncResult(XmlDictionaryWriter writer, Message message, AsyncCallback callback, object state)
: base(callback, state)
{
Fx.Assert(message != null, "message should never be null");
this.message = message;
this.writer = writer;
Schedule();
}
protected override void OnDoWork()
{
this.message.OnWriteMessage(this.writer);
}
}
}
class EmptyBodyWriter : BodyWriter
{
static EmptyBodyWriter value;
EmptyBodyWriter()
: base(true)
{
}
public static EmptyBodyWriter Value
{
get
{
if (value == null)
value = new EmptyBodyWriter();
return value;
}
}
internal override bool IsEmpty
{
get { return true; }
}
protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
{
}
}
class FaultBodyWriter : BodyWriter
{
MessageFault fault;
EnvelopeVersion version;
public FaultBodyWriter(MessageFault fault, EnvelopeVersion version)
: base(true)
{
this.fault = fault;
this.version = version;
}
internal override bool IsFault
{
get { return true; }
}
protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
{
fault.WriteTo(writer, version);
}
}
class XmlObjectSerializerBodyWriter : BodyWriter
{
object body;
XmlObjectSerializer serializer;
public XmlObjectSerializerBodyWriter(object body, XmlObjectSerializer serializer)
: base(true)
{
this.body = body;
this.serializer = serializer;
}
object ThisLock
{
get { return this; }
}
protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
{
lock (ThisLock)
{
serializer.WriteObject(writer, body);
}
}
}
class XmlReaderBodyWriter : BodyWriter
{
XmlDictionaryReader reader;
bool isFault;
public XmlReaderBodyWriter(XmlDictionaryReader reader, EnvelopeVersion version)
: base(false)
{
this.reader = reader;
if (reader.MoveToContent() != XmlNodeType.Element)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.InvalidReaderPositionOnCreateMessage), "reader"));
this.isFault = Message.IsFaultStartElement(reader, version);
}
internal override bool IsFault
{
get
{
return this.isFault;
}
}
protected override BodyWriter OnCreateBufferedCopy(int maxBufferSize)
{
return OnCreateBufferedCopy(maxBufferSize, this.reader.Quotas);
}
protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
{
using (reader)
{
XmlNodeType type = reader.MoveToContent();
while (!reader.EOF && type != XmlNodeType.EndElement)
{
if (type != XmlNodeType.Element)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.InvalidReaderPositionOnCreateMessage), "reader"));
writer.WriteNode(reader, false);
type = reader.MoveToContent();
}
}
}
}
class BodyWriterMessage : Message
{
MessageProperties properties;
MessageHeaders headers;
BodyWriter bodyWriter;
BodyWriterMessage(BodyWriter bodyWriter)
{
this.bodyWriter = bodyWriter;
}
public BodyWriterMessage(MessageVersion version, string action, BodyWriter bodyWriter)
: this(bodyWriter)
{
this.headers = new MessageHeaders(version);
this.headers.Action = action;
}
public BodyWriterMessage(MessageVersion version, ActionHeader actionHeader, BodyWriter bodyWriter)
: this(bodyWriter)
{
this.headers = new MessageHeaders(version);
this.headers.SetActionHeader(actionHeader);
}
public BodyWriterMessage(MessageHeaders headers, KeyValuePair<string, object>[] properties, BodyWriter bodyWriter)
: this(bodyWriter)
{
this.headers = new MessageHeaders(headers);
this.properties = new MessageProperties(properties);
}
public override bool IsFault
{
get
{
if (IsDisposed)
#pragma warning suppress 56503 // [....], Invalid State after dispose
throw TraceUtility.ThrowHelperError(CreateMessageDisposedException(), this);
return bodyWriter.IsFault;
}
}
public override bool IsEmpty
{
get
{
if (IsDisposed)
#pragma warning suppress 56503 // [....], Invalid State after dispose
throw TraceUtility.ThrowHelperError(CreateMessageDisposedException(), this);
return bodyWriter.IsEmpty;
}
}
public override MessageHeaders Headers
{
get
{
if (IsDisposed)
#pragma warning suppress 56503 // [....], Invalid State after dispose
throw TraceUtility.ThrowHelperError(CreateMessageDisposedException(), this);
return headers;
}
}
public override MessageProperties Properties
{
get
{
if (IsDisposed)
#pragma warning suppress 56503 // [....], Invalid State after dispose
throw TraceUtility.ThrowHelperError(CreateMessageDisposedException(), this);
if (properties == null)
properties = new MessageProperties();
return properties;
}
}
public override MessageVersion Version
{
get
{
if (IsDisposed)
#pragma warning suppress 56503 // [....], Invalid State after dispose
throw TraceUtility.ThrowHelperError(CreateMessageDisposedException(), this);
return headers.MessageVersion;
}
}
protected override MessageBuffer OnCreateBufferedCopy(int maxBufferSize)
{
BodyWriter bufferedBodyWriter;
if (bodyWriter.IsBuffered)
{
bufferedBodyWriter = bodyWriter;
}
else
{
bufferedBodyWriter = bodyWriter.CreateBufferedCopy(maxBufferSize);
}
KeyValuePair<string, object>[] properties = new KeyValuePair<string, object>[Properties.Count];
((ICollection<KeyValuePair<string, object>>)Properties).CopyTo(properties, 0);
return new BodyWriterMessageBuffer(headers, properties, bufferedBodyWriter);
}
protected override void OnClose()
{
Exception ex = null;
try
{
base.OnClose();
}
catch (Exception e)
{
if (Fx.IsFatal(e))
throw;
ex = e;
}
try
{
if (properties != null)
properties.Dispose();
}
catch (Exception e)
{
if (Fx.IsFatal(e))
throw;
if (ex == null)
ex = e;
}
if (ex != null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(ex);
bodyWriter = null;
}
protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
{
bodyWriter.WriteBodyContents(writer);
}
protected override IAsyncResult OnBeginWriteMessage(XmlDictionaryWriter writer, AsyncCallback callback, object state)
{
WriteMessagePreamble(writer);
return new OnWriteMessageAsyncResult(writer, this, callback, state);
}
protected override void OnEndWriteMessage(IAsyncResult result)
{
OnWriteMessageAsyncResult.End(result);
}
protected override IAsyncResult OnBeginWriteBodyContents(XmlDictionaryWriter writer, AsyncCallback callback, object state)
{
return bodyWriter.BeginWriteBodyContents(writer, callback, state);
}
protected override void OnEndWriteBodyContents(IAsyncResult result)
{
bodyWriter.EndWriteBodyContents(result);
}
protected override void OnBodyToString(XmlDictionaryWriter writer)
{
if (bodyWriter.IsBuffered)
{
bodyWriter.WriteBodyContents(writer);
}
else
{
writer.WriteString(SR.GetString(SR.MessageBodyIsStream));
}
}
protected internal BodyWriter BodyWriter
{
get
{
return bodyWriter;
}
}
class OnWriteMessageAsyncResult : AsyncResult
{
BodyWriterMessage message;
XmlDictionaryWriter writer;
public OnWriteMessageAsyncResult(XmlDictionaryWriter writer, BodyWriterMessage message, AsyncCallback callback, object state)
: base(callback, state)
{
this.message = message;
this.writer = writer;
if (HandleWriteBodyContents(null))
{
this.Complete(true);
}
}
bool HandleWriteBodyContents(IAsyncResult result)
{
if (result == null)
{
result = this.message.OnBeginWriteBodyContents(this.writer, PrepareAsyncCompletion(HandleWriteBodyContents), this);
if (!result.CompletedSynchronously)
{
return false;
}
}
this.message.OnEndWriteBodyContents(result);
this.message.WriteMessagePostamble(this.writer);
return true;
}
public static void End(IAsyncResult result)
{
AsyncResult.End<OnWriteMessageAsyncResult>(result);
}
}
}
abstract class ReceivedMessage : Message
{
bool isFault;
bool isEmpty;
public override bool IsEmpty
{
get { return isEmpty; }
}
public override bool IsFault
{
get { return isFault; }
}
protected static bool HasHeaderElement(XmlDictionaryReader reader, EnvelopeVersion envelopeVersion)
{
return reader.IsStartElement(XD.MessageDictionary.Header, envelopeVersion.DictionaryNamespace);
}
protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
{
if (!isEmpty)
{
using (XmlDictionaryReader bodyReader = OnGetReaderAtBodyContents())
{
if (bodyReader.ReadState == ReadState.Error || bodyReader.ReadState == ReadState.Closed)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.MessageBodyReaderInvalidReadState, bodyReader.ReadState.ToString())));
while (bodyReader.NodeType != XmlNodeType.EndElement && !bodyReader.EOF)
{
writer.WriteNode(bodyReader, false);
}
this.ReadFromBodyContentsToEnd(bodyReader);
}
}
}
protected bool ReadStartBody(XmlDictionaryReader reader)
{
return Message.ReadStartBody(reader, this.Version.Envelope, out this.isFault, out this.isEmpty);
}
protected static EnvelopeVersion ReadStartEnvelope(XmlDictionaryReader reader)
{
EnvelopeVersion envelopeVersion;
if (reader.IsStartElement(XD.MessageDictionary.Envelope, XD.Message12Dictionary.Namespace))
envelopeVersion = EnvelopeVersion.Soap12;
else if (reader.IsStartElement(XD.MessageDictionary.Envelope, XD.Message11Dictionary.Namespace))
envelopeVersion = EnvelopeVersion.Soap11;
else
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(SR.GetString(SR.MessageVersionUnknown)));
if (reader.IsEmptyElement)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(SR.GetString(SR.MessageBodyMissing)));
reader.Read();
return envelopeVersion;
}
protected static void VerifyStartBody(XmlDictionaryReader reader, EnvelopeVersion version)
{
if (!reader.IsStartElement(XD.MessageDictionary.Body, version.DictionaryNamespace))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(SR.GetString(SR.MessageBodyMissing)));
}
}
sealed class StreamedMessage : ReceivedMessage
{
MessageHeaders headers;
XmlAttributeHolder[] envelopeAttributes;
XmlAttributeHolder[] headerAttributes;
XmlAttributeHolder[] bodyAttributes;
string envelopePrefix;
string headerPrefix;
string bodyPrefix;
MessageProperties properties;
XmlDictionaryReader reader;
XmlDictionaryReaderQuotas quotas;
public StreamedMessage(XmlDictionaryReader reader, int maxSizeOfHeaders, MessageVersion desiredVersion)
{
properties = new MessageProperties();
if (reader.NodeType != XmlNodeType.Element)
reader.MoveToContent();
if (desiredVersion.Envelope == EnvelopeVersion.None)
{
this.reader = reader;
this.headerAttributes = XmlAttributeHolder.emptyArray;
this.headers = new MessageHeaders(desiredVersion);
}
else
{
envelopeAttributes = XmlAttributeHolder.ReadAttributes(reader, ref maxSizeOfHeaders);
envelopePrefix = reader.Prefix;
EnvelopeVersion envelopeVersion = ReadStartEnvelope(reader);
if (desiredVersion.Envelope != envelopeVersion)
{
Exception versionMismatchException = new ArgumentException(SR.GetString(SR.EncoderEnvelopeVersionMismatch, envelopeVersion, desiredVersion.Envelope), "reader");
throw TraceUtility.ThrowHelperError(
new CommunicationException(versionMismatchException.Message, versionMismatchException),
this);
}
if (HasHeaderElement(reader, envelopeVersion))
{
headerPrefix = reader.Prefix;
headerAttributes = XmlAttributeHolder.ReadAttributes(reader, ref maxSizeOfHeaders);
headers = new MessageHeaders(desiredVersion, reader, envelopeAttributes, headerAttributes, ref maxSizeOfHeaders);
}
else
{
headerAttributes = XmlAttributeHolder.emptyArray;
headers = new MessageHeaders(desiredVersion);
}
if (reader.NodeType != XmlNodeType.Element)
reader.MoveToContent();
bodyPrefix = reader.Prefix;
VerifyStartBody(reader, envelopeVersion);
bodyAttributes = XmlAttributeHolder.ReadAttributes(reader, ref maxSizeOfHeaders);
if (ReadStartBody(reader))
{
this.reader = reader;
}
else
{
this.quotas = new XmlDictionaryReaderQuotas();
reader.Quotas.CopyTo(this.quotas);
reader.Close();
}
}
}
public override MessageHeaders Headers
{
get
{
if (IsDisposed)
#pragma warning suppress 56503 // [....], Invalid State after dispose
throw TraceUtility.ThrowHelperError(CreateMessageDisposedException(), this);
return headers;
}
}
public override MessageVersion Version
{
get
{
return headers.MessageVersion;
}
}
public override MessageProperties Properties
{
get
{
return properties;
}
}
protected override void OnBodyToString(XmlDictionaryWriter writer)
{
writer.WriteString(SR.GetString(SR.MessageBodyIsStream));
}
protected override void OnClose()
{
Exception ex = null;
try
{
base.OnClose();
}
catch (Exception e)
{
if (Fx.IsFatal(e))
throw;
ex = e;
}
try
{
properties.Dispose();
}
catch (Exception e)
{
if (Fx.IsFatal(e))
throw;
if (ex == null)
ex = e;
}
try
{
if (reader != null)
{
reader.Close();
}
}
catch (Exception e)
{
if (Fx.IsFatal(e))
throw;
if (ex == null)
ex = e;
}
if (ex != null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(ex);
}
protected override XmlDictionaryReader OnGetReaderAtBodyContents()
{
XmlDictionaryReader reader = this.reader;
this.reader = null;
return reader;
}
protected override MessageBuffer OnCreateBufferedCopy(int maxBufferSize)
{
if (this.reader != null)
return OnCreateBufferedCopy(maxBufferSize, this.reader.Quotas);
return OnCreateBufferedCopy(maxBufferSize, this.quotas);
}
protected override void OnWriteStartBody(XmlDictionaryWriter writer)
{
writer.WriteStartElement(bodyPrefix, MessageStrings.Body, Version.Envelope.Namespace);
XmlAttributeHolder.WriteAttributes(bodyAttributes, writer);
}
protected override void OnWriteStartEnvelope(XmlDictionaryWriter writer)
{
EnvelopeVersion envelopeVersion = Version.Envelope;
writer.WriteStartElement(envelopePrefix, MessageStrings.Envelope, envelopeVersion.Namespace);
XmlAttributeHolder.WriteAttributes(envelopeAttributes, writer);
}
protected override void OnWriteStartHeaders(XmlDictionaryWriter writer)
{
EnvelopeVersion envelopeVersion = Version.Envelope;
writer.WriteStartElement(headerPrefix, MessageStrings.Header, envelopeVersion.Namespace);
XmlAttributeHolder.WriteAttributes(headerAttributes, writer);
}
protected override string OnGetBodyAttribute(string localName, string ns)
{
return XmlAttributeHolder.GetAttribute(bodyAttributes, localName, ns);
}
}
interface IBufferedMessageData
{
MessageEncoder MessageEncoder { get; }
ArraySegment<byte> Buffer { get; }
XmlDictionaryReaderQuotas Quotas { get; }
void Close();
void EnableMultipleUsers();
XmlDictionaryReader GetMessageReader();
void Open();
void ReturnMessageState(RecycledMessageState messageState);
RecycledMessageState TakeMessageState();
}
sealed class BufferedMessage : ReceivedMessage
{
MessageHeaders headers;
MessageProperties properties;
IBufferedMessageData messageData;
RecycledMessageState recycledMessageState;
XmlDictionaryReader reader;
XmlAttributeHolder[] bodyAttributes;
public BufferedMessage(IBufferedMessageData messageData, RecycledMessageState recycledMessageState)
: this(messageData, recycledMessageState, null, false)
{
}
public BufferedMessage(IBufferedMessageData messageData, RecycledMessageState recycledMessageState, bool[] understoodHeaders, bool understoodHeadersModified)
{
bool throwing = true;
try
{
this.recycledMessageState = recycledMessageState;
this.messageData = messageData;
properties = recycledMessageState.TakeProperties();
if (properties == null)
this.properties = new MessageProperties();
XmlDictionaryReader reader = messageData.GetMessageReader();
MessageVersion desiredVersion = messageData.MessageEncoder.MessageVersion;
if (desiredVersion.Envelope == EnvelopeVersion.None)
{
this.reader = reader;
this.headers = new MessageHeaders(desiredVersion);
}
else
{
EnvelopeVersion envelopeVersion = ReadStartEnvelope(reader);
if (desiredVersion.Envelope != envelopeVersion)
{
Exception versionMismatchException = new ArgumentException(SR.GetString(SR.EncoderEnvelopeVersionMismatch, envelopeVersion, desiredVersion.Envelope), "reader");
throw TraceUtility.ThrowHelperError(
new CommunicationException(versionMismatchException.Message, versionMismatchException),
this);
}
if (HasHeaderElement(reader, envelopeVersion))
{
headers = recycledMessageState.TakeHeaders();
if (headers == null)
{
headers = new MessageHeaders(desiredVersion, reader, messageData, recycledMessageState, understoodHeaders, understoodHeadersModified);
}
else
{
headers.Init(desiredVersion, reader, messageData, recycledMessageState, understoodHeaders, understoodHeadersModified);
}
}
else
{
headers = new MessageHeaders(desiredVersion);
}
VerifyStartBody(reader, envelopeVersion);
int maxSizeOfAttributes = int.MaxValue;
bodyAttributes = XmlAttributeHolder.ReadAttributes(reader, ref maxSizeOfAttributes);
if (maxSizeOfAttributes < int.MaxValue - 4096)
bodyAttributes = null;
if (ReadStartBody(reader))
{
this.reader = reader;
}
else
{
reader.Close();
}
}
throwing = false;
}
finally
{
if (throwing && MessageLogger.LoggingEnabled)
{
MessageLogger.LogMessage(messageData.Buffer, MessageLoggingSource.Malformed);
}
}
}
public override MessageHeaders Headers
{
get
{
if (IsDisposed)
#pragma warning suppress 56503 // [....], Invalid State after dispose
throw TraceUtility.ThrowHelperError(CreateMessageDisposedException(), this);
return headers;
}
}
internal IBufferedMessageData MessageData
{
get
{
return messageData;
}
}
public override MessageProperties Properties
{
get
{
if (IsDisposed)
#pragma warning suppress 56503 // [....], Invalid State after dispose
throw TraceUtility.ThrowHelperError(CreateMessageDisposedException(), this);
return properties;
}
}
internal override RecycledMessageState RecycledMessageState
{
get { return recycledMessageState; }
}
public override MessageVersion Version
{
get
{
return headers.MessageVersion;
}
}
protected override XmlDictionaryReader OnGetReaderAtBodyContents()
{
XmlDictionaryReader reader = this.reader;
this.reader = null;
return reader;
}
internal override XmlDictionaryReader GetReaderAtHeader()
{
if (!headers.ContainsOnlyBufferedMessageHeaders)
return base.GetReaderAtHeader();
XmlDictionaryReader reader = messageData.GetMessageReader();
if (reader.NodeType != XmlNodeType.Element)
reader.MoveToContent();
reader.Read();
if (HasHeaderElement(reader, headers.MessageVersion.Envelope))
return reader;
return base.GetReaderAtHeader();
}
public XmlDictionaryReader GetBufferedReaderAtBody()
{
XmlDictionaryReader reader = messageData.GetMessageReader();
if (reader.NodeType != XmlNodeType.Element)
reader.MoveToContent();
if (this.Version.Envelope != EnvelopeVersion.None)
{
reader.Read();
if (HasHeaderElement(reader, headers.MessageVersion.Envelope))
reader.Skip();
if (reader.NodeType != XmlNodeType.Element)
reader.MoveToContent();
}
return reader;
}
public XmlDictionaryReader GetMessageReader()
{
return messageData.GetMessageReader();
}
protected override void OnBodyToString(XmlDictionaryWriter writer)
{
using (XmlDictionaryReader reader = GetBufferedReaderAtBody())
{
if (this.Version == MessageVersion.None)
{
writer.WriteNode(reader, false);
}
else
{
if (!reader.IsEmptyElement)
{
reader.ReadStartElement();
while (reader.NodeType != XmlNodeType.EndElement)
writer.WriteNode(reader, false);
}
}
}
}
protected override void OnClose()
{
Exception ex = null;
try
{
base.OnClose();
}
catch (Exception e)
{
if (Fx.IsFatal(e))
throw;
ex = e;
}
try
{
properties.Dispose();
}
catch (Exception e)
{
if (Fx.IsFatal(e))
throw;
if (ex == null)
ex = e;
}
try
{
if (reader != null)
{
reader.Close();
}
}
catch (Exception e)
{
if (Fx.IsFatal(e))
throw;
if (ex == null)
ex = e;
}
try
{
recycledMessageState.ReturnHeaders(headers);
recycledMessageState.ReturnProperties(properties);
messageData.ReturnMessageState(recycledMessageState);
recycledMessageState = null;
messageData.Close();
messageData = null;
}
catch (Exception e)
{
if (Fx.IsFatal(e))
throw;
if (ex == null)
ex = e;
}
if (ex != null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(ex);
}
protected override void OnWriteStartEnvelope(XmlDictionaryWriter writer)
{
using (XmlDictionaryReader reader = GetMessageReader())
{
reader.MoveToContent();
EnvelopeVersion envelopeVersion = Version.Envelope;
writer.WriteStartElement(reader.Prefix, MessageStrings.Envelope, envelopeVersion.Namespace);
writer.WriteAttributes(reader, false);
}
}
protected override void OnWriteStartHeaders(XmlDictionaryWriter writer)
{
using (XmlDictionaryReader reader = GetMessageReader())
{
reader.MoveToContent();
EnvelopeVersion envelopeVersion = Version.Envelope;
reader.Read();
if (HasHeaderElement(reader, envelopeVersion))
{
writer.WriteStartElement(reader.Prefix, MessageStrings.Header, envelopeVersion.Namespace);
writer.WriteAttributes(reader, false);
}
else
{
writer.WriteStartElement(MessageStrings.Prefix, MessageStrings.Header, envelopeVersion.Namespace);
}
}
}
protected override void OnWriteStartBody(XmlDictionaryWriter writer)
{
using (XmlDictionaryReader reader = GetBufferedReaderAtBody())
{
writer.WriteStartElement(reader.Prefix, MessageStrings.Body, Version.Envelope.Namespace);
writer.WriteAttributes(reader, false);
}
}
protected override MessageBuffer OnCreateBufferedCopy(int maxBufferSize)
{
if (headers.ContainsOnlyBufferedMessageHeaders)
{
KeyValuePair<string, object>[] properties = new KeyValuePair<string, object>[Properties.Count];
((ICollection<KeyValuePair<string, object>>)Properties).CopyTo(properties, 0);
messageData.EnableMultipleUsers();
bool[] understoodHeaders = null;
if (headers.HasMustUnderstandBeenModified)
{
understoodHeaders = new bool[headers.Count];
for (int i = 0; i < headers.Count; i++)
{
understoodHeaders[i] = headers.IsUnderstood(i);
}
}
return new BufferedMessageBuffer(messageData, properties, understoodHeaders, headers.HasMustUnderstandBeenModified);
}
else
{
if (this.reader != null)
return OnCreateBufferedCopy(maxBufferSize, this.reader.Quotas);
return OnCreateBufferedCopy(maxBufferSize, XmlDictionaryReaderQuotas.Max);
}
}
protected override string OnGetBodyAttribute(string localName, string ns)
{
if (this.bodyAttributes != null)
return XmlAttributeHolder.GetAttribute(this.bodyAttributes, localName, ns);
using (XmlDictionaryReader reader = GetBufferedReaderAtBody())
{
return reader.GetAttribute(localName, ns);
}
}
}
struct XmlAttributeHolder
{
string prefix;
string ns;
string localName;
string value;
public static XmlAttributeHolder[] emptyArray = new XmlAttributeHolder[0];
public XmlAttributeHolder(string prefix, string localName, string ns, string value)
{
this.prefix = prefix;
this.localName = localName;
this.ns = ns;
this.value = value;
}
public string Prefix
{
get { return prefix; }
}
public string NamespaceUri
{
get { return ns; }
}
public string LocalName
{
get { return localName; }
}
public string Value
{
get { return value; }
}
public void WriteTo(XmlWriter writer)
{
writer.WriteStartAttribute(prefix, localName, ns);
writer.WriteString(value);
writer.WriteEndAttribute();
}
public static void WriteAttributes(XmlAttributeHolder[] attributes, XmlWriter writer)
{
for (int i = 0; i < attributes.Length; i++)
attributes[i].WriteTo(writer);
}
public static XmlAttributeHolder[] ReadAttributes(XmlDictionaryReader reader)
{
int maxSizeOfHeaders = int.MaxValue;
return ReadAttributes(reader, ref maxSizeOfHeaders);
}
public static XmlAttributeHolder[] ReadAttributes(XmlDictionaryReader reader, ref int maxSizeOfHeaders)
{
if (reader.AttributeCount == 0)
return emptyArray;
XmlAttributeHolder[] attributes = new XmlAttributeHolder[reader.AttributeCount];
reader.MoveToFirstAttribute();
for (int i = 0; i < attributes.Length; i++)
{
string ns = reader.NamespaceURI;
string localName = reader.LocalName;
string prefix = reader.Prefix;
string value = string.Empty;
while (reader.ReadAttributeValue())
{
if (value.Length == 0)
value = reader.Value;
else
value += reader.Value;
}
Deduct(prefix, ref maxSizeOfHeaders);
Deduct(localName, ref maxSizeOfHeaders);
Deduct(ns, ref maxSizeOfHeaders);
Deduct(value, ref maxSizeOfHeaders);
attributes[i] = new XmlAttributeHolder(prefix, localName, ns, value);
reader.MoveToNextAttribute();
}
reader.MoveToElement();
return attributes;
}
static void Deduct(string s, ref int maxSizeOfHeaders)
{
int byteCount = s.Length * sizeof(char);
if (byteCount > maxSizeOfHeaders)
{
string message = SR.GetString(SR.XmlBufferQuotaExceeded);
Exception inner = new QuotaExceededException(message);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(message, inner));
}
maxSizeOfHeaders -= byteCount;
}
public static string GetAttribute(XmlAttributeHolder[] attributes, string localName, string ns)
{
for (int i = 0; i < attributes.Length; i++)
if (attributes[i].LocalName == localName && attributes[i].NamespaceUri == ns)
return attributes[i].Value;
return null;
}
}
class RecycledMessageState
{
MessageHeaders recycledHeaders;
MessageProperties recycledProperties;
UriCache uriCache;
HeaderInfoCache headerInfoCache;
public HeaderInfoCache HeaderInfoCache
{
get
{
if (headerInfoCache == null)
{
headerInfoCache = new HeaderInfoCache();
}
return headerInfoCache;
}
}
public UriCache UriCache
{
get
{
if (uriCache == null)
uriCache = new UriCache();
return uriCache;
}
}
public MessageProperties TakeProperties()
{
MessageProperties taken = recycledProperties;
recycledProperties = null;
return taken;
}
public void ReturnProperties(MessageProperties properties)
{
if (properties.CanRecycle)
{
properties.Recycle();
this.recycledProperties = properties;
}
}
public MessageHeaders TakeHeaders()
{
MessageHeaders taken = recycledHeaders;
recycledHeaders = null;
return taken;
}
public void ReturnHeaders(MessageHeaders headers)
{
if (headers.CanRecycle)
{
headers.Recycle(this.HeaderInfoCache);
this.recycledHeaders = headers;
}
}
}
class HeaderInfoCache
{
const int maxHeaderInfos = 4;
HeaderInfo[] headerInfos;
int index;
public MessageHeaderInfo TakeHeaderInfo(XmlDictionaryReader reader, string actor, bool mustUnderstand, bool relay, bool isRefParam)
{
if (this.headerInfos != null)
{
int i = this.index;
for (;;)
{
HeaderInfo headerInfo = this.headerInfos[i];
if (headerInfo != null)
{
if (headerInfo.Matches(reader, actor, mustUnderstand, relay, isRefParam))
{
this.headerInfos[i] = null;
this.index = (i + 1) % maxHeaderInfos;
return headerInfo;
}
}
i = (i + 1) % maxHeaderInfos;
if (i == this.index)
{
break;
}
}
}
return new HeaderInfo(reader, actor, mustUnderstand, relay, isRefParam);
}
public void ReturnHeaderInfo(MessageHeaderInfo headerInfo)
{
HeaderInfo headerInfoToReturn = headerInfo as HeaderInfo;
if (headerInfoToReturn != null)
{
if (this.headerInfos == null)
{
this.headerInfos = new HeaderInfo[maxHeaderInfos];
}
int i = this.index;
for (;;)
{
if (this.headerInfos[i] == null)
{
break;
}
i = (i + 1) % maxHeaderInfos;
if (i == this.index)
{
break;
}
}
this.headerInfos[i] = headerInfoToReturn;
this.index = (i + 1) % maxHeaderInfos;
}
}
class HeaderInfo : MessageHeaderInfo
{
string name;
string ns;
string actor;
bool isReferenceParameter;
bool mustUnderstand;
bool relay;
public HeaderInfo(XmlDictionaryReader reader, string actor, bool mustUnderstand, bool relay, bool isReferenceParameter)
{
this.actor = actor;
this.mustUnderstand = mustUnderstand;
this.relay = relay;
this.isReferenceParameter = isReferenceParameter;
reader.GetNonAtomizedNames(out name, out ns);
}
public override string Name
{
get { return name; }
}
public override string Namespace
{
get { return ns; }
}
public override bool IsReferenceParameter
{
get { return isReferenceParameter; }
}
public override string Actor
{
get { return actor; }
}
public override bool MustUnderstand
{
get { return mustUnderstand; }
}
public override bool Relay
{
get { return relay; }
}
public bool Matches(XmlDictionaryReader reader, string actor, bool mustUnderstand, bool relay, bool isRefParam)
{
return reader.IsStartElement(this.name, this.ns) &&
this.actor == actor && this.mustUnderstand == mustUnderstand && this.relay == relay && this.isReferenceParameter == isRefParam;
}
}
}
class UriCache
{
const int MaxKeyLength = 128;
const int MaxEntries = 8;
Entry[] entries;
int count;
public UriCache()
{
entries = new Entry[MaxEntries];
}
public Uri CreateUri(string uriString)
{
Uri uri = Get(uriString);
if (uri == null)
{
uri = new Uri(uriString);
Set(uriString, uri);
}
return uri;
}
Uri Get(string key)
{
if (key.Length > MaxKeyLength)
return null;
for (int i = count - 1; i >= 0; i--)
if (entries[i].Key == key)
return entries[i].Value;
return null;
}
void Set(string key, Uri value)
{
if (key.Length > MaxKeyLength)
return;
if (count < entries.Length)
{
entries[count++] = new Entry(key, value);
}
else
{
Array.Copy(entries, 1, entries, 0, entries.Length - 1);
entries[count - 1] = new Entry(key, value);
}
}
struct Entry
{
string key;
Uri value;
public Entry(string key, Uri value)
{
this.key = key;
this.value = value;
}
public string Key
{
get { return key; }
}
public Uri Value
{
get { return value; }
}
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2007 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using Microsoft.Win32;
namespace NUnit.Engine
{
/// <summary>
/// Enumeration identifying a common language
/// runtime implementation.
/// </summary>
public enum RuntimeType
{
/// <summary>Any supported runtime framework</summary>
Any,
/// <summary>Microsoft .NET Framework</summary>
Net,
/// <summary>Microsoft .NET Compact Framework</summary>
NetCF,
/// <summary>Microsoft Shared Source CLI</summary>
SSCLI,
/// <summary>Mono</summary>
Mono,
/// <summary>Silverlight</summary>
Silverlight,
/// <summary>MonoTouch</summary>
MonoTouch
}
/// <summary>
/// RuntimeFramework represents a particular version
/// of a common language runtime implementation.
/// </summary>
[Serializable]
public sealed class RuntimeFramework
{
#region Static and Instance Fields
/// <summary>
/// DefaultVersion is an empty Version, used to indicate that
/// NUnit should select the CLR version to use for the test.
/// </summary>
public static readonly Version DefaultVersion = new Version(0, 0);
private static RuntimeFramework currentFramework;
private static RuntimeFramework[] availableFrameworks;
#endregion
#region Constructor
/// <summary>
/// Construct from a runtime type and version. If the version has
/// two parts, it is taken as a framework version. If it has three
/// or more, it is taken as a CLR version. In either case, the other
/// version is deduced based on the runtime type and provided version.
/// </summary>
/// <param name="runtime">The runtime type of the framework</param>
/// <param name="version">The version of the framework</param>
public RuntimeFramework(RuntimeType runtime, Version version)
{
Runtime = runtime;
if (version.Build < 0)
InitFromFrameworkVersion(version);
else
InitFromClrVersion(version);
DisplayName = GetDefaultDisplayName(runtime, version);
}
private void InitFromFrameworkVersion(Version version)
{
this.FrameworkVersion = this.ClrVersion = version;
if (version.Major > 0) // 0 means any version
switch (Runtime)
{
case RuntimeType.Net:
case RuntimeType.Mono:
case RuntimeType.Any:
switch (version.Major)
{
case 1:
switch (version.Minor)
{
case 0:
this.ClrVersion = Runtime == RuntimeType.Mono
? new Version(1, 1, 4322)
: new Version(1, 0, 3705);
break;
case 1:
if (Runtime == RuntimeType.Mono)
this.FrameworkVersion = new Version(1, 0);
this.ClrVersion = new Version(1, 1, 4322);
break;
default:
ThrowInvalidFrameworkVersion(version);
break;
}
break;
case 2:
case 3:
this.ClrVersion = new Version(2, 0, 50727);
break;
case 4:
this.ClrVersion = new Version(4, 0, 30319);
break;
default:
ThrowInvalidFrameworkVersion(version);
break;
}
break;
case RuntimeType.Silverlight:
this.ClrVersion = version.Major >= 4
? new Version(4, 0, 60310)
: new Version(2, 0, 50727);
break;
}
}
private static void ThrowInvalidFrameworkVersion(Version version)
{
throw new ArgumentException("Unknown framework version " + version.ToString(), "version");
}
private void InitFromClrVersion(Version version)
{
this.FrameworkVersion = new Version(version.Major, version.Minor);
this.ClrVersion = version;
if (Runtime == RuntimeType.Mono && version.Major == 1)
this.FrameworkVersion = new Version(1, 0);
}
#endregion
#region Properties
/// <summary>
/// Static method to return a RuntimeFramework object
/// for the framework that is currently in use.
/// </summary>
public static RuntimeFramework CurrentFramework
{
get
{
if (currentFramework == null)
{
Type monoRuntimeType = Type.GetType("Mono.Runtime", false);
bool isMono = monoRuntimeType != null;
RuntimeType runtime = isMono
? RuntimeType.Mono
: Environment.OSVersion.Platform == PlatformID.WinCE
? RuntimeType.NetCF
: RuntimeType.Net;
int major = Environment.Version.Major;
int minor = Environment.Version.Minor;
if (isMono)
{
switch (major)
{
case 1:
minor = 0;
break;
case 2:
major = 3;
minor = 5;
break;
}
}
else /* It's windows */
if (major == 2)
{
RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\.NETFramework");
if (key != null)
{
string installRoot = key.GetValue("InstallRoot") as string;
if (installRoot != null)
{
if (Directory.Exists(Path.Combine(installRoot, "v3.5")))
{
major = 3;
minor = 5;
}
else if (Directory.Exists(Path.Combine(installRoot, "v3.0")))
{
major = 3;
minor = 0;
}
}
}
}
else if (major == 4 && Type.GetType("System.Reflection.AssemblyMetadataAttribute") != null)
{
minor = 5;
}
currentFramework = new RuntimeFramework(runtime, new Version(major, minor));
currentFramework.ClrVersion = Environment.Version;
if (isMono)
{
MethodInfo getDisplayNameMethod = monoRuntimeType.GetMethod(
"GetDisplayName", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.DeclaredOnly | BindingFlags.ExactBinding);
if (getDisplayNameMethod != null)
currentFramework.DisplayName = (string)getDisplayNameMethod.Invoke(null, new object[0]);
}
}
return currentFramework;
}
}
/// <summary>
/// Gets an array of all available frameworks
/// </summary>
// TODO: Special handling for netcf
public static RuntimeFramework[] AvailableFrameworks
{
get
{
if (availableFrameworks == null)
{
List<RuntimeFramework> frameworks = new List<RuntimeFramework>();
AppendDotNetFrameworks(frameworks);
AppendDefaultMonoFramework(frameworks);
// NYI
//AppendMonoFrameworks(frameworks);
availableFrameworks = frameworks.ToArray();
}
return availableFrameworks;
}
}
/// <summary>
/// Returns true if the current RuntimeFramework is available.
/// In the current implementation, only Mono and Microsoft .NET
/// are supported.
/// </summary>
/// <returns>True if it's available, false if not</returns>
public bool IsAvailable
{
get
{
foreach (RuntimeFramework framework in AvailableFrameworks)
if (framework.Supports(this))
return true;
return false;
}
}
/// <summary>
/// The type of this runtime framework
/// </summary>
public RuntimeType Runtime { get; private set; }
/// <summary>
/// The framework version for this runtime framework
/// </summary>
public Version FrameworkVersion { get; private set; }
/// <summary>
/// The CLR version for this runtime framework
/// </summary>
public Version ClrVersion { get; private set; }
/// <summary>
/// Return true if any CLR version may be used in
/// matching this RuntimeFramework object.
/// </summary>
public bool AllowAnyVersion
{
get { return this.ClrVersion == DefaultVersion; }
}
/// <summary>
/// Returns the Display name for this framework
/// </summary>
public string DisplayName { get; private set; }
#endregion
#region Public Methods
/// <summary>
/// Parses a string representing a RuntimeFramework.
/// The string may be just a RuntimeType name or just
/// a Version or a hyphenated RuntimeType-Version or
/// a Version prefixed by 'v'.
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static RuntimeFramework Parse(string s)
{
RuntimeType runtime = RuntimeType.Any;
Version version = DefaultVersion;
string[] parts = s.Split(new char[] { '-' });
if (parts.Length == 2)
{
runtime = (RuntimeType)System.Enum.Parse(typeof(RuntimeType), parts[0], true);
string vstring = parts[1];
if (vstring != "")
version = new Version(vstring);
}
else if (char.ToLower(s[0]) == 'v')
{
version = new Version(s.Substring(1));
}
else if (IsRuntimeTypeName(s))
{
runtime = (RuntimeType)System.Enum.Parse(typeof(RuntimeType), s, true);
}
else
{
version = new Version(s);
}
return new RuntimeFramework(runtime, version);
}
/// <summary>
/// Returns the best available framework that matches a target framework.
/// If the target framework has a build number specified, then an exact
/// match is needed. Otherwise, the matching framework with the highest
/// build number is used.
/// </summary>
/// <param name="target"></param>
/// <returns></returns>
public static RuntimeFramework GetBestAvailableFramework(RuntimeFramework target)
{
RuntimeFramework result = target;
if (target.ClrVersion.Build < 0)
{
foreach (RuntimeFramework framework in AvailableFrameworks)
if (framework.Supports(target) &&
framework.ClrVersion.Build > result.ClrVersion.Build)
{
result = framework;
}
}
return result;
}
/// <summary>
/// Overridden to return the short name of the framework
/// </summary>
/// <returns></returns>
public override string ToString()
{
if (this.AllowAnyVersion)
{
return Runtime.ToString().ToLower();
}
else
{
string vstring = FrameworkVersion.ToString();
if (Runtime == RuntimeType.Any)
return "v" + vstring;
else
return Runtime.ToString().ToLower() + "-" + vstring;
}
}
/// <summary>
/// Returns true if the current framework matches the
/// one supplied as an argument. Two frameworks match
/// if their runtime types are the same or either one
/// is RuntimeType.Any and all specified version components
/// are equal. Negative (i.e. unspecified) version
/// components are ignored.
/// </summary>
/// <param name="target">The RuntimeFramework to be matched.</param>
/// <returns><c>true</c> on match, otherwise <c>false</c></returns>
public bool Supports(RuntimeFramework target)
{
if (this.Runtime != RuntimeType.Any
&& target.Runtime != RuntimeType.Any
&& this.Runtime != target.Runtime)
return false;
if (this.AllowAnyVersion || target.AllowAnyVersion)
return true;
return VersionsMatch(this.ClrVersion, target.ClrVersion)
&& this.FrameworkVersion.Major >= target.FrameworkVersion.Major
&& this.FrameworkVersion.Minor >= target.FrameworkVersion.Minor;
}
#endregion
#region Helper Methods
private static bool IsRuntimeTypeName(string name)
{
foreach (string item in Enum.GetNames(typeof(RuntimeType)))
if (item.ToLower() == name.ToLower())
return true;
return false;
}
private static string GetDefaultDisplayName(RuntimeType runtime, Version version)
{
if (version == DefaultVersion)
return runtime.ToString();
else if (runtime == RuntimeType.Any)
return "v" + version.ToString();
else
return runtime.ToString() + " " + version.ToString();
}
private static bool VersionsMatch(Version v1, Version v2)
{
return v1.Major == v2.Major &&
v1.Minor == v2.Minor &&
(v1.Build < 0 || v2.Build < 0 || v1.Build == v2.Build) &&
(v1.Revision < 0 || v2.Revision < 0 || v1.Revision == v2.Revision);
}
private static void AppendMonoFrameworks(List<RuntimeFramework> frameworks)
{
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
AppendAllMonoFrameworks(frameworks);
else
AppendDefaultMonoFramework(frameworks);
}
private static void AppendAllMonoFrameworks(List<RuntimeFramework> frameworks)
{
// TODO: Find multiple installed Mono versions under Linux
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
{
// Use registry to find alternate versions
RegistryKey key = Registry.LocalMachine.OpenSubKey(@"Software\Novell\Mono");
if (key == null) return;
foreach (string version in key.GetSubKeyNames())
{
RegistryKey subKey = key.OpenSubKey(version);
if (subKey == null) continue;
string monoPrefix = subKey.GetValue("SdkInstallRoot") as string;
AppendMonoFramework(frameworks, monoPrefix, version);
}
}
else
AppendDefaultMonoFramework(frameworks);
}
// This method works for Windows and Linux but currently
// is only called under Linux.
private static void AppendDefaultMonoFramework(List<RuntimeFramework> frameworks)
{
string monoPrefix = null;
string version = null;
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
{
RegistryKey key = Registry.LocalMachine.OpenSubKey(@"Software\Novell\Mono");
if (key != null)
{
version = key.GetValue("DefaultCLR") as string;
if (version != null && version != "")
{
key = key.OpenSubKey(version);
if (key != null)
monoPrefix = key.GetValue("SdkInstallRoot") as string;
}
}
}
else // Assuming we're currently running Mono - change if more runtimes are added
{
string libMonoDir = Path.GetDirectoryName(typeof(object).Assembly.Location);
monoPrefix = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(libMonoDir)));
}
AppendMonoFramework(frameworks, monoPrefix, version);
}
private static void AppendMonoFramework(List<RuntimeFramework> frameworks, string monoPrefix, string version)
{
if (monoPrefix != null)
{
string displayFmt = version != null
? "Mono " + version + " - {0} Profile"
: "Mono {0} Profile";
if (File.Exists(Path.Combine(monoPrefix, "lib/mono/1.0/mscorlib.dll")))
{
RuntimeFramework framework = new RuntimeFramework(RuntimeType.Mono, new Version(1, 1, 4322));
framework.DisplayName = string.Format(displayFmt, "1.0");
frameworks.Add(framework);
}
if (File.Exists(Path.Combine(monoPrefix, "lib/mono/2.0/mscorlib.dll")))
{
RuntimeFramework framework = new RuntimeFramework(RuntimeType.Mono, new Version(2, 0, 50727));
framework.DisplayName = string.Format(displayFmt, "2.0");
frameworks.Add(framework);
}
if (Directory.Exists(Path.Combine(monoPrefix, "lib/mono/3.5")))
{
RuntimeFramework framework = new RuntimeFramework(RuntimeType.Mono, new Version(2, 0, 50727));
framework.FrameworkVersion = new Version(3,5);
framework.DisplayName = string.Format(displayFmt, "3.5");
frameworks.Add(framework);
}
if (File.Exists(Path.Combine(monoPrefix, "lib/mono/4.0/mscorlib.dll")))
{
RuntimeFramework framework = new RuntimeFramework(RuntimeType.Mono, new Version(4, 0, 30319));
framework.DisplayName = string.Format(displayFmt, "4.0");
frameworks.Add(framework);
}
if (File.Exists(Path.Combine(monoPrefix, "lib/mono/4.5/mscorlib.dll")))
{
RuntimeFramework framework = new RuntimeFramework(RuntimeType.Mono, new Version(4, 0, 30319));
framework.FrameworkVersion = new Version(4,5);
framework.DisplayName = string.Format(displayFmt, "4.5");
frameworks.Add(framework);
}
}
}
private static void AppendDotNetFrameworks(List<RuntimeFramework> frameworks)
{
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
{
// Handle Version 1.0, using a different registry key
AppendExtremelyOldDotNetFrameworkVersions(frameworks);
RegistryKey key = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\NET Framework Setup\NDP");
if (key != null)
{
foreach (string name in key.GetSubKeyNames())
{
if (name.StartsWith("v"))
{
var versionKey = key.OpenSubKey(name);
if (versionKey == null) continue;
if (name.StartsWith("v4", StringComparison.Ordinal))
// Version 4 and 4.5
AppendDotNetFourFrameworkVersions(frameworks, versionKey);
else
// Versions 1.1 through 3.5
AppendOlderDotNetFrameworkVersion(frameworks, versionKey, new Version(name.Substring(1)));
}
}
}
}
}
private static void AppendExtremelyOldDotNetFrameworkVersions(List<RuntimeFramework> frameworks)
{
RegistryKey key = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\.NETFramework\policy\v1.0");
if (key != null)
foreach (string build in key.GetValueNames())
frameworks.Add(new RuntimeFramework(RuntimeType.Net, new Version("1.0." + build)));
}
private static void AppendOlderDotNetFrameworkVersion(List<RuntimeFramework> frameworks, RegistryKey versionKey, Version version)
{
if (CheckInstallDword(versionKey))
frameworks.Add(new RuntimeFramework(RuntimeType.Net, version));
}
// Note: this method cannot be generalized past V4, because (a) it has
// specific code for detecting .NET 4.5 and (b) we don't know what
// microsoft will do in the future
private static void AppendDotNetFourFrameworkVersions(List<RuntimeFramework> frameworks, RegistryKey versionKey)
{
foreach (string profile in new string[] { "Full", "Client" })
{
var profileKey = versionKey.OpenSubKey(profile);
if (profileKey == null) continue;
if (CheckInstallDword(profileKey))
{
var framework = new RuntimeFramework(RuntimeType.Net, new Version(4, 0));
framework.DisplayName += " - " + profile;
frameworks.Add(framework);
var release = (int)profileKey.GetValue("Release", 0);
if (release > 0)
{
framework = new RuntimeFramework(RuntimeType.Net, new Version(4, 5));
framework.DisplayName += " - " + profile;
frameworks.Add(framework);
}
}
}
}
private static bool CheckInstallDword(RegistryKey key)
{
return ((int)key.GetValue("Install", 0) == 1);
}
#endregion
}
}
| |
/*
* Copyright (c) 2007-2008, openmetaverse.org
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the openmetaverse.org nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/*
*
* This implementation is based upon the description at
*
* http://wiki.secondlife.com/wiki/LLSD
*
* and (partially) tested against the (supposed) reference implementation at
*
* http://svn.secondlife.com/svn/linden/release/indra/lib/python/indra/base/osd.py
*
*/
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace OpenMetaverse.StructuredData
{
/// <summary>
///
/// </summary>
public static partial class OSDParser
{
private const int initialBufferSize = 128;
private const int int32Length = 4;
private const int doubleLength = 8;
private const string llsdBinaryHead = "<? llsd/binary ?>";
private const string llsdBinaryHead2 = "<?llsd/binary?>";
private const byte undefBinaryValue = (byte)'!';
private const byte trueBinaryValue = (byte)'1';
private const byte falseBinaryValue = (byte)'0';
private const byte integerBinaryMarker = (byte)'i';
private const byte realBinaryMarker = (byte)'r';
private const byte uuidBinaryMarker = (byte)'u';
private const byte binaryBinaryMarker = (byte)'b';
private const byte stringBinaryMarker = (byte)'s';
private const byte uriBinaryMarker = (byte)'l';
private const byte dateBinaryMarker = (byte)'d';
private const byte arrayBeginBinaryMarker = (byte)'[';
private const byte arrayEndBinaryMarker = (byte)']';
private const byte mapBeginBinaryMarker = (byte)'{';
private const byte mapEndBinaryMarker = (byte)'}';
private const byte keyBinaryMarker = (byte)'k';
private static readonly byte[] llsdBinaryHeadBytes = Encoding.ASCII.GetBytes(llsdBinaryHead2);
/// <summary>
/// Deserializes binary LLSD
/// </summary>
/// <param name="binaryData">Serialized data</param>
/// <returns>OSD containting deserialized data</returns>
public static OSD DeserializeLLSDBinary(byte[] binaryData)
{
MemoryStream stream = new MemoryStream(binaryData);
OSD osd = DeserializeLLSDBinary(stream);
stream.Close();
return osd;
}
/// <summary>
/// Deserializes binary LLSD
/// </summary>
/// <param name="stream">Stream to read the data from</param>
/// <returns>OSD containting deserialized data</returns>
public static OSD DeserializeLLSDBinary(Stream stream)
{
if (!stream.CanSeek)
throw new OSDException("Cannot deserialize binary LLSD from unseekable streams");
SkipWhiteSpace(stream);
if (!FindString(stream, llsdBinaryHead) && !FindString(stream, llsdBinaryHead2))
{
//throw new OSDException("Failed to decode binary LLSD");
}
SkipWhiteSpace(stream);
return ParseLLSDBinaryElement(stream);
}
/// <summary>
/// Serializes OSD to binary format. It does no prepend header
/// </summary>
/// <param name="osd">OSD to serialize</param>
/// <returns>Serialized data</returns>
public static byte[] SerializeLLSDBinary(OSD osd)
{
return SerializeLLSDBinary(osd, true);
}
/// <summary>
/// Serializes OSD to binary format
/// </summary>
/// <param name="osd">OSD to serialize</param>
/// <param name="prependHeader"></param>
/// <returns>Serialized data</returns>
public static byte[] SerializeLLSDBinary(OSD osd, bool prependHeader)
{
MemoryStream stream = SerializeLLSDBinaryStream(osd, prependHeader);
byte[] binaryData = stream.ToArray();
stream.Close();
return binaryData;
}
/// <summary>
/// Serializes OSD to binary format. It does no prepend header
/// </summary>
/// <param name="data">OSD to serialize</param>
/// <returns>Serialized data</returns>
public static MemoryStream SerializeLLSDBinaryStream(OSD data)
{
return SerializeLLSDBinaryStream(data, true);
}
/// <summary>
/// Serializes OSD to binary format
/// </summary>
/// <param name="data">OSD to serialize</param>
/// <param name="prependHeader"></param>
/// <returns>Serialized data</returns>
public static MemoryStream SerializeLLSDBinaryStream(OSD data, bool prependHeader)
{
MemoryStream stream = new MemoryStream(initialBufferSize);
if (prependHeader)
{
stream.Write(llsdBinaryHeadBytes, 0, llsdBinaryHeadBytes.Length);
stream.WriteByte((byte)'\n');
}
SerializeLLSDBinaryElement(stream, data);
return stream;
}
private static void SerializeLLSDBinaryElement(MemoryStream stream, OSD osd)
{
switch (osd.Type)
{
case OSDType.Unknown:
stream.WriteByte(undefBinaryValue);
break;
case OSDType.Boolean:
stream.Write(osd.AsBinary(), 0, 1);
break;
case OSDType.Integer:
stream.WriteByte(integerBinaryMarker);
stream.Write(osd.AsBinary(), 0, int32Length);
break;
case OSDType.Real:
stream.WriteByte(realBinaryMarker);
stream.Write(osd.AsBinary(), 0, doubleLength);
break;
case OSDType.UUID:
stream.WriteByte(uuidBinaryMarker);
stream.Write(osd.AsBinary(), 0, 16);
break;
case OSDType.String:
stream.WriteByte(stringBinaryMarker);
byte[] rawString = osd.AsBinary();
byte[] stringLengthNetEnd = HostToNetworkIntBytes(rawString.Length);
stream.Write(stringLengthNetEnd, 0, int32Length);
stream.Write(rawString, 0, rawString.Length);
break;
case OSDType.Binary:
stream.WriteByte(binaryBinaryMarker);
byte[] rawBinary = osd.AsBinary();
byte[] binaryLengthNetEnd = HostToNetworkIntBytes(rawBinary.Length);
stream.Write(binaryLengthNetEnd, 0, int32Length);
stream.Write(rawBinary, 0, rawBinary.Length);
break;
case OSDType.Date:
stream.WriteByte(dateBinaryMarker);
stream.Write(osd.AsBinary(), 0, doubleLength);
break;
case OSDType.URI:
stream.WriteByte(uriBinaryMarker);
byte[] rawURI = osd.AsBinary();
byte[] uriLengthNetEnd = HostToNetworkIntBytes(rawURI.Length);
stream.Write(uriLengthNetEnd, 0, int32Length);
stream.Write(rawURI, 0, rawURI.Length);
break;
case OSDType.Array:
SerializeLLSDBinaryArray(stream, (OSDArray)osd);
break;
case OSDType.Map:
SerializeLLSDBinaryMap(stream, (OSDMap)osd);
break;
default:
throw new OSDException("Binary serialization: Not existing element discovered.");
}
}
private static void SerializeLLSDBinaryArray(MemoryStream stream, OSDArray osdArray)
{
stream.WriteByte(arrayBeginBinaryMarker);
byte[] binaryNumElementsHostEnd = HostToNetworkIntBytes(osdArray.Count);
stream.Write(binaryNumElementsHostEnd, 0, int32Length);
foreach (OSD osd in osdArray)
{
SerializeLLSDBinaryElement(stream, osd);
}
stream.WriteByte(arrayEndBinaryMarker);
}
private static void SerializeLLSDBinaryMap(MemoryStream stream, OSDMap osdMap)
{
stream.WriteByte(mapBeginBinaryMarker);
byte[] binaryNumElementsNetEnd = HostToNetworkIntBytes(osdMap.Count);
stream.Write(binaryNumElementsNetEnd, 0, int32Length);
foreach (KeyValuePair<string, OSD> kvp in osdMap)
{
stream.WriteByte(keyBinaryMarker);
byte[] binaryKey = Encoding.UTF8.GetBytes(kvp.Key);
byte[] binaryKeyLength = HostToNetworkIntBytes(binaryKey.Length);
stream.Write(binaryKeyLength, 0, int32Length);
stream.Write(binaryKey, 0, binaryKey.Length);
SerializeLLSDBinaryElement(stream, kvp.Value);
}
stream.WriteByte(mapEndBinaryMarker);
}
private static OSD ParseLLSDBinaryElement(Stream stream)
{
SkipWhiteSpace(stream);
OSD osd;
int marker = stream.ReadByte();
if (marker < 0)
throw new OSDException("Binary LLSD parsing: Unexpected end of stream.");
switch ((byte)marker)
{
case undefBinaryValue:
osd = new OSD();
break;
case trueBinaryValue:
osd = OSD.FromBoolean(true);
break;
case falseBinaryValue:
osd = OSD.FromBoolean(false);
break;
case integerBinaryMarker:
int integer = NetworkToHostInt(ConsumeBytes(stream, int32Length));
osd = OSD.FromInteger(integer);
break;
case realBinaryMarker:
double dbl = NetworkToHostDouble(ConsumeBytes(stream, doubleLength));
osd = OSD.FromReal(dbl);
break;
case uuidBinaryMarker:
osd = OSD.FromUUID(new UUID(ConsumeBytes(stream, 16), 0));
break;
case binaryBinaryMarker:
int binaryLength = NetworkToHostInt(ConsumeBytes(stream, int32Length));
osd = OSD.FromBinary(ConsumeBytes(stream, binaryLength));
break;
case stringBinaryMarker:
int stringLength = NetworkToHostInt(ConsumeBytes(stream, int32Length));
string ss = Encoding.UTF8.GetString(ConsumeBytes(stream, stringLength));
osd = OSD.FromString(ss);
break;
case uriBinaryMarker:
int uriLength = NetworkToHostInt(ConsumeBytes(stream, int32Length));
string sUri = Encoding.UTF8.GetString(ConsumeBytes(stream, uriLength));
Uri uri;
try
{
uri = new Uri(sUri, UriKind.RelativeOrAbsolute);
}
catch
{
throw new OSDException("Binary LLSD parsing: Invalid Uri format detected.");
}
osd = OSD.FromUri(uri);
break;
case dateBinaryMarker:
double timestamp = Utils.BytesToDouble(ConsumeBytes(stream, doubleLength), 0);
DateTime dateTime = DateTime.SpecifyKind(Utils.Epoch, DateTimeKind.Utc);
dateTime = dateTime.AddSeconds(timestamp);
osd = OSD.FromDate(dateTime.ToLocalTime());
break;
case arrayBeginBinaryMarker:
osd = ParseLLSDBinaryArray(stream);
break;
case mapBeginBinaryMarker:
osd = ParseLLSDBinaryMap(stream);
break;
default:
throw new OSDException("Binary LLSD parsing: Unknown type marker.");
}
return osd;
}
private static OSD ParseLLSDBinaryArray(Stream stream)
{
int numElements = NetworkToHostInt(ConsumeBytes(stream, int32Length));
int crrElement = 0;
OSDArray osdArray = new OSDArray();
while (crrElement < numElements)
{
osdArray.Add(ParseLLSDBinaryElement(stream));
crrElement++;
}
if (!FindByte(stream, arrayEndBinaryMarker))
throw new OSDException("Binary LLSD parsing: Missing end marker in array.");
return (OSD)osdArray;
}
private static OSD ParseLLSDBinaryMap(Stream stream)
{
int numElements = NetworkToHostInt(ConsumeBytes(stream, int32Length));
int crrElement = 0;
OSDMap osdMap = new OSDMap();
while (crrElement < numElements)
{
if (!FindByte(stream, keyBinaryMarker))
throw new OSDException("Binary LLSD parsing: Missing key marker in map.");
int keyLength = NetworkToHostInt(ConsumeBytes(stream, int32Length));
string key = Encoding.UTF8.GetString(ConsumeBytes(stream, keyLength));
osdMap[key] = ParseLLSDBinaryElement(stream);
crrElement++;
}
if (!FindByte(stream, mapEndBinaryMarker))
throw new OSDException("Binary LLSD parsing: Missing end marker in map.");
return (OSD)osdMap;
}
/// <summary>
///
/// </summary>
/// <param name="stream"></param>
public static void SkipWhiteSpace(Stream stream)
{
int bt;
while (((bt = stream.ReadByte()) > 0) &&
((byte)bt == ' ' || (byte)bt == '\t' ||
(byte)bt == '\n' || (byte)bt == '\r')
)
{
}
stream.Seek(-1, SeekOrigin.Current);
}
/// <summary>
///
/// </summary>
/// <param name="stream"></param>
/// <param name="toFind"></param>
/// <returns></returns>
public static bool FindByte(Stream stream, byte toFind)
{
int bt = stream.ReadByte();
if (bt < 0)
return false;
if ((byte)bt == toFind)
return true;
else
{
stream.Seek(-1L, SeekOrigin.Current);
return false;
}
}
/// <summary>
///
/// </summary>
/// <param name="stream"></param>
/// <param name="toFind"></param>
/// <returns></returns>
public static bool FindString(Stream stream, string toFind)
{
int lastIndexToFind = toFind.Length - 1;
int crrIndex = 0;
bool found = true;
int bt;
long lastPosition = stream.Position;
while (found &&
((bt = stream.ReadByte()) > 0) &&
(crrIndex <= lastIndexToFind)
)
{
if (toFind[crrIndex].ToString().Equals(((char)bt).ToString(), StringComparison.InvariantCultureIgnoreCase))
{
found = true;
crrIndex++;
}
else
found = false;
}
if (found && crrIndex > lastIndexToFind)
{
stream.Seek(-1L, SeekOrigin.Current);
return true;
}
else
{
stream.Position = lastPosition;
return false;
}
}
/// <summary>
///
/// </summary>
/// <param name="stream"></param>
/// <param name="consumeBytes"></param>
/// <returns></returns>
public static byte[] ConsumeBytes(Stream stream, int consumeBytes)
{
byte[] bytes = new byte[consumeBytes];
if (stream.Read(bytes, 0, consumeBytes) < consumeBytes)
throw new OSDException("Binary LLSD parsing: Unexpected end of stream.");
return bytes;
}
/// <summary>
///
/// </summary>
/// <param name="binaryNetEnd"></param>
/// <returns></returns>
public static int NetworkToHostInt(byte[] binaryNetEnd)
{
if (binaryNetEnd == null)
return -1;
int intNetEnd = BitConverter.ToInt32(binaryNetEnd, 0);
int intHostEnd = System.Net.IPAddress.NetworkToHostOrder(intNetEnd);
return intHostEnd;
}
/// <summary>
///
/// </summary>
/// <param name="binaryNetEnd"></param>
/// <returns></returns>
public static double NetworkToHostDouble(byte[] binaryNetEnd)
{
if (binaryNetEnd == null)
return -1d;
long longNetEnd = BitConverter.ToInt64(binaryNetEnd, 0);
long longHostEnd = System.Net.IPAddress.NetworkToHostOrder(longNetEnd);
byte[] binaryHostEnd = BitConverter.GetBytes(longHostEnd);
double doubleHostEnd = BitConverter.ToDouble(binaryHostEnd, 0);
return doubleHostEnd;
}
/// <summary>
///
/// </summary>
/// <param name="intHostEnd"></param>
/// <returns></returns>
public static byte[] HostToNetworkIntBytes(int intHostEnd)
{
int intNetEnd = System.Net.IPAddress.HostToNetworkOrder(intHostEnd);
byte[] bytesNetEnd = BitConverter.GetBytes(intNetEnd);
return bytesNetEnd;
}
}
}
| |
// 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.Diagnostics.Contracts;
using System.Globalization;
using System.Text;
namespace System.Net.Http.Headers
{
public class ContentDispositionHeaderValue : ICloneable
{
#region Fields
private const string fileName = "filename";
private const string name = "name";
private const string fileNameStar = "filename*";
private const string creationDate = "creation-date";
private const string modificationDate = "modification-date";
private const string readDate = "read-date";
private const string size = "size";
// Use ObjectCollection<T> since we may have multiple parameters with the same name.
private ObjectCollection<NameValueHeaderValue> _parameters;
private string _dispositionType;
#endregion Fields
#region Properties
public string DispositionType
{
get { return _dispositionType; }
set
{
CheckDispositionTypeFormat(value, nameof(value));
_dispositionType = value;
}
}
public ICollection<NameValueHeaderValue> Parameters
{
get
{
if (_parameters == null)
{
_parameters = new ObjectCollection<NameValueHeaderValue>();
}
return _parameters;
}
}
public string Name
{
get { return GetName(name); }
set { SetName(name, value); }
}
public string FileName
{
get { return GetName(fileName); }
set { SetName(fileName, value); }
}
public string FileNameStar
{
get { return GetName(fileNameStar); }
set { SetName(fileNameStar, value); }
}
public DateTimeOffset? CreationDate
{
get { return GetDate(creationDate); }
set { SetDate(creationDate, value); }
}
public DateTimeOffset? ModificationDate
{
get { return GetDate(modificationDate); }
set { SetDate(modificationDate, value); }
}
public DateTimeOffset? ReadDate
{
get { return GetDate(readDate); }
set { SetDate(readDate, value); }
}
public long? Size
{
get
{
NameValueHeaderValue sizeParameter = NameValueHeaderValue.Find(_parameters, size);
ulong value;
if (sizeParameter != null)
{
string sizeString = sizeParameter.Value;
if (UInt64.TryParse(sizeString, NumberStyles.Integer, CultureInfo.InvariantCulture, out value))
{
return (long)value;
}
}
return null;
}
set
{
NameValueHeaderValue sizeParameter = NameValueHeaderValue.Find(_parameters, size);
if (value == null)
{
// Remove parameter.
if (sizeParameter != null)
{
_parameters.Remove(sizeParameter);
}
}
else if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
else if (sizeParameter != null)
{
sizeParameter.Value = value.Value.ToString(CultureInfo.InvariantCulture);
}
else
{
string sizeString = value.Value.ToString(CultureInfo.InvariantCulture);
_parameters.Add(new NameValueHeaderValue(size, sizeString));
}
}
}
#endregion Properties
#region Constructors
internal ContentDispositionHeaderValue()
{
// Used by the parser to create a new instance of this type.
}
protected ContentDispositionHeaderValue(ContentDispositionHeaderValue source)
{
Contract.Requires(source != null);
_dispositionType = source._dispositionType;
if (source._parameters != null)
{
foreach (var parameter in source._parameters)
{
this.Parameters.Add((NameValueHeaderValue)((ICloneable)parameter).Clone());
}
}
}
public ContentDispositionHeaderValue(string dispositionType)
{
CheckDispositionTypeFormat(dispositionType, nameof(dispositionType));
_dispositionType = dispositionType;
}
#endregion Constructors
#region Overloads
public override string ToString()
{
return _dispositionType + NameValueHeaderValue.ToString(_parameters, ';', true);
}
public override bool Equals(object obj)
{
ContentDispositionHeaderValue other = obj as ContentDispositionHeaderValue;
if (other == null)
{
return false;
}
return string.Equals(_dispositionType, other._dispositionType, StringComparison.OrdinalIgnoreCase) &&
HeaderUtilities.AreEqualCollections(_parameters, other._parameters);
}
public override int GetHashCode()
{
// The dispositionType string is case-insensitive.
return StringComparer.OrdinalIgnoreCase.GetHashCode(_dispositionType) ^ NameValueHeaderValue.GetHashCode(_parameters);
}
// Implement ICloneable explicitly to allow derived types to "override" the implementation.
object ICloneable.Clone()
{
return new ContentDispositionHeaderValue(this);
}
#endregion Overloads
#region Parsing
public static ContentDispositionHeaderValue Parse(string input)
{
int index = 0;
return (ContentDispositionHeaderValue)GenericHeaderParser.ContentDispositionParser.ParseValue(input,
null, ref index);
}
public static bool TryParse(string input, out ContentDispositionHeaderValue parsedValue)
{
int index = 0;
object output;
parsedValue = null;
if (GenericHeaderParser.ContentDispositionParser.TryParseValue(input, null, ref index, out output))
{
parsedValue = (ContentDispositionHeaderValue)output;
return true;
}
return false;
}
internal static int GetDispositionTypeLength(string input, int startIndex, out object parsedValue)
{
Contract.Requires(startIndex >= 0);
parsedValue = null;
if (string.IsNullOrEmpty(input) || (startIndex >= input.Length))
{
return 0;
}
// Caller must remove leading whitespace. If not, we'll return 0.
string dispositionType = null;
int dispositionTypeLength = GetDispositionTypeExpressionLength(input, startIndex, out dispositionType);
if (dispositionTypeLength == 0)
{
return 0;
}
int current = startIndex + dispositionTypeLength;
current = current + HttpRuleParser.GetWhitespaceLength(input, current);
ContentDispositionHeaderValue contentDispositionHeader = new ContentDispositionHeaderValue();
contentDispositionHeader._dispositionType = dispositionType;
// If we're not done and we have a parameter delimiter, then we have a list of parameters.
if ((current < input.Length) && (input[current] == ';'))
{
current++; // Skip delimiter.
int parameterLength = NameValueHeaderValue.GetNameValueListLength(input, current, ';',
(ObjectCollection<NameValueHeaderValue>)contentDispositionHeader.Parameters);
if (parameterLength == 0)
{
return 0;
}
parsedValue = contentDispositionHeader;
return current + parameterLength - startIndex;
}
// We have a ContentDisposition header without parameters.
parsedValue = contentDispositionHeader;
return current - startIndex;
}
private static int GetDispositionTypeExpressionLength(string input, int startIndex, out string dispositionType)
{
Contract.Requires((input != null) && (input.Length > 0) && (startIndex < input.Length));
// This method just parses the disposition type string, it does not parse parameters.
dispositionType = null;
// Parse the disposition type, i.e. <dispositiontype> in content-disposition string
// "<dispositiontype>; param1=value1; param2=value2".
int typeLength = HttpRuleParser.GetTokenLength(input, startIndex);
if (typeLength == 0)
{
return 0;
}
dispositionType = input.Substring(startIndex, typeLength);
return typeLength;
}
private static void CheckDispositionTypeFormat(string dispositionType, string parameterName)
{
if (string.IsNullOrEmpty(dispositionType))
{
throw new ArgumentException(SR.net_http_argument_empty_string, parameterName);
}
// When adding values using strongly typed objects, no leading/trailing LWS (whitespace) are allowed.
string tempDispositionType;
int dispositionTypeLength = GetDispositionTypeExpressionLength(dispositionType, 0, out tempDispositionType);
if ((dispositionTypeLength == 0) || (tempDispositionType.Length != dispositionType.Length))
{
throw new FormatException(string.Format(System.Globalization.CultureInfo.InvariantCulture,
SR.net_http_headers_invalid_value, dispositionType));
}
}
#endregion Parsing
#region Helpers
// Gets a parameter of the given name and attempts to extract a date.
// Returns null if the parameter is not present or the format is incorrect.
private DateTimeOffset? GetDate(string parameter)
{
NameValueHeaderValue dateParameter = NameValueHeaderValue.Find(_parameters, parameter);
DateTimeOffset date;
if (dateParameter != null)
{
string dateString = dateParameter.Value;
// Should have quotes, remove them.
if (IsQuoted(dateString))
{
dateString = dateString.Substring(1, dateString.Length - 2);
}
if (HttpRuleParser.TryStringToDate(dateString, out date))
{
return date;
}
}
return null;
}
// Add the given parameter to the list. Remove if date is null.
private void SetDate(string parameter, DateTimeOffset? date)
{
NameValueHeaderValue dateParameter = NameValueHeaderValue.Find(_parameters, parameter);
if (date == null)
{
// Remove parameter.
if (dateParameter != null)
{
_parameters.Remove(dateParameter);
}
}
else
{
// Must always be quoted.
string dateString = string.Format(CultureInfo.InvariantCulture, "\"{0}\"",
HttpRuleParser.DateToString(date.Value));
if (dateParameter != null)
{
dateParameter.Value = dateString;
}
else
{
Parameters.Add(new NameValueHeaderValue(parameter, dateString));
}
}
}
// Gets a parameter of the given name and attempts to decode it if necessary.
// Returns null if the parameter is not present or the raw value if the encoding is incorrect.
private string GetName(string parameter)
{
NameValueHeaderValue nameParameter = NameValueHeaderValue.Find(_parameters, parameter);
if (nameParameter != null)
{
string result;
// filename*=utf-8'lang'%7FMyString
if (parameter.EndsWith("*", StringComparison.Ordinal))
{
if (TryDecode5987(nameParameter.Value, out result))
{
return result;
}
return null; // Unrecognized encoding.
}
// filename="=?utf-8?B?BDFSDFasdfasdc==?="
if (TryDecodeMime(nameParameter.Value, out result))
{
return result;
}
// May not have been encoded.
return nameParameter.Value;
}
return null;
}
// Add/update the given parameter in the list, encoding if necessary.
// Remove if value is null/Empty
private void SetName(string parameter, string value)
{
NameValueHeaderValue nameParameter = NameValueHeaderValue.Find(_parameters, parameter);
if (string.IsNullOrEmpty(value))
{
// Remove parameter.
if (nameParameter != null)
{
_parameters.Remove(nameParameter);
}
}
else
{
string processedValue = string.Empty;
if (parameter.EndsWith("*", StringComparison.Ordinal))
{
processedValue = Encode5987(value);
}
else
{
processedValue = EncodeAndQuoteMime(value);
}
if (nameParameter != null)
{
nameParameter.Value = processedValue;
}
else
{
Parameters.Add(new NameValueHeaderValue(parameter, processedValue));
}
}
}
// Returns input for decoding failures, as the content might not be encoded.
private string EncodeAndQuoteMime(string input)
{
string result = input;
bool needsQuotes = false;
// Remove bounding quotes, they'll get re-added later.
if (IsQuoted(result))
{
result = result.Substring(1, result.Length - 2);
needsQuotes = true;
}
if (result.IndexOf("\"", 0, StringComparison.Ordinal) >= 0) // Only bounding quotes are allowed.
{
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
SR.net_http_headers_invalid_value, input));
}
else if (RequiresEncoding(result))
{
needsQuotes = true; // Encoded data must always be quoted, the equals signs are invalid in tokens.
result = EncodeMime(result); // =?utf-8?B?asdfasdfaesdf?=
}
else if (!needsQuotes && HttpRuleParser.GetTokenLength(result, 0) != result.Length)
{
needsQuotes = true;
}
if (needsQuotes)
{
// Re-add quotes "value".
result = string.Format(CultureInfo.InvariantCulture, "\"{0}\"", result);
}
return result;
}
// Returns true if the value starts and ends with a quote.
private bool IsQuoted(string value)
{
Debug.Assert(value != null);
return value.Length > 1 && value.StartsWith("\"", StringComparison.Ordinal)
&& value.EndsWith("\"", StringComparison.Ordinal);
}
// tspecials are required to be in a quoted string. Only non-ascii needs to be encoded.
private bool RequiresEncoding(string input)
{
Debug.Assert(input != null);
foreach (char c in input)
{
if ((int)c > 0x7f)
{
return true;
}
}
return false;
}
// Encode using MIME encoding.
private string EncodeMime(string input)
{
byte[] buffer = Encoding.UTF8.GetBytes(input);
string encodedName = Convert.ToBase64String(buffer);
return string.Format(CultureInfo.InvariantCulture, "=?utf-8?B?{0}?=", encodedName);
}
// Attempt to decode MIME encoded strings.
private bool TryDecodeMime(string input, out string output)
{
Debug.Assert(input != null);
output = null;
string processedInput = input;
// Require quotes, min of "=?e?b??="
if (!IsQuoted(processedInput) || processedInput.Length < 10)
{
return false;
}
string[] parts = processedInput.Split('?');
// "=, encodingName, encodingType, encodedData, ="
if (parts.Length != 5 || parts[0] != "\"=" || parts[4] != "=\"" || parts[2].ToLowerInvariant() != "b")
{
// Not encoded.
// This does not support multi-line encoding.
// Only base64 encoding is supported, not quoted printable.
return false;
}
try
{
Encoding encoding = Encoding.GetEncoding(parts[1]);
byte[] bytes = Convert.FromBase64String(parts[3]);
output = encoding.GetString(bytes, 0, bytes.Length);
return true;
}
catch (ArgumentException)
{
// Unknown encoding or bad characters.
}
catch (FormatException)
{
// Bad base64 decoding.
}
return false;
}
// Encode a string using RFC 5987 encoding.
// encoding'lang'PercentEncodedSpecials
private string Encode5987(string input)
{
StringBuilder builder = new StringBuilder("utf-8\'\'");
foreach (char c in input)
{
// attr-char = ALPHA / DIGIT / "!" / "#" / "$" / "&" / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
// ; token except ( "*" / "'" / "%" )
if (c > 0x7F) // Encodes as multiple utf-8 bytes
{
byte[] bytes = Encoding.UTF8.GetBytes(c.ToString());
foreach (byte b in bytes)
{
builder.Append(UriShim.HexEscape((char)b));
}
}
else if (!HttpRuleParser.IsTokenChar(c) || c == '*' || c == '\'' || c == '%')
{
// ASCII - Only one encoded byte.
builder.Append(UriShim.HexEscape(c));
}
else
{
builder.Append(c);
}
}
return builder.ToString();
}
// Attempt to decode using RFC 5987 encoding.
// encoding'language'my%20string
private bool TryDecode5987(string input, out string output)
{
output = null;
int quoteIndex = input.IndexOf('\'');
if (quoteIndex == -1)
{
return false;
}
int lastQuoteIndex = input.LastIndexOf('\'');
if (quoteIndex == lastQuoteIndex || input.IndexOf('\'', quoteIndex + 1) != lastQuoteIndex)
{
return false;
}
string encodingString = input.Substring(0, quoteIndex);
string dataString = input.Substring(lastQuoteIndex + 1, input.Length - (lastQuoteIndex + 1));
StringBuilder decoded = new StringBuilder();
try
{
Encoding encoding = Encoding.GetEncoding(encodingString);
byte[] unescapedBytes = new byte[dataString.Length];
int unescapedBytesCount = 0;
for (int index = 0; index < dataString.Length; index++)
{
if (UriShim.IsHexEncoding(dataString, index)) // %FF
{
// Unescape and cache bytes, multi-byte characters must be decoded all at once.
unescapedBytes[unescapedBytesCount++] = (byte)UriShim.HexUnescape(dataString, ref index);
index--; // HexUnescape did +=3; Offset the for loop's ++
}
else
{
if (unescapedBytesCount > 0)
{
// Decode any previously cached bytes.
decoded.Append(encoding.GetString(unescapedBytes, 0, unescapedBytesCount));
unescapedBytesCount = 0;
}
decoded.Append(dataString[index]); // Normal safe character.
}
}
if (unescapedBytesCount > 0)
{
// Decode any previously cached bytes.
decoded.Append(encoding.GetString(unescapedBytes, 0, unescapedBytesCount));
}
}
catch (ArgumentException)
{
return false; // Unknown encoding or bad characters.
}
output = decoded.ToString();
return true;
}
#endregion Helpers
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagr = Google.Api.Gax.ResourceNames;
using gcav = Google.Cloud.AIPlatform.V1;
namespace Google.Cloud.AIPlatform.V1
{
public partial class CreateCustomJobRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class GetCustomJobRequest
{
/// <summary>
/// <see cref="gcav::CustomJobName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcav::CustomJobName CustomJobName
{
get => string.IsNullOrEmpty(Name) ? null : gcav::CustomJobName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class ListCustomJobsRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class DeleteCustomJobRequest
{
/// <summary>
/// <see cref="gcav::CustomJobName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcav::CustomJobName CustomJobName
{
get => string.IsNullOrEmpty(Name) ? null : gcav::CustomJobName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class CancelCustomJobRequest
{
/// <summary>
/// <see cref="gcav::CustomJobName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcav::CustomJobName CustomJobName
{
get => string.IsNullOrEmpty(Name) ? null : gcav::CustomJobName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class CreateDataLabelingJobRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class GetDataLabelingJobRequest
{
/// <summary>
/// <see cref="gcav::DataLabelingJobName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcav::DataLabelingJobName DataLabelingJobName
{
get => string.IsNullOrEmpty(Name) ? null : gcav::DataLabelingJobName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class ListDataLabelingJobsRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class DeleteDataLabelingJobRequest
{
/// <summary>
/// <see cref="gcav::DataLabelingJobName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcav::DataLabelingJobName DataLabelingJobName
{
get => string.IsNullOrEmpty(Name) ? null : gcav::DataLabelingJobName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class CancelDataLabelingJobRequest
{
/// <summary>
/// <see cref="gcav::DataLabelingJobName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcav::DataLabelingJobName DataLabelingJobName
{
get => string.IsNullOrEmpty(Name) ? null : gcav::DataLabelingJobName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class CreateHyperparameterTuningJobRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class GetHyperparameterTuningJobRequest
{
/// <summary>
/// <see cref="gcav::HyperparameterTuningJobName"/>-typed view over the <see cref="Name"/> resource name
/// property.
/// </summary>
public gcav::HyperparameterTuningJobName HyperparameterTuningJobName
{
get => string.IsNullOrEmpty(Name) ? null : gcav::HyperparameterTuningJobName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class ListHyperparameterTuningJobsRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class DeleteHyperparameterTuningJobRequest
{
/// <summary>
/// <see cref="gcav::HyperparameterTuningJobName"/>-typed view over the <see cref="Name"/> resource name
/// property.
/// </summary>
public gcav::HyperparameterTuningJobName HyperparameterTuningJobName
{
get => string.IsNullOrEmpty(Name) ? null : gcav::HyperparameterTuningJobName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class CancelHyperparameterTuningJobRequest
{
/// <summary>
/// <see cref="gcav::HyperparameterTuningJobName"/>-typed view over the <see cref="Name"/> resource name
/// property.
/// </summary>
public gcav::HyperparameterTuningJobName HyperparameterTuningJobName
{
get => string.IsNullOrEmpty(Name) ? null : gcav::HyperparameterTuningJobName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class CreateBatchPredictionJobRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class GetBatchPredictionJobRequest
{
/// <summary>
/// <see cref="gcav::BatchPredictionJobName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcav::BatchPredictionJobName BatchPredictionJobName
{
get => string.IsNullOrEmpty(Name) ? null : gcav::BatchPredictionJobName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class ListBatchPredictionJobsRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class DeleteBatchPredictionJobRequest
{
/// <summary>
/// <see cref="gcav::BatchPredictionJobName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcav::BatchPredictionJobName BatchPredictionJobName
{
get => string.IsNullOrEmpty(Name) ? null : gcav::BatchPredictionJobName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class CancelBatchPredictionJobRequest
{
/// <summary>
/// <see cref="gcav::BatchPredictionJobName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcav::BatchPredictionJobName BatchPredictionJobName
{
get => string.IsNullOrEmpty(Name) ? null : gcav::BatchPredictionJobName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class CreateModelDeploymentMonitoringJobRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class SearchModelDeploymentMonitoringStatsAnomaliesRequest
{
/// <summary>
/// <see cref="ModelDeploymentMonitoringJobName"/>-typed view over the
/// <see cref="ModelDeploymentMonitoringJob"/> resource name property.
/// </summary>
public ModelDeploymentMonitoringJobName ModelDeploymentMonitoringJobAsModelDeploymentMonitoringJobName
{
get => string.IsNullOrEmpty(ModelDeploymentMonitoringJob) ? null : ModelDeploymentMonitoringJobName.Parse(ModelDeploymentMonitoringJob, allowUnparsed: true);
set => ModelDeploymentMonitoringJob = value?.ToString() ?? "";
}
}
public partial class GetModelDeploymentMonitoringJobRequest
{
/// <summary>
/// <see cref="gcav::ModelDeploymentMonitoringJobName"/>-typed view over the <see cref="Name"/> resource name
/// property.
/// </summary>
public gcav::ModelDeploymentMonitoringJobName ModelDeploymentMonitoringJobName
{
get => string.IsNullOrEmpty(Name) ? null : gcav::ModelDeploymentMonitoringJobName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class ListModelDeploymentMonitoringJobsRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class DeleteModelDeploymentMonitoringJobRequest
{
/// <summary>
/// <see cref="gcav::ModelDeploymentMonitoringJobName"/>-typed view over the <see cref="Name"/> resource name
/// property.
/// </summary>
public gcav::ModelDeploymentMonitoringJobName ModelDeploymentMonitoringJobName
{
get => string.IsNullOrEmpty(Name) ? null : gcav::ModelDeploymentMonitoringJobName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class PauseModelDeploymentMonitoringJobRequest
{
/// <summary>
/// <see cref="gcav::ModelDeploymentMonitoringJobName"/>-typed view over the <see cref="Name"/> resource name
/// property.
/// </summary>
public gcav::ModelDeploymentMonitoringJobName ModelDeploymentMonitoringJobName
{
get => string.IsNullOrEmpty(Name) ? null : gcav::ModelDeploymentMonitoringJobName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class ResumeModelDeploymentMonitoringJobRequest
{
/// <summary>
/// <see cref="gcav::ModelDeploymentMonitoringJobName"/>-typed view over the <see cref="Name"/> resource name
/// property.
/// </summary>
public gcav::ModelDeploymentMonitoringJobName ModelDeploymentMonitoringJobName
{
get => string.IsNullOrEmpty(Name) ? null : gcav::ModelDeploymentMonitoringJobName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Threading;
using Debug = System.Diagnostics.Debug;
namespace Internal.TypeSystem
{
/// <summary>
/// A hash table which is lock free for readers and up to 1 writer at a time.
/// It must be possible to compute the key's hashcode from a value.
/// All values must convertable to/from an IntPtr.
/// It must be possible to perform an equality check between a key and a value.
/// It must be possible to perform an equality check between a value and a value.
/// A LockFreeReaderKeyValueComparer must be provided to perform these operations.
/// </summary>
abstract public class LockFreeReaderHashtableOfPointers<TKey, TValue>
{
private const int _initialSize = 16;
private const int _fillPercentageBeforeResize = 60;
/// <summary>
/// _hashtable is the currently visible underlying array for the hashtable
/// Any modifications to this array must be additive only, and there must
/// never be a situation where the visible _hashtable has less data than
/// it did at an earlier time. This value is initialized to an array of size
/// 1. (That array is never mutated as any additions will trigger an Expand
/// operation, but we don't use an empty array as the
/// initial step, as this approach allows the TryGetValue logic to always
/// succeed without needing any length or null checks.)
/// </summary>
private volatile IntPtr[] _hashtable = new IntPtr[_initialSize];
/// <summary>
/// Tracks the hashtable being used by expansion. Used as a sentinel
/// to threads trying to add to the old hashtable that an expansion is
/// in progress.
/// </summary>
private volatile IntPtr[] _newHashTable;
/// <summary>
/// _count represents the current count of elements in the hashtable
/// _count is used in combination with _resizeCount to control when the
/// hashtable should expand
/// </summary>
private volatile int _count = 0;
/// <summary>
/// Represents _count plus the number of potential adds currently happening.
/// If this reaches _hashTable.Length-1, an expansion is required (because
/// one slot must always be null for seeks to complete).
/// </summary>
private int _reserve = 0;
/// <summary>
/// _resizeCount represents the size at which the hashtable should resize.
/// While this doesn't strictly need to be volatile, having threads read stale values
/// triggers a lot of unneeded attempts to expand.
/// </summary>
private volatile int _resizeCount = _initialSize * _fillPercentageBeforeResize / 100;
/// <summary>
/// Get the underlying array for the hashtable at this time.
/// </summary>
private IntPtr[] GetCurrentHashtable()
{
return _hashtable;
}
/// <summary>
/// Set the newly visible hashtable underlying array. Used by writers after
/// the new array is fully constructed. The volatile write is used to ensure
/// that all writes to the contents of hashtable are completed before _hashtable
/// is visible to readers.
/// </summary>
private void SetCurrentHashtable(IntPtr[] hashtable)
{
_hashtable = hashtable;
}
/// <summary>
/// Used to ensure that the hashtable can function with
/// fairly poor initial hash codes.
/// </summary>
public static int HashInt1(int key)
{
unchecked
{
int a = (int)0x9e3779b9 + key;
int b = (int)0x9e3779b9;
int c = 16777619;
a -= b; a -= c; a ^= (c >> 13);
b -= c; b -= a; b ^= (a << 8);
c -= a; c -= b; c ^= (b >> 13);
a -= b; a -= c; a ^= (c >> 12);
b -= c; b -= a; b ^= (a << 16);
c -= a; c -= b; c ^= (b >> 5);
a -= b; a -= c; a ^= (c >> 3);
b -= c; b -= a; b ^= (a << 10);
c -= a; c -= b; c ^= (b >> 15);
return c;
}
}
/// <summary>
/// Generate a somewhat independent hash value from another integer. This is used
/// as part of a double hashing scheme. By being relatively prime with powers of 2
/// this hash function can be reliably used as part of a double hashing scheme as it
/// is guaranteed to eventually probe every slot in the table. (Table sizes are
/// constrained to be a power of two)
/// </summary>
public static int HashInt2(int key)
{
unchecked
{
int hash = unchecked((int)0xB1635D64) + key;
hash += (hash << 3);
hash ^= (hash >> 11);
hash += (hash << 15);
hash |= 0x00000001; // To make sure that this is relatively prime with power of 2
return hash;
}
}
/// <summary>
/// Create the LockFreeReaderHashtable. This hash table is designed for GetOrCreateValue
/// to be a generally lock free api (unless an add is necessary)
/// </summary>
public LockFreeReaderHashtableOfPointers()
{
#if DEBUG
// Ensure the initial value is a power of 2
bool foundAOne = false;
for (int i = 0; i < 32; i++)
{
int lastBit = _initialSize >> i;
if ((lastBit & 0x1) == 0x1)
{
Debug.Assert(!foundAOne);
foundAOne = true;
}
}
#endif // DEBUG
_newHashTable = _hashtable;
}
/// <summary>
/// The current count of elements in the hashtable
/// </summary>
public int Count { get { return _count; } }
/// <summary>
/// Gets the value associated with the specified key.
/// </summary>
/// <param name="key">The key of the value to get.</param>
/// <param name="value">When this method returns, contains the value associated with
/// the specified key, if the key is found; otherwise, the default value for the type
/// of the value parameter. This parameter is passed uninitialized. This function is threadsafe,
/// and wait-free</param>
/// <returns>true if a value was found</returns>
public bool TryGetValue(TKey key, out TValue value)
{
IntPtr[] hashTableLocal = GetCurrentHashtable();
Debug.Assert(hashTableLocal.Length > 0);
int mask = hashTableLocal.Length - 1;
int hashCode = GetKeyHashCode(key);
int tableIndex = HashInt1(hashCode) & mask;
if (hashTableLocal[tableIndex] == IntPtr.Zero)
{
value = default(TValue);
return false;
}
TValue valTemp = ConvertIntPtrToValue(hashTableLocal[tableIndex]);
if (CompareKeyToValue(key, valTemp))
{
value = valTemp;
return true;
}
int hash2 = HashInt2(hashCode);
tableIndex = (tableIndex + hash2) & mask;
while (hashTableLocal[tableIndex] != IntPtr.Zero)
{
valTemp = ConvertIntPtrToValue(hashTableLocal[tableIndex]);
if (CompareKeyToValue(key, valTemp))
{
value = valTemp;
return true;
}
tableIndex = (tableIndex + hash2) & mask;
}
value = default(TValue);
return false;
}
/// <summary>
/// Make the underlying array of the hashtable bigger. This function
/// does not change the contents of the hashtable. This entire function locks.
/// </summary>
private void Expand(IntPtr[] oldHashtable)
{
lock(this)
{
// If somebody else already resized, don't try to do it based on an old table
if(oldHashtable != _hashtable)
{
return;
}
// The checked statement here protects against both the hashTable size and _reserve overflowing. That does mean
// the maximum size of _hashTable is 0x70000000
int newSize = checked(oldHashtable.Length * 2);
// The hashtable only functions well when it has a certain minimum size
const int minimumUsefulSize = 16;
if (newSize < minimumUsefulSize)
newSize = minimumUsefulSize;
IntPtr[] newHashTable = new IntPtr[newSize];
_newHashTable = newHashTable;
int mask = newHashTable.Length - 1;
foreach (IntPtr ptrValue in _hashtable)
{
if (ptrValue == IntPtr.Zero)
continue;
TValue value = ConvertIntPtrToValue(ptrValue);
// If there's a deadlock at this point, GetValueHashCode is re-entering Add, which it must not do.
int hashCode = GetValueHashCode(value);
int tableIndex = HashInt1(hashCode) & mask;
// Initial probe into hashtable found empty spot
if (newHashTable[tableIndex] == IntPtr.Zero)
{
// Add to hash
newHashTable[tableIndex] = ptrValue;
continue;
}
int hash2 = HashInt2(hashCode);
tableIndex = (tableIndex + hash2) & mask;
while (newHashTable[tableIndex] != IntPtr.Zero)
{
tableIndex = (tableIndex + hash2) & mask;
}
// We've probed to find an empty spot
// Add to hash
newHashTable[tableIndex] = ptrValue;
}
_resizeCount = checked((newSize * _fillPercentageBeforeResize) / 100);
SetCurrentHashtable(newHashTable);
}
}
/// <summary>
/// Grow the hashtable so that storing into the hashtable does not require any allocation
/// operations.
/// </summary>
/// <param name="size"></param>
public void Reserve(int size)
{
while (size >= _resizeCount)
Expand(_hashtable);
}
/// <summary>
/// Adds a value to the hashtable if it is not already present.
/// Note that the key is not specified as it is implicit in the value. This function is thread-safe,
/// but must only take locks around internal operations and GetValueHashCode.
/// </summary>
/// <param name="value">Value to attempt to add to the hashtable, must not be null</param>
/// <returns>True if the value was added. False if it was already present.</returns>
public bool TryAdd(TValue value)
{
bool addedValue;
AddOrGetExistingInner(value, out addedValue);
return addedValue;
}
/// <summary>
/// Add a value to the hashtable, or find a value which is already present in the hashtable.
/// Note that the key is not specified as it is implicit in the value. This function is thread-safe,
/// but must only take locks around internal operations and GetValueHashCode.
/// </summary>
/// <param name="value">Value to attempt to add to the hashtable, its conversion to IntPtr must not result in IntPtr.Zero</param>
/// <returns>Newly added value, or a value which was already present in the hashtable which is equal to it.</returns>
public TValue AddOrGetExisting(TValue value)
{
bool unused;
return AddOrGetExistingInner(value, out unused);
}
private TValue AddOrGetExistingInner(TValue value, out bool addedValue)
{
IntPtr ptrValue = ConvertValueToIntPtr(value);
if (ptrValue == IntPtr.Zero)
throw new ArgumentNullException();
// Optimistically check to see if adding this value may require an expansion. If so, expand
// the table now. This isn't required to ensure space for the write, but helps keep
// the ratio in a good range.
if (_count >= _resizeCount)
{
Expand(_hashtable);
}
TValue result = default(TValue);
bool success;
do
{
success = TryAddOrGetExisting(value, out addedValue, ref result);
} while (!success);
return result;
}
/// <summary>
/// Attemps to add a value to the hashtable, or find a value which is already present in the hashtable.
/// In some cases, this will fail due to contention with other additions and must be retried.
/// Note that the key is not specified as it is implicit in the value. This function is thread-safe,
/// but must only take locks around internal operations and GetValueHashCode.
/// </summary>
/// <param name="value">Value to attempt to add to the hashtable, must not be null</param>
/// <param name="addedValue">Set to true if <paramref name="value"/> was added to the table. False if the value
/// was already present. Not defined if adding was attempted but failed.</param>
/// <param name="valueInHashtable">Newly added value if adding succeds, a value which was already present in the hashtable which is equal to it,
/// or an undefined value if adding fails and must be retried.</param>
/// <returns>True if the operation succeeded (either because the value was added or the value was already present).</returns>
private bool TryAddOrGetExisting(TValue value, out bool addedValue, ref TValue valueInHashtable)
{
// The table must be captured into a local to ensure reads/writes
// don't get torn by expansions
IntPtr[] hashTableLocal = _hashtable;
addedValue = true;
int mask = hashTableLocal.Length - 1;
int hashCode = GetValueHashCode(value);
int tableIndex = HashInt1(hashCode) & mask;
// Find an empty spot, starting with the initial tableIndex
if (hashTableLocal[tableIndex] != IntPtr.Zero)
{
TValue valTmp = ConvertIntPtrToValue(hashTableLocal[tableIndex]);
if (CompareValueToValue(value, valTmp))
{
// Value is already present in hash, do not add
addedValue = false;
valueInHashtable = valTmp;
return true;
}
int hash2 = HashInt2(hashCode);
tableIndex = (tableIndex + hash2) & mask;
while (hashTableLocal[tableIndex] != IntPtr.Zero)
{
valTmp = ConvertIntPtrToValue(hashTableLocal[tableIndex]);
if (CompareValueToValue(value, valTmp))
{
// Value is already present in hash, do not add
addedValue = false;
valueInHashtable = valTmp;
return true;
}
tableIndex = (tableIndex + hash2) & mask;
}
}
// Ensure there's enough space for at least one null slot after this write
if (Interlocked.Increment(ref _reserve) >= hashTableLocal.Length - 1)
{
Interlocked.Decrement(ref _reserve);
Expand(hashTableLocal);
// Since we expanded, our index won't work, restart
return false;
}
// We've probed to find an empty spot, add to hash
IntPtr ptrValue = ConvertValueToIntPtr(value);
if (!TryWriteValueToLocation(ptrValue, hashTableLocal, tableIndex))
{
Interlocked.Decrement(ref _reserve);
return false;
}
// Now that we've written to the local array, find out if that array has been
// replaced by expansion. If it has, we need to restart and write to the new array.
if (_newHashTable != hashTableLocal)
{
// Pulse the lock so we don't spin during an expansion
lock(this) { }
Interlocked.Decrement(ref _reserve);
return false;
}
// If the write succeeded, increment _count
Interlocked.Increment(ref _count);
valueInHashtable = value;
return true;
}
/// <summary>
/// Attampts to write a value into the table. May fail if another value has been added.
/// </summary>
/// <returns>True if the value was successfully written</returns>
private bool TryWriteValueToLocation(IntPtr value, IntPtr[] hashTableLocal, int tableIndex)
{
// Add to hash, use a volatile write to ensure that
// the contents of the value are fully published to all
// threads before adding to the hashtable
if (Interlocked.CompareExchange(ref hashTableLocal[tableIndex], value, IntPtr.Zero) == IntPtr.Zero)
{
return true;
}
return false;
}
[MethodImpl(MethodImplOptions.NoInlining)]
private TValue CreateValueAndEnsureValueIsInTable(TKey key)
{
TValue newValue = CreateValueFromKey(key);
Debug.Assert(GetValueHashCode(newValue) == GetKeyHashCode(key));
return AddOrGetExisting(newValue);
}
/// <summary>
/// Get the value associated with a key. If value is not present in dictionary, use the creator delegate passed in
/// at object construction time to create the value, and attempt to add it to the table. (Create the value while not
/// under the lock, but add it to the table while under the lock. This may result in a throw away object being constructed)
/// This function is thread-safe, but will take a lock to perform its operations.
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public TValue GetOrCreateValue(TKey key)
{
TValue existingValue;
if (TryGetValue(key, out existingValue))
return existingValue;
return CreateValueAndEnsureValueIsInTable(key);
}
/// <summary>
/// Determine if this collection contains a value associated with a key. This function is thread-safe, and wait-free.
/// </summary>
public bool Contains(TKey key)
{
TValue dummyExistingValue;
return TryGetValue(key, out dummyExistingValue);
}
/// <summary>
/// Determine if this collection contains a given value, and returns the value in the hashtable if found. This function is thread-safe, and wait-free.
/// </summary>
/// <param name="value">Value to search for in the hashtable, must not be null</param>
/// <returns>Value from the hashtable if found, otherwise null.</returns>
public TValue GetValueIfExists(TValue value)
{
if (value == null)
throw new ArgumentNullException();
IntPtr[] hashTableLocal = GetCurrentHashtable();
Debug.Assert(hashTableLocal.Length > 0);
int mask = hashTableLocal.Length - 1;
int hashCode = GetValueHashCode(value);
int tableIndex = HashInt1(hashCode) & mask;
if (hashTableLocal[tableIndex] == IntPtr.Zero)
return default(TValue);
TValue valTmp = ConvertIntPtrToValue(hashTableLocal[tableIndex]);
if (CompareValueToValue(value, valTmp))
return valTmp;
int hash2 = HashInt2(hashCode);
tableIndex = (tableIndex + hash2) & mask;
while (hashTableLocal[tableIndex] != IntPtr.Zero)
{
valTmp = ConvertIntPtrToValue(hashTableLocal[tableIndex]);
if (CompareValueToValue(value, valTmp))
return valTmp;
tableIndex = (tableIndex + hash2) & mask;
}
return default(TValue);
}
/// <summary>
/// Enumerator type for the LockFreeReaderHashtable
/// This is threadsafe, but is not garaunteed to avoid torn state.
/// In particular, the enumerator may report some newly added values
/// but not others. All values in the hashtable as of enumerator
/// creation will always be enumerated.
/// </summary>
public struct Enumerator : IEnumerator<TValue>
{
LockFreeReaderHashtableOfPointers<TKey, TValue> _hashtable;
private IntPtr[] _hashtableContentsToEnumerate;
private int _index;
private TValue _current;
/// <summary>
/// Use this to get an enumerable collection from a LockFreeReaderHashtable.
/// Used instead of a GetEnumerator method on the LockFreeReaderHashtable to
/// reduce excess type creation. (By moving the method here, the generic dictionary for
/// LockFreeReaderHashtable does not need to contain a reference to the
/// enumerator type.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Enumerator Get(LockFreeReaderHashtableOfPointers<TKey, TValue> hashtable)
{
return new Enumerator(hashtable);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Enumerator GetEnumerator()
{
return this;
}
internal Enumerator(LockFreeReaderHashtableOfPointers<TKey, TValue> hashtable)
{
_hashtable = hashtable;
_hashtableContentsToEnumerate = hashtable._hashtable;
_index = 0;
_current = default(TValue);
}
public bool MoveNext()
{
if ((_hashtableContentsToEnumerate != null) && (_index < _hashtableContentsToEnumerate.Length))
{
for (; _index < _hashtableContentsToEnumerate.Length; _index++)
{
if (_hashtableContentsToEnumerate[_index] != IntPtr.Zero)
{
_current = _hashtable.ConvertIntPtrToValue(_hashtableContentsToEnumerate[_index]);
_index++;
return true;
}
}
}
_current = default(TValue);
return false;
}
public void Dispose()
{
}
public void Reset()
{
throw new NotImplementedException();
}
public TValue Current
{
get
{
return _current;
}
}
object IEnumerator.Current
{
get
{
throw new NotImplementedException();
}
}
}
/// <summary>
/// Given a key, compute a hash code. This function must be thread safe.
/// </summary>
protected abstract int GetKeyHashCode(TKey key);
/// <summary>
/// Given a value, compute a hash code which would be identical to the hash code
/// for a key which should look up this value. This function must be thread safe.
/// This function must also not cause additional hashtable adds.
/// </summary>
protected abstract int GetValueHashCode(TValue value);
/// <summary>
/// Compare a key and value. If the key refers to this value, return true.
/// This function must be thread safe.
/// </summary>
protected abstract bool CompareKeyToValue(TKey key, TValue value);
/// <summary>
/// Compare a value with another value. Return true if values are equal.
/// This function must be thread safe.
/// </summary>
protected abstract bool CompareValueToValue(TValue value1, TValue value2);
/// <summary>
/// Create a new value from a key. Must be threadsafe. Value may or may not be added
/// to collection. Return value must not be null.
/// </summary>
protected abstract TValue CreateValueFromKey(TKey key);
/// <summary>
/// Convert a value to an IntPtr for storage into the hashtable
/// </summary>
protected abstract IntPtr ConvertValueToIntPtr(TValue value);
/// <summary>
/// Convert an IntPtr into a value for comparisions, or for returning.
/// </summary>
protected abstract TValue ConvertIntPtrToValue(IntPtr pointer);
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Asset.V1.Snippets
{
using Google.Api.Gax;
using Google.LongRunning;
using Google.Protobuf.WellKnownTypes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class GeneratedAssetServiceClientSnippets
{
/// <summary>Snippet for ExportAssets</summary>
public void ExportAssetsRequestObject()
{
// Snippet: ExportAssets(ExportAssetsRequest, CallSettings)
// Create client
AssetServiceClient assetServiceClient = AssetServiceClient.Create();
// Initialize request argument(s)
ExportAssetsRequest request = new ExportAssetsRequest
{
ParentAsResourceName = new UnparsedResourceName("a/wildcard/resource"),
ReadTime = new Timestamp(),
AssetTypes = { "", },
ContentType = ContentType.Unspecified,
OutputConfig = new OutputConfig(),
RelationshipTypes = { "", },
};
// Make the request
Operation<ExportAssetsResponse, ExportAssetsRequest> response = assetServiceClient.ExportAssets(request);
// Poll until the returned long-running operation is complete
Operation<ExportAssetsResponse, ExportAssetsRequest> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
ExportAssetsResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<ExportAssetsResponse, ExportAssetsRequest> retrievedResponse = assetServiceClient.PollOnceExportAssets(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
ExportAssetsResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for ExportAssetsAsync</summary>
public async Task ExportAssetsRequestObjectAsync()
{
// Snippet: ExportAssetsAsync(ExportAssetsRequest, CallSettings)
// Additional: ExportAssetsAsync(ExportAssetsRequest, CancellationToken)
// Create client
AssetServiceClient assetServiceClient = await AssetServiceClient.CreateAsync();
// Initialize request argument(s)
ExportAssetsRequest request = new ExportAssetsRequest
{
ParentAsResourceName = new UnparsedResourceName("a/wildcard/resource"),
ReadTime = new Timestamp(),
AssetTypes = { "", },
ContentType = ContentType.Unspecified,
OutputConfig = new OutputConfig(),
RelationshipTypes = { "", },
};
// Make the request
Operation<ExportAssetsResponse, ExportAssetsRequest> response = await assetServiceClient.ExportAssetsAsync(request);
// Poll until the returned long-running operation is complete
Operation<ExportAssetsResponse, ExportAssetsRequest> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
ExportAssetsResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<ExportAssetsResponse, ExportAssetsRequest> retrievedResponse = await assetServiceClient.PollOnceExportAssetsAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
ExportAssetsResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for ListAssets</summary>
public void ListAssetsRequestObject()
{
// Snippet: ListAssets(ListAssetsRequest, CallSettings)
// Create client
AssetServiceClient assetServiceClient = AssetServiceClient.Create();
// Initialize request argument(s)
ListAssetsRequest request = new ListAssetsRequest
{
ParentAsResourceName = new UnparsedResourceName("a/wildcard/resource"),
ReadTime = new Timestamp(),
AssetTypes = { "", },
ContentType = ContentType.Unspecified,
RelationshipTypes = { "", },
};
// Make the request
PagedEnumerable<ListAssetsResponse, Asset> response = assetServiceClient.ListAssets(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (Asset item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListAssetsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Asset item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Asset> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Asset item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListAssetsAsync</summary>
public async Task ListAssetsRequestObjectAsync()
{
// Snippet: ListAssetsAsync(ListAssetsRequest, CallSettings)
// Create client
AssetServiceClient assetServiceClient = await AssetServiceClient.CreateAsync();
// Initialize request argument(s)
ListAssetsRequest request = new ListAssetsRequest
{
ParentAsResourceName = new UnparsedResourceName("a/wildcard/resource"),
ReadTime = new Timestamp(),
AssetTypes = { "", },
ContentType = ContentType.Unspecified,
RelationshipTypes = { "", },
};
// Make the request
PagedAsyncEnumerable<ListAssetsResponse, Asset> response = assetServiceClient.ListAssetsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Asset item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListAssetsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Asset item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Asset> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Asset item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListAssets</summary>
public void ListAssets()
{
// Snippet: ListAssets(string, string, int?, CallSettings)
// Create client
AssetServiceClient assetServiceClient = AssetServiceClient.Create();
// Initialize request argument(s)
string parent = "a/wildcard/resource";
// Make the request
PagedEnumerable<ListAssetsResponse, Asset> response = assetServiceClient.ListAssets(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (Asset item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListAssetsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Asset item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Asset> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Asset item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListAssetsAsync</summary>
public async Task ListAssetsAsync()
{
// Snippet: ListAssetsAsync(string, string, int?, CallSettings)
// Create client
AssetServiceClient assetServiceClient = await AssetServiceClient.CreateAsync();
// Initialize request argument(s)
string parent = "a/wildcard/resource";
// Make the request
PagedAsyncEnumerable<ListAssetsResponse, Asset> response = assetServiceClient.ListAssetsAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Asset item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListAssetsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Asset item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Asset> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Asset item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListAssets</summary>
public void ListAssetsResourceNames()
{
// Snippet: ListAssets(IResourceName, string, int?, CallSettings)
// Create client
AssetServiceClient assetServiceClient = AssetServiceClient.Create();
// Initialize request argument(s)
IResourceName parent = new UnparsedResourceName("a/wildcard/resource");
// Make the request
PagedEnumerable<ListAssetsResponse, Asset> response = assetServiceClient.ListAssets(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (Asset item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListAssetsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Asset item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Asset> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Asset item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListAssetsAsync</summary>
public async Task ListAssetsResourceNamesAsync()
{
// Snippet: ListAssetsAsync(IResourceName, string, int?, CallSettings)
// Create client
AssetServiceClient assetServiceClient = await AssetServiceClient.CreateAsync();
// Initialize request argument(s)
IResourceName parent = new UnparsedResourceName("a/wildcard/resource");
// Make the request
PagedAsyncEnumerable<ListAssetsResponse, Asset> response = assetServiceClient.ListAssetsAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Asset item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListAssetsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Asset item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Asset> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Asset item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for BatchGetAssetsHistory</summary>
public void BatchGetAssetsHistoryRequestObject()
{
// Snippet: BatchGetAssetsHistory(BatchGetAssetsHistoryRequest, CallSettings)
// Create client
AssetServiceClient assetServiceClient = AssetServiceClient.Create();
// Initialize request argument(s)
BatchGetAssetsHistoryRequest request = new BatchGetAssetsHistoryRequest
{
ParentAsResourceName = new UnparsedResourceName("a/wildcard/resource"),
AssetNames = { "", },
ContentType = ContentType.Unspecified,
ReadTimeWindow = new TimeWindow(),
RelationshipTypes = { "", },
};
// Make the request
BatchGetAssetsHistoryResponse response = assetServiceClient.BatchGetAssetsHistory(request);
// End snippet
}
/// <summary>Snippet for BatchGetAssetsHistoryAsync</summary>
public async Task BatchGetAssetsHistoryRequestObjectAsync()
{
// Snippet: BatchGetAssetsHistoryAsync(BatchGetAssetsHistoryRequest, CallSettings)
// Additional: BatchGetAssetsHistoryAsync(BatchGetAssetsHistoryRequest, CancellationToken)
// Create client
AssetServiceClient assetServiceClient = await AssetServiceClient.CreateAsync();
// Initialize request argument(s)
BatchGetAssetsHistoryRequest request = new BatchGetAssetsHistoryRequest
{
ParentAsResourceName = new UnparsedResourceName("a/wildcard/resource"),
AssetNames = { "", },
ContentType = ContentType.Unspecified,
ReadTimeWindow = new TimeWindow(),
RelationshipTypes = { "", },
};
// Make the request
BatchGetAssetsHistoryResponse response = await assetServiceClient.BatchGetAssetsHistoryAsync(request);
// End snippet
}
/// <summary>Snippet for CreateFeed</summary>
public void CreateFeedRequestObject()
{
// Snippet: CreateFeed(CreateFeedRequest, CallSettings)
// Create client
AssetServiceClient assetServiceClient = AssetServiceClient.Create();
// Initialize request argument(s)
CreateFeedRequest request = new CreateFeedRequest
{
Parent = "",
FeedId = "",
Feed = new Feed(),
};
// Make the request
Feed response = assetServiceClient.CreateFeed(request);
// End snippet
}
/// <summary>Snippet for CreateFeedAsync</summary>
public async Task CreateFeedRequestObjectAsync()
{
// Snippet: CreateFeedAsync(CreateFeedRequest, CallSettings)
// Additional: CreateFeedAsync(CreateFeedRequest, CancellationToken)
// Create client
AssetServiceClient assetServiceClient = await AssetServiceClient.CreateAsync();
// Initialize request argument(s)
CreateFeedRequest request = new CreateFeedRequest
{
Parent = "",
FeedId = "",
Feed = new Feed(),
};
// Make the request
Feed response = await assetServiceClient.CreateFeedAsync(request);
// End snippet
}
/// <summary>Snippet for CreateFeed</summary>
public void CreateFeed()
{
// Snippet: CreateFeed(string, CallSettings)
// Create client
AssetServiceClient assetServiceClient = AssetServiceClient.Create();
// Initialize request argument(s)
string parent = "";
// Make the request
Feed response = assetServiceClient.CreateFeed(parent);
// End snippet
}
/// <summary>Snippet for CreateFeedAsync</summary>
public async Task CreateFeedAsync()
{
// Snippet: CreateFeedAsync(string, CallSettings)
// Additional: CreateFeedAsync(string, CancellationToken)
// Create client
AssetServiceClient assetServiceClient = await AssetServiceClient.CreateAsync();
// Initialize request argument(s)
string parent = "";
// Make the request
Feed response = await assetServiceClient.CreateFeedAsync(parent);
// End snippet
}
/// <summary>Snippet for GetFeed</summary>
public void GetFeedRequestObject()
{
// Snippet: GetFeed(GetFeedRequest, CallSettings)
// Create client
AssetServiceClient assetServiceClient = AssetServiceClient.Create();
// Initialize request argument(s)
GetFeedRequest request = new GetFeedRequest
{
FeedName = FeedName.FromProjectFeed("[PROJECT]", "[FEED]"),
};
// Make the request
Feed response = assetServiceClient.GetFeed(request);
// End snippet
}
/// <summary>Snippet for GetFeedAsync</summary>
public async Task GetFeedRequestObjectAsync()
{
// Snippet: GetFeedAsync(GetFeedRequest, CallSettings)
// Additional: GetFeedAsync(GetFeedRequest, CancellationToken)
// Create client
AssetServiceClient assetServiceClient = await AssetServiceClient.CreateAsync();
// Initialize request argument(s)
GetFeedRequest request = new GetFeedRequest
{
FeedName = FeedName.FromProjectFeed("[PROJECT]", "[FEED]"),
};
// Make the request
Feed response = await assetServiceClient.GetFeedAsync(request);
// End snippet
}
/// <summary>Snippet for GetFeed</summary>
public void GetFeed()
{
// Snippet: GetFeed(string, CallSettings)
// Create client
AssetServiceClient assetServiceClient = AssetServiceClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/feeds/[FEED]";
// Make the request
Feed response = assetServiceClient.GetFeed(name);
// End snippet
}
/// <summary>Snippet for GetFeedAsync</summary>
public async Task GetFeedAsync()
{
// Snippet: GetFeedAsync(string, CallSettings)
// Additional: GetFeedAsync(string, CancellationToken)
// Create client
AssetServiceClient assetServiceClient = await AssetServiceClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/feeds/[FEED]";
// Make the request
Feed response = await assetServiceClient.GetFeedAsync(name);
// End snippet
}
/// <summary>Snippet for GetFeed</summary>
public void GetFeedResourceNames()
{
// Snippet: GetFeed(FeedName, CallSettings)
// Create client
AssetServiceClient assetServiceClient = AssetServiceClient.Create();
// Initialize request argument(s)
FeedName name = FeedName.FromProjectFeed("[PROJECT]", "[FEED]");
// Make the request
Feed response = assetServiceClient.GetFeed(name);
// End snippet
}
/// <summary>Snippet for GetFeedAsync</summary>
public async Task GetFeedResourceNamesAsync()
{
// Snippet: GetFeedAsync(FeedName, CallSettings)
// Additional: GetFeedAsync(FeedName, CancellationToken)
// Create client
AssetServiceClient assetServiceClient = await AssetServiceClient.CreateAsync();
// Initialize request argument(s)
FeedName name = FeedName.FromProjectFeed("[PROJECT]", "[FEED]");
// Make the request
Feed response = await assetServiceClient.GetFeedAsync(name);
// End snippet
}
/// <summary>Snippet for ListFeeds</summary>
public void ListFeedsRequestObject()
{
// Snippet: ListFeeds(ListFeedsRequest, CallSettings)
// Create client
AssetServiceClient assetServiceClient = AssetServiceClient.Create();
// Initialize request argument(s)
ListFeedsRequest request = new ListFeedsRequest { Parent = "", };
// Make the request
ListFeedsResponse response = assetServiceClient.ListFeeds(request);
// End snippet
}
/// <summary>Snippet for ListFeedsAsync</summary>
public async Task ListFeedsRequestObjectAsync()
{
// Snippet: ListFeedsAsync(ListFeedsRequest, CallSettings)
// Additional: ListFeedsAsync(ListFeedsRequest, CancellationToken)
// Create client
AssetServiceClient assetServiceClient = await AssetServiceClient.CreateAsync();
// Initialize request argument(s)
ListFeedsRequest request = new ListFeedsRequest { Parent = "", };
// Make the request
ListFeedsResponse response = await assetServiceClient.ListFeedsAsync(request);
// End snippet
}
/// <summary>Snippet for ListFeeds</summary>
public void ListFeeds()
{
// Snippet: ListFeeds(string, CallSettings)
// Create client
AssetServiceClient assetServiceClient = AssetServiceClient.Create();
// Initialize request argument(s)
string parent = "";
// Make the request
ListFeedsResponse response = assetServiceClient.ListFeeds(parent);
// End snippet
}
/// <summary>Snippet for ListFeedsAsync</summary>
public async Task ListFeedsAsync()
{
// Snippet: ListFeedsAsync(string, CallSettings)
// Additional: ListFeedsAsync(string, CancellationToken)
// Create client
AssetServiceClient assetServiceClient = await AssetServiceClient.CreateAsync();
// Initialize request argument(s)
string parent = "";
// Make the request
ListFeedsResponse response = await assetServiceClient.ListFeedsAsync(parent);
// End snippet
}
/// <summary>Snippet for UpdateFeed</summary>
public void UpdateFeedRequestObject()
{
// Snippet: UpdateFeed(UpdateFeedRequest, CallSettings)
// Create client
AssetServiceClient assetServiceClient = AssetServiceClient.Create();
// Initialize request argument(s)
UpdateFeedRequest request = new UpdateFeedRequest
{
Feed = new Feed(),
UpdateMask = new FieldMask(),
};
// Make the request
Feed response = assetServiceClient.UpdateFeed(request);
// End snippet
}
/// <summary>Snippet for UpdateFeedAsync</summary>
public async Task UpdateFeedRequestObjectAsync()
{
// Snippet: UpdateFeedAsync(UpdateFeedRequest, CallSettings)
// Additional: UpdateFeedAsync(UpdateFeedRequest, CancellationToken)
// Create client
AssetServiceClient assetServiceClient = await AssetServiceClient.CreateAsync();
// Initialize request argument(s)
UpdateFeedRequest request = new UpdateFeedRequest
{
Feed = new Feed(),
UpdateMask = new FieldMask(),
};
// Make the request
Feed response = await assetServiceClient.UpdateFeedAsync(request);
// End snippet
}
/// <summary>Snippet for UpdateFeed</summary>
public void UpdateFeed()
{
// Snippet: UpdateFeed(Feed, CallSettings)
// Create client
AssetServiceClient assetServiceClient = AssetServiceClient.Create();
// Initialize request argument(s)
Feed feed = new Feed();
// Make the request
Feed response = assetServiceClient.UpdateFeed(feed);
// End snippet
}
/// <summary>Snippet for UpdateFeedAsync</summary>
public async Task UpdateFeedAsync()
{
// Snippet: UpdateFeedAsync(Feed, CallSettings)
// Additional: UpdateFeedAsync(Feed, CancellationToken)
// Create client
AssetServiceClient assetServiceClient = await AssetServiceClient.CreateAsync();
// Initialize request argument(s)
Feed feed = new Feed();
// Make the request
Feed response = await assetServiceClient.UpdateFeedAsync(feed);
// End snippet
}
/// <summary>Snippet for DeleteFeed</summary>
public void DeleteFeedRequestObject()
{
// Snippet: DeleteFeed(DeleteFeedRequest, CallSettings)
// Create client
AssetServiceClient assetServiceClient = AssetServiceClient.Create();
// Initialize request argument(s)
DeleteFeedRequest request = new DeleteFeedRequest
{
FeedName = FeedName.FromProjectFeed("[PROJECT]", "[FEED]"),
};
// Make the request
assetServiceClient.DeleteFeed(request);
// End snippet
}
/// <summary>Snippet for DeleteFeedAsync</summary>
public async Task DeleteFeedRequestObjectAsync()
{
// Snippet: DeleteFeedAsync(DeleteFeedRequest, CallSettings)
// Additional: DeleteFeedAsync(DeleteFeedRequest, CancellationToken)
// Create client
AssetServiceClient assetServiceClient = await AssetServiceClient.CreateAsync();
// Initialize request argument(s)
DeleteFeedRequest request = new DeleteFeedRequest
{
FeedName = FeedName.FromProjectFeed("[PROJECT]", "[FEED]"),
};
// Make the request
await assetServiceClient.DeleteFeedAsync(request);
// End snippet
}
/// <summary>Snippet for DeleteFeed</summary>
public void DeleteFeed()
{
// Snippet: DeleteFeed(string, CallSettings)
// Create client
AssetServiceClient assetServiceClient = AssetServiceClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/feeds/[FEED]";
// Make the request
assetServiceClient.DeleteFeed(name);
// End snippet
}
/// <summary>Snippet for DeleteFeedAsync</summary>
public async Task DeleteFeedAsync()
{
// Snippet: DeleteFeedAsync(string, CallSettings)
// Additional: DeleteFeedAsync(string, CancellationToken)
// Create client
AssetServiceClient assetServiceClient = await AssetServiceClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/feeds/[FEED]";
// Make the request
await assetServiceClient.DeleteFeedAsync(name);
// End snippet
}
/// <summary>Snippet for DeleteFeed</summary>
public void DeleteFeedResourceNames()
{
// Snippet: DeleteFeed(FeedName, CallSettings)
// Create client
AssetServiceClient assetServiceClient = AssetServiceClient.Create();
// Initialize request argument(s)
FeedName name = FeedName.FromProjectFeed("[PROJECT]", "[FEED]");
// Make the request
assetServiceClient.DeleteFeed(name);
// End snippet
}
/// <summary>Snippet for DeleteFeedAsync</summary>
public async Task DeleteFeedResourceNamesAsync()
{
// Snippet: DeleteFeedAsync(FeedName, CallSettings)
// Additional: DeleteFeedAsync(FeedName, CancellationToken)
// Create client
AssetServiceClient assetServiceClient = await AssetServiceClient.CreateAsync();
// Initialize request argument(s)
FeedName name = FeedName.FromProjectFeed("[PROJECT]", "[FEED]");
// Make the request
await assetServiceClient.DeleteFeedAsync(name);
// End snippet
}
/// <summary>Snippet for SearchAllResources</summary>
public void SearchAllResourcesRequestObject()
{
// Snippet: SearchAllResources(SearchAllResourcesRequest, CallSettings)
// Create client
AssetServiceClient assetServiceClient = AssetServiceClient.Create();
// Initialize request argument(s)
SearchAllResourcesRequest request = new SearchAllResourcesRequest
{
Scope = "",
Query = "",
AssetTypes = { "", },
OrderBy = "",
ReadMask = new FieldMask(),
};
// Make the request
PagedEnumerable<SearchAllResourcesResponse, ResourceSearchResult> response = assetServiceClient.SearchAllResources(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (ResourceSearchResult item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (SearchAllResourcesResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (ResourceSearchResult item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<ResourceSearchResult> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (ResourceSearchResult item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for SearchAllResourcesAsync</summary>
public async Task SearchAllResourcesRequestObjectAsync()
{
// Snippet: SearchAllResourcesAsync(SearchAllResourcesRequest, CallSettings)
// Create client
AssetServiceClient assetServiceClient = await AssetServiceClient.CreateAsync();
// Initialize request argument(s)
SearchAllResourcesRequest request = new SearchAllResourcesRequest
{
Scope = "",
Query = "",
AssetTypes = { "", },
OrderBy = "",
ReadMask = new FieldMask(),
};
// Make the request
PagedAsyncEnumerable<SearchAllResourcesResponse, ResourceSearchResult> response = assetServiceClient.SearchAllResourcesAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((ResourceSearchResult item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((SearchAllResourcesResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (ResourceSearchResult item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<ResourceSearchResult> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (ResourceSearchResult item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for SearchAllResources</summary>
public void SearchAllResources()
{
// Snippet: SearchAllResources(string, string, IEnumerable<string>, string, int?, CallSettings)
// Create client
AssetServiceClient assetServiceClient = AssetServiceClient.Create();
// Initialize request argument(s)
string scope = "";
string query = "";
IEnumerable<string> assetTypes = new string[] { "", };
// Make the request
PagedEnumerable<SearchAllResourcesResponse, ResourceSearchResult> response = assetServiceClient.SearchAllResources(scope, query, assetTypes);
// Iterate over all response items, lazily performing RPCs as required
foreach (ResourceSearchResult item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (SearchAllResourcesResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (ResourceSearchResult item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<ResourceSearchResult> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (ResourceSearchResult item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for SearchAllResourcesAsync</summary>
public async Task SearchAllResourcesAsync()
{
// Snippet: SearchAllResourcesAsync(string, string, IEnumerable<string>, string, int?, CallSettings)
// Create client
AssetServiceClient assetServiceClient = await AssetServiceClient.CreateAsync();
// Initialize request argument(s)
string scope = "";
string query = "";
IEnumerable<string> assetTypes = new string[] { "", };
// Make the request
PagedAsyncEnumerable<SearchAllResourcesResponse, ResourceSearchResult> response = assetServiceClient.SearchAllResourcesAsync(scope, query, assetTypes);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((ResourceSearchResult item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((SearchAllResourcesResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (ResourceSearchResult item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<ResourceSearchResult> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (ResourceSearchResult item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for SearchAllIamPolicies</summary>
public void SearchAllIamPoliciesRequestObject()
{
// Snippet: SearchAllIamPolicies(SearchAllIamPoliciesRequest, CallSettings)
// Create client
AssetServiceClient assetServiceClient = AssetServiceClient.Create();
// Initialize request argument(s)
SearchAllIamPoliciesRequest request = new SearchAllIamPoliciesRequest
{
Scope = "",
Query = "",
AssetTypes = { "", },
OrderBy = "",
};
// Make the request
PagedEnumerable<SearchAllIamPoliciesResponse, IamPolicySearchResult> response = assetServiceClient.SearchAllIamPolicies(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (IamPolicySearchResult item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (SearchAllIamPoliciesResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (IamPolicySearchResult item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<IamPolicySearchResult> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (IamPolicySearchResult item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for SearchAllIamPoliciesAsync</summary>
public async Task SearchAllIamPoliciesRequestObjectAsync()
{
// Snippet: SearchAllIamPoliciesAsync(SearchAllIamPoliciesRequest, CallSettings)
// Create client
AssetServiceClient assetServiceClient = await AssetServiceClient.CreateAsync();
// Initialize request argument(s)
SearchAllIamPoliciesRequest request = new SearchAllIamPoliciesRequest
{
Scope = "",
Query = "",
AssetTypes = { "", },
OrderBy = "",
};
// Make the request
PagedAsyncEnumerable<SearchAllIamPoliciesResponse, IamPolicySearchResult> response = assetServiceClient.SearchAllIamPoliciesAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((IamPolicySearchResult item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((SearchAllIamPoliciesResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (IamPolicySearchResult item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<IamPolicySearchResult> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (IamPolicySearchResult item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for SearchAllIamPolicies</summary>
public void SearchAllIamPolicies()
{
// Snippet: SearchAllIamPolicies(string, string, string, int?, CallSettings)
// Create client
AssetServiceClient assetServiceClient = AssetServiceClient.Create();
// Initialize request argument(s)
string scope = "";
string query = "";
// Make the request
PagedEnumerable<SearchAllIamPoliciesResponse, IamPolicySearchResult> response = assetServiceClient.SearchAllIamPolicies(scope, query);
// Iterate over all response items, lazily performing RPCs as required
foreach (IamPolicySearchResult item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (SearchAllIamPoliciesResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (IamPolicySearchResult item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<IamPolicySearchResult> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (IamPolicySearchResult item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for SearchAllIamPoliciesAsync</summary>
public async Task SearchAllIamPoliciesAsync()
{
// Snippet: SearchAllIamPoliciesAsync(string, string, string, int?, CallSettings)
// Create client
AssetServiceClient assetServiceClient = await AssetServiceClient.CreateAsync();
// Initialize request argument(s)
string scope = "";
string query = "";
// Make the request
PagedAsyncEnumerable<SearchAllIamPoliciesResponse, IamPolicySearchResult> response = assetServiceClient.SearchAllIamPoliciesAsync(scope, query);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((IamPolicySearchResult item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((SearchAllIamPoliciesResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (IamPolicySearchResult item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<IamPolicySearchResult> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (IamPolicySearchResult item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for AnalyzeIamPolicy</summary>
public void AnalyzeIamPolicyRequestObject()
{
// Snippet: AnalyzeIamPolicy(AnalyzeIamPolicyRequest, CallSettings)
// Create client
AssetServiceClient assetServiceClient = AssetServiceClient.Create();
// Initialize request argument(s)
AnalyzeIamPolicyRequest request = new AnalyzeIamPolicyRequest
{
AnalysisQuery = new IamPolicyAnalysisQuery(),
ExecutionTimeout = new Duration(),
};
// Make the request
AnalyzeIamPolicyResponse response = assetServiceClient.AnalyzeIamPolicy(request);
// End snippet
}
/// <summary>Snippet for AnalyzeIamPolicyAsync</summary>
public async Task AnalyzeIamPolicyRequestObjectAsync()
{
// Snippet: AnalyzeIamPolicyAsync(AnalyzeIamPolicyRequest, CallSettings)
// Additional: AnalyzeIamPolicyAsync(AnalyzeIamPolicyRequest, CancellationToken)
// Create client
AssetServiceClient assetServiceClient = await AssetServiceClient.CreateAsync();
// Initialize request argument(s)
AnalyzeIamPolicyRequest request = new AnalyzeIamPolicyRequest
{
AnalysisQuery = new IamPolicyAnalysisQuery(),
ExecutionTimeout = new Duration(),
};
// Make the request
AnalyzeIamPolicyResponse response = await assetServiceClient.AnalyzeIamPolicyAsync(request);
// End snippet
}
/// <summary>Snippet for AnalyzeIamPolicyLongrunning</summary>
public void AnalyzeIamPolicyLongrunningRequestObject()
{
// Snippet: AnalyzeIamPolicyLongrunning(AnalyzeIamPolicyLongrunningRequest, CallSettings)
// Create client
AssetServiceClient assetServiceClient = AssetServiceClient.Create();
// Initialize request argument(s)
AnalyzeIamPolicyLongrunningRequest request = new AnalyzeIamPolicyLongrunningRequest
{
AnalysisQuery = new IamPolicyAnalysisQuery(),
OutputConfig = new IamPolicyAnalysisOutputConfig(),
};
// Make the request
Operation<AnalyzeIamPolicyLongrunningResponse, AnalyzeIamPolicyLongrunningMetadata> response = assetServiceClient.AnalyzeIamPolicyLongrunning(request);
// Poll until the returned long-running operation is complete
Operation<AnalyzeIamPolicyLongrunningResponse, AnalyzeIamPolicyLongrunningMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
AnalyzeIamPolicyLongrunningResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<AnalyzeIamPolicyLongrunningResponse, AnalyzeIamPolicyLongrunningMetadata> retrievedResponse = assetServiceClient.PollOnceAnalyzeIamPolicyLongrunning(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
AnalyzeIamPolicyLongrunningResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for AnalyzeIamPolicyLongrunningAsync</summary>
public async Task AnalyzeIamPolicyLongrunningRequestObjectAsync()
{
// Snippet: AnalyzeIamPolicyLongrunningAsync(AnalyzeIamPolicyLongrunningRequest, CallSettings)
// Additional: AnalyzeIamPolicyLongrunningAsync(AnalyzeIamPolicyLongrunningRequest, CancellationToken)
// Create client
AssetServiceClient assetServiceClient = await AssetServiceClient.CreateAsync();
// Initialize request argument(s)
AnalyzeIamPolicyLongrunningRequest request = new AnalyzeIamPolicyLongrunningRequest
{
AnalysisQuery = new IamPolicyAnalysisQuery(),
OutputConfig = new IamPolicyAnalysisOutputConfig(),
};
// Make the request
Operation<AnalyzeIamPolicyLongrunningResponse, AnalyzeIamPolicyLongrunningMetadata> response = await assetServiceClient.AnalyzeIamPolicyLongrunningAsync(request);
// Poll until the returned long-running operation is complete
Operation<AnalyzeIamPolicyLongrunningResponse, AnalyzeIamPolicyLongrunningMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
AnalyzeIamPolicyLongrunningResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<AnalyzeIamPolicyLongrunningResponse, AnalyzeIamPolicyLongrunningMetadata> retrievedResponse = await assetServiceClient.PollOnceAnalyzeIamPolicyLongrunningAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
AnalyzeIamPolicyLongrunningResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for AnalyzeMove</summary>
public void AnalyzeMoveRequestObject()
{
// Snippet: AnalyzeMove(AnalyzeMoveRequest, CallSettings)
// Create client
AssetServiceClient assetServiceClient = AssetServiceClient.Create();
// Initialize request argument(s)
AnalyzeMoveRequest request = new AnalyzeMoveRequest
{
Resource = "",
DestinationParent = "",
View = AnalyzeMoveRequest.Types.AnalysisView.Unspecified,
};
// Make the request
AnalyzeMoveResponse response = assetServiceClient.AnalyzeMove(request);
// End snippet
}
/// <summary>Snippet for AnalyzeMoveAsync</summary>
public async Task AnalyzeMoveRequestObjectAsync()
{
// Snippet: AnalyzeMoveAsync(AnalyzeMoveRequest, CallSettings)
// Additional: AnalyzeMoveAsync(AnalyzeMoveRequest, CancellationToken)
// Create client
AssetServiceClient assetServiceClient = await AssetServiceClient.CreateAsync();
// Initialize request argument(s)
AnalyzeMoveRequest request = new AnalyzeMoveRequest
{
Resource = "",
DestinationParent = "",
View = AnalyzeMoveRequest.Types.AnalysisView.Unspecified,
};
// Make the request
AnalyzeMoveResponse response = await assetServiceClient.AnalyzeMoveAsync(request);
// End snippet
}
}
}
| |
#if !SILVERLIGHT
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using ServiceStack.Service;
using ServiceStack.ServiceHost;
using ServiceStack.Text;
namespace ServiceStack.Common.Web
{
public class HttpResult
: IHttpResult, IStreamWriter
{
public HttpResult()
: this((object)null, null)
{
}
public HttpResult(object response)
: this(response, null)
{
}
public HttpResult(object response, string contentType)
: this(response, contentType, HttpStatusCode.OK)
{
}
public HttpResult(HttpStatusCode statusCode, string statusDescription)
: this()
{
StatusCode = statusCode;
StatusDescription = statusDescription;
}
public HttpResult(object response, HttpStatusCode statusCode)
: this(response, null, statusCode) {}
public HttpResult(object response, string contentType, HttpStatusCode statusCode)
{
this.Headers = new Dictionary<string, string>();
this.ResponseFilter = HttpResponseFilter.Instance;
this.Response = response;
this.ContentType = contentType;
this.StatusCode = statusCode;
}
public HttpResult(FileInfo fileResponse)
: this(fileResponse, false, MimeTypes.GetMimeType(fileResponse.Name)) { }
public HttpResult(FileInfo fileResponse, bool asAttachment)
: this(fileResponse, asAttachment, MimeTypes.GetMimeType(fileResponse.Name)) { }
public HttpResult(FileInfo fileResponse, bool asAttachment, string contentType)
: this(null, contentType, HttpStatusCode.OK)
{
this.FileInfo = fileResponse;
if (!asAttachment) return;
var headerValue =
"attachment; " +
"filename=\"" + fileResponse.Name + "\"; " +
"size=" + fileResponse.Length + "; " +
"creation-date=" + fileResponse.CreationTimeUtc.ToString("R").Replace(",","") + "; " +
"modification-date=" + fileResponse.LastWriteTimeUtc.ToString("R").Replace(",", "") + "; " +
"read-date=" + fileResponse.LastAccessTimeUtc.ToString("R").Replace(",", "");
this.Headers = new Dictionary<string, string> {
{ HttpHeaders.ContentDisposition, headerValue },
};
}
public HttpResult(Stream responseStream, string contentType)
: this(null, contentType, HttpStatusCode.OK)
{
this.ResponseStream = responseStream;
}
public HttpResult(string responseText, string contentType)
: this(null, contentType, HttpStatusCode.OK)
{
this.ResponseText = responseText;
}
public string ResponseText { get; private set; }
public Stream ResponseStream { get; private set; }
public FileInfo FileInfo { get; private set; }
public string ContentType { get; set; }
public Dictionary<string, string> Headers { get; private set; }
public DateTime LastModified
{
set
{
this.Headers[HttpHeaders.LastModified] = value.ToUniversalTime().ToString("r");
}
}
public string Location
{
set
{
if (StatusCode == HttpStatusCode.OK)
StatusCode = HttpStatusCode.Redirect;
this.Headers[HttpHeaders.Location] = value;
}
}
public void SetPermanentCookie(string name, string value)
{
SetCookie(name, value, DateTime.UtcNow.AddYears(20), null);
}
public void SetPermanentCookie(string name, string value, string path)
{
SetCookie(name, value, DateTime.UtcNow.AddYears(20), path);
}
public void SetSessionCookie(string name, string value)
{
SetSessionCookie(name, value, null);
}
public void SetSessionCookie(string name, string value, string path)
{
path = path ?? "/";
this.Headers[HttpHeaders.SetCookie] = string.Format("{0}={1};path=" + path, name, value);
}
public void SetCookie(string name, string value, TimeSpan expiresIn, string path)
{
var expiresAt = DateTime.UtcNow.Add(expiresIn);
SetCookie(name, value, expiresAt, path);
}
public void SetCookie(string name, string value, DateTime expiresAt, string path)
{
path = path ?? "/";
var cookie = string.Format("{0}={1};expires={2};path={3}", name, value, expiresAt.ToString("R"), path);
this.Headers[HttpHeaders.SetCookie] = cookie;
}
public void DeleteCookie(string name)
{
var cookie = string.Format("{0}=;expires={1};path=/", name, DateTime.UtcNow.AddDays(-1).ToString("R"));
this.Headers[HttpHeaders.SetCookie] = cookie;
}
public IDictionary<string, string> Options
{
get { return this.Headers; }
}
public HttpStatusCode StatusCode { get; set; }
public string StatusDescription { get; set; }
public object Response { get; set; }
public IContentTypeWriter ResponseFilter { get; set; }
public IRequestContext RequestContext { get; set; }
public string TemplateName { get; set; }
public void WriteTo(Stream responseStream)
{
if (this.FileInfo != null)
{
using (var fs = this.FileInfo.OpenRead())
{
fs.WriteTo(responseStream);
responseStream.Flush();
}
return;
}
if (this.ResponseStream != null)
{
this.ResponseStream.WriteTo(responseStream);
responseStream.Flush();
try
{
this.ResponseStream.Dispose();
}
catch { /*ignore*/ }
return;
}
if (this.ResponseText != null)
{
var bytes = System.Text.Encoding.UTF8.GetBytes(this.ResponseText);
responseStream.Write(bytes, 0, bytes.Length);
responseStream.Flush();
return;
}
if (this.ResponseFilter == null)
throw new ArgumentNullException("ResponseFilter");
if (this.RequestContext == null)
throw new ArgumentNullException("RequestContext");
var bytesResponse = this.Response as byte[];
if (bytesResponse != null)
{
responseStream.Write(bytesResponse, 0, bytesResponse.Length);
return;
}
ResponseFilter.SerializeToStream(this.RequestContext, this.Response, responseStream);
}
public static HttpResult Status201Created(object response, string newLocationUri)
{
return new HttpResult(response)
{
StatusCode = HttpStatusCode.Created,
Headers =
{
{ HttpHeaders.Location, newLocationUri },
}
};
}
}
}
#endif
| |
/*
* 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.Globalization;
using System.Net;
using System.Reflection;
using System.Xml;
using log4net;
using OpenMetaverse;
namespace OpenSim.Framework
{
public class ConfigurationMember
{
#region Delegates
public delegate bool ConfigurationOptionResult(string configuration_key, object configuration_result);
public delegate void ConfigurationOptionsLoad();
#endregion
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private int cE = 0;
private string configurationDescription = String.Empty;
private string configurationFilename = String.Empty;
private XmlNode configurationFromXMLNode = null;
private List<ConfigurationOption> configurationOptions = new List<ConfigurationOption>();
private IGenericConfig configurationPlugin = null;
/// <summary>
/// This is the default configuration DLL loaded
/// </summary>
private string configurationPluginFilename = "OpenSim.Framework.Configuration.XML.dll";
private ConfigurationOptionsLoad loadFunction;
private ConfigurationOptionResult resultFunction;
private bool useConsoleToPromptOnError = true;
public ConfigurationMember(string configuration_filename, string configuration_description,
ConfigurationOptionsLoad load_function, ConfigurationOptionResult result_function, bool use_console_to_prompt_on_error)
{
configurationFilename = configuration_filename;
configurationDescription = configuration_description;
loadFunction = load_function;
resultFunction = result_function;
useConsoleToPromptOnError = use_console_to_prompt_on_error;
}
public ConfigurationMember(XmlNode configuration_xml, string configuration_description,
ConfigurationOptionsLoad load_function, ConfigurationOptionResult result_function, bool use_console_to_prompt_on_error)
{
configurationFilename = String.Empty;
configurationFromXMLNode = configuration_xml;
configurationDescription = configuration_description;
loadFunction = load_function;
resultFunction = result_function;
useConsoleToPromptOnError = use_console_to_prompt_on_error;
}
public void setConfigurationFilename(string filename)
{
configurationFilename = filename;
}
public void setConfigurationDescription(string desc)
{
configurationDescription = desc;
}
public void setConfigurationResultFunction(ConfigurationOptionResult result)
{
resultFunction = result;
}
public void forceConfigurationPluginLibrary(string dll_filename)
{
configurationPluginFilename = dll_filename;
}
private void checkAndAddConfigOption(ConfigurationOption option)
{
if ((!String.IsNullOrEmpty(option.configurationKey) && !String.IsNullOrEmpty(option.configurationQuestion)) ||
(!String.IsNullOrEmpty(option.configurationKey) && option.configurationUseDefaultNoPrompt))
{
if (!configurationOptions.Contains(option))
{
configurationOptions.Add(option);
}
}
else
{
m_log.Info(
"[CONFIG]: Required fields for adding a configuration option is invalid. Will not add this option (" +
option.configurationKey + ")");
}
}
public void addConfigurationOption(string configuration_key,
ConfigurationOption.ConfigurationTypes configuration_type,
string configuration_question, string configuration_default,
bool use_default_no_prompt)
{
ConfigurationOption configOption = new ConfigurationOption();
configOption.configurationKey = configuration_key;
configOption.configurationQuestion = configuration_question;
configOption.configurationDefault = configuration_default;
configOption.configurationType = configuration_type;
configOption.configurationUseDefaultNoPrompt = use_default_no_prompt;
configOption.shouldIBeAsked = null; //Assumes true, I can ask whenever
checkAndAddConfigOption(configOption);
}
public void addConfigurationOption(string configuration_key,
ConfigurationOption.ConfigurationTypes configuration_type,
string configuration_question, string configuration_default,
bool use_default_no_prompt,
ConfigurationOption.ConfigurationOptionShouldBeAsked shouldIBeAskedDelegate)
{
ConfigurationOption configOption = new ConfigurationOption();
configOption.configurationKey = configuration_key;
configOption.configurationQuestion = configuration_question;
configOption.configurationDefault = configuration_default;
configOption.configurationType = configuration_type;
configOption.configurationUseDefaultNoPrompt = use_default_no_prompt;
configOption.shouldIBeAsked = shouldIBeAskedDelegate;
checkAndAddConfigOption(configOption);
}
// TEMP - REMOVE
public void performConfigurationRetrieve()
{
if (cE > 1)
m_log.Error("[CONFIG]: READING CONFIGURATION COUT: " + cE.ToString());
configurationPlugin = LoadConfigDll(configurationPluginFilename);
configurationOptions.Clear();
if (loadFunction == null)
{
m_log.Error("[CONFIG]: Load Function for '" + configurationDescription +
"' is null. Refusing to run configuration.");
return;
}
if (resultFunction == null)
{
m_log.Error("[CONFIG]: Result Function for '" + configurationDescription +
"' is null. Refusing to run configuration.");
return;
}
//m_log.Debug("[CONFIG]: Calling Configuration Load Function...");
loadFunction();
if (configurationOptions.Count <= 0)
{
m_log.Error("[CONFIG]: No configuration options were specified for '" + configurationOptions +
"'. Refusing to continue configuration.");
return;
}
bool useFile = true;
if (configurationPlugin == null)
{
m_log.Error("[CONFIG]: Configuration Plugin NOT LOADED!");
return;
}
if (!String.IsNullOrWhiteSpace(configurationFilename))
{
configurationPlugin.SetFileName(configurationFilename);
try
{
configurationPlugin.LoadData();
useFile = true;
}
catch (XmlException e)
{
m_log.WarnFormat("[CONFIG]: Not using {0}: {1}",
configurationFilename,
e.Message.ToString());
//m_log.Error("Error loading " + configurationFilename + ": " + e.ToString());
useFile = false;
}
}
else
{
if (configurationFromXMLNode != null)
{
m_log.Info("[CONFIG]: Loading from XML Node, will not save to the file");
configurationPlugin.LoadDataFromString(configurationFromXMLNode.OuterXml);
}
m_log.Info("[CONFIG]: XML Configuration Filename is not valid; will not save to the file.");
useFile = false;
}
foreach (ConfigurationOption configOption in configurationOptions)
{
bool convertSuccess = false;
object return_result = null;
string errorMessage = String.Empty;
bool ignoreNextFromConfig = false;
while (convertSuccess == false)
{
string console_result = String.Empty;
string attribute = null;
if (useFile || configurationFromXMLNode != null)
{
if (!ignoreNextFromConfig)
{
attribute = configurationPlugin.GetAttribute(configOption.configurationKey);
}
else
{
ignoreNextFromConfig = false;
}
}
if (attribute == null)
{
if (configOption.configurationUseDefaultNoPrompt || useConsoleToPromptOnError == false)
{
console_result = configOption.configurationDefault;
}
else
{
if ((configOption.shouldIBeAsked != null &&
configOption.shouldIBeAsked(configOption.configurationKey)) ||
configOption.shouldIBeAsked == null)
{
if (!String.IsNullOrWhiteSpace(configurationDescription))
{
console_result =
MainConsole.Instance.CmdPrompt(
configurationDescription + ": " + configOption.configurationQuestion,
configOption.configurationDefault);
}
else
{
console_result =
MainConsole.Instance.CmdPrompt(configOption.configurationQuestion,
configOption.configurationDefault);
}
}
else
{
//Dont Ask! Just use default
console_result = configOption.configurationDefault;
}
}
}
else
{
console_result = attribute;
}
// If the first character of a multicharacter string is a "$", assume it's the name of an environment variable and substitute with the value of that variable.
if (console_result.StartsWith("$", StringComparison.InvariantCulture) && console_result.Length > 1)
{
// Using a second $ to be an escape character was experimented with, but that would require modifying the write process to re-apply the escape character. Over-all escapes seem too fragile, and the below code handles it cleanly. If the admin wants to use a value that collides with an environment variable, then the admin can make sure to unset it first.
var env_var_key = console_result.Substring(1);
var env_var_value = Environment.GetEnvironmentVariable(env_var_key);
if (env_var_value != null)
{
// Log the use of an environment variable just in case someone didn't expect it.
m_log.Info($"[CONFIG]: Parameter [{configOption.configurationKey}] started with '$'. Value replaced with environment variable '{env_var_key}' value '{env_var_value}'.");
console_result = env_var_value;
}
else
{
// Unless there is no such variable, in which case just move on with the original and let the user know that happened.
m_log.Warn($"[CONFIG]: Parameter [{configOption.configurationKey}] started with '$', however there was no environment variable found with the name '{env_var_key}'.");
}
}
switch (configOption.configurationType)
{
case ConfigurationOption.ConfigurationTypes.TYPE_STRING:
return_result = console_result;
convertSuccess = true;
break;
case ConfigurationOption.ConfigurationTypes.TYPE_STRING_NOT_EMPTY:
if (!String.IsNullOrEmpty(console_result))
{
return_result = console_result;
convertSuccess = true;
}
errorMessage = "a string that is not empty";
break;
case ConfigurationOption.ConfigurationTypes.TYPE_BOOLEAN:
bool boolResult;
if (Boolean.TryParse(console_result, out boolResult))
{
convertSuccess = true;
return_result = boolResult;
}
errorMessage = "'true' or 'false' (Boolean)";
break;
case ConfigurationOption.ConfigurationTypes.TYPE_BYTE:
byte byteResult;
if (Byte.TryParse(console_result, out byteResult))
{
convertSuccess = true;
return_result = byteResult;
}
errorMessage = "a byte (Byte)";
break;
case ConfigurationOption.ConfigurationTypes.TYPE_CHARACTER:
char charResult;
if (Char.TryParse(console_result, out charResult))
{
convertSuccess = true;
return_result = charResult;
}
errorMessage = "a character (Char)";
break;
case ConfigurationOption.ConfigurationTypes.TYPE_INT16:
short shortResult;
if (Int16.TryParse(console_result, out shortResult))
{
convertSuccess = true;
return_result = shortResult;
}
errorMessage = "a signed 32 bit integer (short)";
break;
case ConfigurationOption.ConfigurationTypes.TYPE_INT32:
int intResult;
if (Int32.TryParse(console_result, out intResult))
{
convertSuccess = true;
return_result = intResult;
}
errorMessage = "a signed 32 bit integer (int)";
break;
case ConfigurationOption.ConfigurationTypes.TYPE_INT64:
long longResult;
if (Int64.TryParse(console_result, out longResult))
{
convertSuccess = true;
return_result = longResult;
}
errorMessage = "a signed 32 bit integer (long)";
break;
case ConfigurationOption.ConfigurationTypes.TYPE_IP_ADDRESS:
IPAddress ipAddressResult;
if (IPAddress.TryParse(console_result, out ipAddressResult))
{
convertSuccess = true;
return_result = ipAddressResult;
}
errorMessage = "an IP Address (IPAddress)";
break;
case ConfigurationOption.ConfigurationTypes.TYPE_UUID:
UUID uuidResult;
if (UUID.TryParse(console_result, out uuidResult))
{
convertSuccess = true;
return_result = uuidResult;
}
errorMessage = "a UUID (UUID)";
break;
case ConfigurationOption.ConfigurationTypes.TYPE_UUID_NULL_FREE:
UUID uuidResult2;
if (UUID.TryParse(console_result, out uuidResult2))
{
convertSuccess = true;
if (uuidResult2 == UUID.Zero)
uuidResult2 = UUID.Random();
return_result = uuidResult2;
}
errorMessage = "a non-null UUID (UUID)";
break;
case ConfigurationOption.ConfigurationTypes.TYPE_Vector3:
Vector3 vectorResult;
if (Vector3.TryParse(console_result, out vectorResult))
{
convertSuccess = true;
return_result = vectorResult;
}
errorMessage = "a vector (Vector3)";
break;
case ConfigurationOption.ConfigurationTypes.TYPE_UINT16:
ushort ushortResult;
if (UInt16.TryParse(console_result, out ushortResult))
{
convertSuccess = true;
return_result = ushortResult;
}
errorMessage = "an unsigned 16 bit integer (ushort)";
break;
case ConfigurationOption.ConfigurationTypes.TYPE_UINT32:
uint uintResult;
if (UInt32.TryParse(console_result, out uintResult))
{
convertSuccess = true;
return_result = uintResult;
}
errorMessage = "an unsigned 32 bit integer (uint)";
break;
case ConfigurationOption.ConfigurationTypes.TYPE_UINT64:
ulong ulongResult;
if (UInt64.TryParse(console_result, out ulongResult))
{
convertSuccess = true;
return_result = ulongResult;
}
errorMessage = "an unsigned 64 bit integer (ulong)";
break;
case ConfigurationOption.ConfigurationTypes.TYPE_FLOAT:
float floatResult;
if (
float.TryParse(console_result, NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign, Culture.NumberFormatInfo,
out floatResult))
{
convertSuccess = true;
return_result = floatResult;
}
errorMessage = "a single-precision floating point number (float)";
break;
case ConfigurationOption.ConfigurationTypes.TYPE_DOUBLE:
double doubleResult;
if (
Double.TryParse(console_result, NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign, Culture.NumberFormatInfo,
out doubleResult))
{
convertSuccess = true;
return_result = doubleResult;
}
errorMessage = "an double-precision floating point number (double)";
break;
}
if (convertSuccess)
{
if (useFile)
{
configurationPlugin.SetAttribute(configOption.configurationKey, console_result);
}
if (!resultFunction(configOption.configurationKey, return_result))
{
m_log.Info(
"[CONFIG]: The handler for the last configuration option denied that input, please try again.");
convertSuccess = false;
ignoreNextFromConfig = true;
}
}
else
{
if (configOption.configurationUseDefaultNoPrompt)
{
m_log.Error(string.Format(
"[CONFIG]: [{3}]:[{1}] is not valid default for parameter [{0}].\nThe configuration result must be parsable to {2}.\n",
configOption.configurationKey, console_result, errorMessage,
configurationFilename));
convertSuccess = true;
}
else
{
m_log.Warn(string.Format(
"[CONFIG]: [{3}]:[{1}] is not a valid value [{0}].\nThe configuration result must be parsable to {2}.\n",
configOption.configurationKey, console_result, errorMessage,
configurationFilename));
ignoreNextFromConfig = true;
}
}
}
}
if (useFile)
{
configurationPlugin.Commit();
configurationPlugin.Close();
}
}
private static IGenericConfig LoadConfigDll(string dllName)
{
Assembly pluginAssembly = Assembly.LoadFrom(dllName);
IGenericConfig plug = null;
foreach (Type pluginType in pluginAssembly.GetTypes())
{
if (pluginType.IsPublic)
{
if (!pluginType.IsAbstract)
{
if (typeof(IGenericConfig).IsAssignableFrom(pluginType))
{
plug =
(IGenericConfig) Activator.CreateInstance(pluginAssembly.GetType(pluginType.ToString()));
}
}
}
}
pluginAssembly = null;
return plug;
}
public void forceUpdateConfigurationOneOption(string configuration_key, string configuration_value)
{
configurationPlugin.LoadData();
configurationPlugin.SetAttribute(configuration_key, configuration_value);
configurationPlugin.Commit();
configurationPlugin.Close();
}
public void forceUpdateConfigurationOptions(Dictionary<string,string>options)
{
configurationPlugin.LoadData();
foreach (KeyValuePair<string,string>option in options)
configurationPlugin.SetAttribute(option.Key, option.Value);
configurationPlugin.Commit();
configurationPlugin.Close();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.AccessControl;
using DokanNet;
using Microsoft.Win32;
using FileAccess = DokanNet.FileAccess;
namespace RegistryFS
{
internal class RFS : IDokanOperations
{
#region DokanOperations member
private readonly Dictionary<string, RegistryKey> TopDirectory;
public RFS()
{
TopDirectory = new Dictionary<string, RegistryKey>
{
["ClassesRoot"] = Registry.ClassesRoot,
["CurrentUser"] = Registry.CurrentUser,
["CurrentConfig"] = Registry.CurrentConfig,
["LocalMachine"] = Registry.LocalMachine,
["Users"] = Registry.Users
};
}
public void Cleanup(string filename, DokanFileInfo info)
{
}
public void CloseFile(string filename, DokanFileInfo info)
{
}
public NtStatus CreateFile(
string filename,
FileAccess access,
FileShare share,
FileMode mode,
FileOptions options,
FileAttributes attributes,
DokanFileInfo info)
{
if (info.IsDirectory && mode == FileMode.CreateNew)
return DokanResult.AccessDenied;
return DokanResult.Success;
}
public NtStatus DeleteDirectory(string filename, DokanFileInfo info)
{
return DokanResult.Error;
}
public NtStatus DeleteFile(string filename, DokanFileInfo info)
{
return DokanResult.Error;
}
private RegistryKey GetRegistoryEntry(string name)
{
Console.WriteLine($"GetRegistoryEntry : {name}");
var top = name.IndexOf('\\', 1) - 1;
if (top < 0)
top = name.Length - 1;
var topname = name.Substring(1, top);
var sub = name.IndexOf('\\', 1);
if (TopDirectory.ContainsKey(topname))
{
if (sub == -1)
return TopDirectory[topname];
else
return TopDirectory[topname].OpenSubKey(name.Substring(sub + 1));
}
return null;
}
public NtStatus FlushFileBuffers(
string filename,
DokanFileInfo info)
{
return DokanResult.Error;
}
public NtStatus FindFiles(
string filename,
out IList<FileInformation> files,
DokanFileInfo info)
{
files = new List<FileInformation>();
if (filename == "\\")
{
foreach (var name in TopDirectory.Keys)
{
var finfo = new FileInformation
{
FileName = name,
Attributes = FileAttributes.Directory,
LastAccessTime = DateTime.Now,
LastWriteTime = null,
CreationTime = null
};
files.Add(finfo);
}
return DokanResult.Success;
}
else
{
var key = GetRegistoryEntry(filename);
if (key == null)
return DokanResult.Error;
foreach (var name in key.GetSubKeyNames())
{
var finfo = new FileInformation
{
FileName = name,
Attributes = FileAttributes.Directory,
LastAccessTime = DateTime.Now,
LastWriteTime = null,
CreationTime = null
};
files.Add(finfo);
}
foreach (var name in key.GetValueNames())
{
var finfo = new FileInformation
{
FileName = name,
Attributes = FileAttributes.Normal,
LastAccessTime = DateTime.Now,
LastWriteTime = null,
CreationTime = null
};
files.Add(finfo);
}
return DokanResult.Success;
}
}
public NtStatus GetFileInformation(
string filename,
out FileInformation fileinfo,
DokanFileInfo info)
{
fileinfo = new FileInformation {FileName = filename};
if (filename == "\\")
{
fileinfo.Attributes = FileAttributes.Directory;
fileinfo.LastAccessTime = DateTime.Now;
fileinfo.LastWriteTime = null;
fileinfo.CreationTime = null;
return DokanResult.Success;
}
var key = GetRegistoryEntry(filename);
if (key == null)
return DokanResult.Error;
fileinfo.Attributes = FileAttributes.Directory;
fileinfo.LastAccessTime = DateTime.Now;
fileinfo.LastWriteTime = null;
fileinfo.CreationTime = null;
return DokanResult.Success;
}
public NtStatus LockFile(
string filename,
long offset,
long length,
DokanFileInfo info)
{
return DokanResult.Success;
}
public NtStatus MoveFile(
string filename,
string newname,
bool replace,
DokanFileInfo info)
{
return DokanResult.Error;
}
public NtStatus ReadFile(
string filename,
byte[] buffer,
out int readBytes,
long offset,
DokanFileInfo info)
{
readBytes = 0;
return DokanResult.Error;
}
public NtStatus SetEndOfFile(string filename, long length, DokanFileInfo info)
{
return DokanResult.Error;
}
public NtStatus SetAllocationSize(string filename, long length, DokanFileInfo info)
{
return DokanResult.Error;
}
public NtStatus SetFileAttributes(
string filename,
FileAttributes attr,
DokanFileInfo info)
{
return DokanResult.Error;
}
public NtStatus SetFileTime(
string filename,
DateTime? ctime,
DateTime? atime,
DateTime? mtime,
DokanFileInfo info)
{
return DokanResult.Error;
}
public NtStatus UnlockFile(string filename, long offset, long length, DokanFileInfo info)
{
return DokanResult.Success;
}
public NtStatus Mounted(DokanFileInfo info)
{
return DokanResult.Success;
}
public NtStatus Unmounted(DokanFileInfo info)
{
return DokanResult.Success;
}
public NtStatus GetDiskFreeSpace(
out long freeBytesAvailable,
out long totalBytes,
out long totalFreeBytes,
DokanFileInfo info)
{
freeBytesAvailable = 512*1024*1024;
totalBytes = 1024*1024*1024;
totalFreeBytes = 512*1024*1024;
return DokanResult.Success;
}
public NtStatus WriteFile(
string filename,
byte[] buffer,
out int writtenBytes,
long offset,
DokanFileInfo info)
{
writtenBytes = 0;
return DokanResult.Error;
}
public NtStatus GetVolumeInformation(out string volumeLabel, out FileSystemFeatures features,
out string fileSystemName, DokanFileInfo info)
{
volumeLabel = "RFS";
features = FileSystemFeatures.None;
fileSystemName = string.Empty;
return DokanResult.Error;
}
public NtStatus GetFileSecurity(string fileName, out FileSystemSecurity security, AccessControlSections sections,
DokanFileInfo info)
{
security = null;
return DokanResult.Error;
}
public NtStatus SetFileSecurity(string fileName, FileSystemSecurity security, AccessControlSections sections,
DokanFileInfo info)
{
return DokanResult.Error;
}
public NtStatus EnumerateNamedStreams(string fileName, IntPtr enumContext, out string streamName,
out long streamSize, DokanFileInfo info)
{
streamName = string.Empty;
streamSize = 0;
return DokanResult.NotImplemented;
}
public NtStatus FindStreams(string fileName, out IList<FileInformation> streams, DokanFileInfo info)
{
streams = new FileInformation[0];
return DokanResult.NotImplemented;
}
public NtStatus FindFilesWithPattern(string fileName, string searchPattern, out IList<FileInformation> files,
DokanFileInfo info)
{
files = new FileInformation[0];
return DokanResult.NotImplemented;
}
#endregion DokanOperations member
}
internal class Program
{
private static void Main()
{
try
{
var rfs = new RFS();
rfs.Mount("r:\\", DokanOptions.DebugMode | DokanOptions.StderrOutput);
Console.WriteLine(@"Success");
}
catch (DokanException ex)
{
Console.WriteLine(@"Error: " + ex.Message);
}
}
}
}
| |
//
// Copyright (C) Microsoft. All rights reserved.
//
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Reflection;
namespace System.Management.Automation
{
/// <summary>
/// Internal wrapper for third-party adapters (PSPropertyAdapter)
/// </summary>
internal class ThirdPartyAdapter : PropertyOnlyAdapter
{
internal ThirdPartyAdapter(Type adaptedType, PSPropertyAdapter externalAdapter)
{
AdaptedType = adaptedType;
_externalAdapter = externalAdapter;
}
/// <summary>
/// The type this instance is adapting
/// </summary>
internal Type AdaptedType { get; }
/// <summary>
/// The type of the external adapter
/// </summary>
internal Type ExternalAdapterType
{
get
{
return _externalAdapter.GetType();
}
}
/// <summary>
/// Returns the TypeNameHierarchy out of an object
/// </summary>
protected override IEnumerable<string> GetTypeNameHierarchy(object obj)
{
Collection<string> typeNameHierarchy = null;
try
{
typeNameHierarchy = _externalAdapter.GetTypeNameHierarchy(obj);
}
catch (Exception exception)
{
CommandProcessorBase.CheckForSevereException(exception);
throw new ExtendedTypeSystemException(
"PSPropertyAdapter.GetTypeNameHierarchyError",
exception,
ExtendedTypeSystem.GetTypeNameHierarchyError, obj.ToString());
}
if (typeNameHierarchy == null)
{
throw new ExtendedTypeSystemException(
"PSPropertyAdapter.NullReturnValueError",
null,
ExtendedTypeSystem.NullReturnValueError, "PSPropertyAdapter.GetTypeNameHierarchy");
}
return typeNameHierarchy;
}
/// <summary>
/// Retrieves all the properties available in the object.
/// </summary>
protected override void DoAddAllProperties<T>(object obj, PSMemberInfoInternalCollection<T> members)
{
Collection<PSAdaptedProperty> properties = null;
try
{
properties = _externalAdapter.GetProperties(obj);
}
catch (Exception exception)
{
CommandProcessorBase.CheckForSevereException(exception);
throw new ExtendedTypeSystemException(
"PSPropertyAdapter.GetProperties",
exception,
ExtendedTypeSystem.GetProperties, obj.ToString());
}
if (properties == null)
{
throw new ExtendedTypeSystemException(
"PSPropertyAdapter.NullReturnValueError",
null,
ExtendedTypeSystem.NullReturnValueError, "PSPropertyAdapter.GetProperties");
}
foreach (PSAdaptedProperty property in properties)
{
InitializeProperty(property, obj);
members.Add(property as T);
}
}
/// <summary>
/// Returns null if propertyName is not a property in the adapter or
/// the corresponding PSProperty with its adapterData set to information
/// to be used when retrieving the property.
/// </summary>
protected override PSProperty DoGetProperty(object obj, string propertyName)
{
PSAdaptedProperty property = null;
try
{
property = _externalAdapter.GetProperty(obj, propertyName);
}
catch (Exception exception)
{
CommandProcessorBase.CheckForSevereException(exception);
throw new ExtendedTypeSystemException(
"PSPropertyAdapter.GetProperty",
exception,
ExtendedTypeSystem.GetProperty, propertyName, obj.ToString());
}
if (property != null)
{
InitializeProperty(property, obj);
}
return property;
}
/// <summary>
/// Ensures that the adapter and base object are set in the given PSAdaptedProperty
/// </summary>
private void InitializeProperty(PSAdaptedProperty property, object baseObject)
{
if (property.adapter == null)
{
property.adapter = this;
property.baseObject = baseObject;
}
}
/// <summary>
/// Returns true if the property is settable
/// </summary>
protected override bool PropertyIsSettable(PSProperty property)
{
PSAdaptedProperty adaptedProperty = property as PSAdaptedProperty;
Diagnostics.Assert(adaptedProperty != null, "ThirdPartyAdapter should only receive PSAdaptedProperties");
try
{
return _externalAdapter.IsSettable(adaptedProperty);
}
catch (Exception exception)
{
CommandProcessorBase.CheckForSevereException(exception);
throw new ExtendedTypeSystemException(
"PSPropertyAdapter.PropertyIsSettableError",
exception,
ExtendedTypeSystem.PropertyIsSettableError, property.Name);
}
}
/// <summary>
/// Returns true if the property is gettable
/// </summary>
protected override bool PropertyIsGettable(PSProperty property)
{
PSAdaptedProperty adaptedProperty = property as PSAdaptedProperty;
Diagnostics.Assert(adaptedProperty != null, "ThirdPartyAdapter should only receive PSAdaptedProperties");
try
{
return _externalAdapter.IsGettable(adaptedProperty);
}
catch (Exception exception)
{
CommandProcessorBase.CheckForSevereException(exception);
throw new ExtendedTypeSystemException(
"PSPropertyAdapter.PropertyIsGettableError",
exception,
ExtendedTypeSystem.PropertyIsGettableError, property.Name);
}
}
/// <summary>
/// Returns the value from a property coming from a previous call to DoGetProperty
/// </summary>
protected override object PropertyGet(PSProperty property)
{
PSAdaptedProperty adaptedProperty = property as PSAdaptedProperty;
Diagnostics.Assert(adaptedProperty != null, "ThirdPartyAdapter should only receive PSAdaptedProperties");
try
{
return _externalAdapter.GetPropertyValue(adaptedProperty);
}
catch (Exception exception)
{
CommandProcessorBase.CheckForSevereException(exception);
throw new ExtendedTypeSystemException(
"PSPropertyAdapter.PropertyGetError",
exception,
ExtendedTypeSystem.PropertyGetError, property.Name);
}
}
/// <summary>
/// Sets the value of a property coming from a previous call to DoGetProperty
/// </summary>
protected override void PropertySet(PSProperty property, object setValue, bool convertIfPossible)
{
PSAdaptedProperty adaptedProperty = property as PSAdaptedProperty;
Diagnostics.Assert(adaptedProperty != null, "ThirdPartyAdapter should only receive PSAdaptedProperties");
try
{
_externalAdapter.SetPropertyValue(adaptedProperty, setValue);
}
catch (SetValueException) { throw; }
catch (Exception exception)
{
CommandProcessorBase.CheckForSevereException(exception);
throw new ExtendedTypeSystemException(
"PSPropertyAdapter.PropertySetError",
exception,
ExtendedTypeSystem.PropertySetError, property.Name);
}
}
/// <summary>
/// Returns the name of the type corresponding to the property
/// </summary>
protected override string PropertyType(PSProperty property, bool forDisplay)
{
PSAdaptedProperty adaptedProperty = property as PSAdaptedProperty;
Diagnostics.Assert(adaptedProperty != null, "ThirdPartyAdapter should only receive PSAdaptedProperties");
string propertyTypeName = null;
try
{
propertyTypeName = _externalAdapter.GetPropertyTypeName(adaptedProperty);
}
catch (Exception exception)
{
CommandProcessorBase.CheckForSevereException(exception);
throw new ExtendedTypeSystemException(
"PSPropertyAdapter.PropertyTypeError",
exception,
ExtendedTypeSystem.PropertyTypeError, property.Name);
}
return propertyTypeName ?? "System.Object";
}
private PSPropertyAdapter _externalAdapter;
}
/// <summary>
/// User-defined property adapter
/// </summary>
/// <remarks>
/// This class is used to expose a simplified version of the type adapter API
/// </remarks>
public abstract class PSPropertyAdapter
{
/// <summary>
/// Returns the type hierarchy for the given object
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "object")]
public virtual Collection<string> GetTypeNameHierarchy(object baseObject)
{
if (baseObject == null)
{
throw new ArgumentNullException("baseObject");
}
Collection<string> types = new Collection<String>();
for (Type type = baseObject.GetType(); type != null; type = type.GetTypeInfo().BaseType)
{
types.Add(type.FullName);
}
return types;
}
/// <summary>
/// Returns a list of the adapted properties
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "object")]
public abstract Collection<PSAdaptedProperty> GetProperties(object baseObject);
/// <summary>
/// Returns a specific property, or null if the base object does not contain the given property
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "object")]
public abstract PSAdaptedProperty GetProperty(object baseObject, string propertyName);
/// <summary>
/// Returns true if the given property is settable
/// </summary>
public abstract bool IsSettable(PSAdaptedProperty adaptedProperty);
/// <summary>
/// Returns true if the given property is gettable
/// </summary>
public abstract bool IsGettable(PSAdaptedProperty adaptedProperty);
/// <summary>
/// Returns the value of a given property
/// </summary>
public abstract object GetPropertyValue(PSAdaptedProperty adaptedProperty);
/// <summary>
/// Sets the value of a given property
/// </summary>
public abstract void SetPropertyValue(PSAdaptedProperty adaptedProperty, object value);
/// <summary>
/// Returns the type for a given property
/// </summary>
public abstract string GetPropertyTypeName(PSAdaptedProperty adaptedProperty);
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AspenTech.SmartObjects.Client.Datalake;
using AspenTech.SmartObjects.Client.Tests.Common;
using FluentAssertions;
using NUnit.Framework;
namespace AspenTech.SmartObjects.Client.ITTest.Datalake
{
[TestFixture]
public class DatalakeClientTests : DatasetTests
{
private readonly ISmartObjectsClient _client;
public DatalakeClientTests()
{
this._client = ITTestHelper.newClient();
}
[Test]
public async Task GivenADataset_WhenIToDeleteIt_ThenItIsDeleted()
{
var createDataset = this.GivenCreateDataset();
await this._client
.WhenTryingToCreateIt(createDataset)
.Should()
.NotThrowAsync();
await this._client
.WhenTryingToDeleteTheDataset(createDataset.DatasetKey)
.Should()
.NotThrowAsync();
}
[Test]
public async Task GivenAValidDataset_WhenICreateIt_ThenIShouldGet200()
{
var createDataset = this.GivenCreateDataset();
await this._client
.WhenTryingToCreateIt(createDataset)
.Should()
.NotThrowAsync();
await this._client.DeleteDataset(createDataset.DatasetKey);
}
[Test]
public async Task GivenADataset_WhenIAddFields_ThenIGetA200()
{
var createDataset = this.GivenCreateDataset();
await this._client
.WhenTryingToCreateIt(createDataset)
.Should()
.NotThrowAsync();
await this._client
.WhenTryingToAddFieldToDataset(createDataset.DatasetKey, new DatasetField
{
Description = "new field",
DisplayName = "new display name",
Key = "potato",
Type = new FieldType
{
HighLevelType = FieldHighLevelType.Double
}
})
.Should()
.NotThrowAsync();
await this._client.DeleteDataset(createDataset.DatasetKey);
}
[Test]
public async Task GivenADataset_WhenIFetchIt_ThenIGetTheDataset()
{
var createDataset = this.GivenCreateDataset();
await this._client
.WhenTryingToCreateIt(createDataset)
.Should()
.NotThrowAsync();
await this._client
.WhenTryingToGetTheDataset(createDataset.DatasetKey)
.ThenIGetTheCorrectDataset(createDataset.DatasetKey);
await this._client.DeleteDataset(createDataset.DatasetKey);
}
[Test]
public async Task GivenDatasets_WhenIFetchThem_ThenIGetDatasets()
{
var createDataset = this.GivenCreateDataset();
await this._client
.WhenTryingToCreateIt(createDataset)
.Should()
.NotThrowAsync();
await this._client
.WhenTryingToListDatasets()
.ThenIGetAtLeastTheOneICreated(createDataset.DatasetKey);
await this._client.DeleteDataset(createDataset.DatasetKey);
}
[Test]
public async Task GivenADataset_WhenIUpdateIt_ThenItIsUpdated()
{
var createDataset = this.GivenCreateDataset();
var updateDataset = this.GivenUpdateDataset();
await this._client
.WhenTryingToCreateIt(createDataset)
.Should()
.NotThrowAsync();
await this._client
.WhenTryingToUpdateTheDataset(createDataset.DatasetKey, updateDataset)
.Should()
.NotThrowAsync();
await this._client.DeleteDataset(createDataset.DatasetKey);
}
[Test]
public async Task GivenADataset_WhenIUpdateAField_ThenIGet200()
{
var createDataset = this.GivenCreateDataset();
var fieldToUpdate = this.GivenUpdateField();
var fieldKey = createDataset.Fields.First().Key;
await this._client
.WhenTryingToCreateIt(createDataset)
.Should()
.NotThrowAsync();
await this._client
.WhenTryingToUpdateAFieldOfDataset(createDataset.DatasetKey, fieldKey, fieldToUpdate)
.Should()
.NotThrowAsync();
await this._client.DeleteDataset(createDataset.DatasetKey);
}
[Test]
public async Task GivenADataset_WhenIIngestData_ThenIGet200()
{
var createDataset = this.GivenCreateDataset();
await this._client
.WhenTryingToCreateIt(createDataset)
.Should()
.NotThrowAsync();
await this.EventuallyAssert(async () =>
{
await this._client
.WhenTryingToIngestData(createDataset.DatasetKey, new List<IDictionary<string, object>>
{
new Dictionary<string, object>
{
{ "rainbowdash", "some-value" }
}
})
.Should()
.NotThrowAsync();
});
await this._client.DeleteDataset(createDataset.DatasetKey);
}
}
internal static class DatalakeClientTestsExtensions
{
internal static async Task ThenIGetTheCorrectDataset(this Func<Task<Dataset>> dataSetFunc, string dataSetKey)
{
var dataSet = await dataSetFunc();
dataSet.Should().NotBeNull();
dataSet.DatasetKey.Should().Be(dataSetKey);
}
internal static async Task ThenIGetAtLeastTheOneICreated(this Func<Task<IEnumerable<Dataset>>> datasetsFunc, string datasetKey)
{
var datasets = await datasetsFunc();
datasets.Should().NotBeNull();
datasets.Should().NotBeEmpty();
datasets.Count().Should().BeGreaterOrEqualTo(1);
var dataset = datasets.FirstOrDefault(x => x.DatasetKey.Equals(datasetKey));
dataset.Should().NotBeNull();
}
}
}
| |
/*
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
namespace Amazon.DynamoDBv2.Model
{
/// <summary>
/// <para>Represents the output of a <i>Scan</i> operation.</para>
/// </summary>
public class ScanResult
{
private List<Dictionary<string,AttributeValue>> items = new List<Dictionary<string,AttributeValue>>();
private int? count;
private int? scannedCount;
private Dictionary<string,AttributeValue> lastEvaluatedKey = new Dictionary<string,AttributeValue>();
private ConsumedCapacity consumedCapacity;
/// <summary>
/// An array of item attributes that match the scan criteria. Each element in this array consists of an attribute name and the value for that
/// attribute.
///
/// </summary>
public List<Dictionary<string,AttributeValue>> Items
{
get { return this.items; }
set { this.items = value; }
}
/// <summary>
/// Adds elements to the Items collection
/// </summary>
/// <param name="items">The values to add to the Items collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public ScanResult WithItems(params Dictionary<string,AttributeValue>[] items)
{
foreach (Dictionary<string,AttributeValue> element in items)
{
this.items.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the Items collection
/// </summary>
/// <param name="items">The values to add to the Items collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public ScanResult WithItems(IEnumerable<Dictionary<string,AttributeValue>> items)
{
foreach (Dictionary<string,AttributeValue> element in items)
{
this.items.Add(element);
}
return this;
}
// Check to see if Items property is set
internal bool IsSetItems()
{
return this.items.Count > 0;
}
/// <summary>
/// The number of items in the response.
///
/// </summary>
public int Count
{
get { return this.count ?? default(int); }
set { this.count = value; }
}
/// <summary>
/// Sets the Count property
/// </summary>
/// <param name="count">The value to set for the Count property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public ScanResult WithCount(int count)
{
this.count = count;
return this;
}
// Check to see if Count property is set
internal bool IsSetCount()
{
return this.count.HasValue;
}
/// <summary>
/// The number of items in the complete scan, before any filters are applied. A high <i>ScannedCount</i> value with few, or no, <i>Count</i>
/// results indicates an inefficient <i>Scan</i> operation. For more information, see <a
/// href="http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/QueryAndScan.html#Count">Count and ScannedCount</a> in the <i>Amazon
/// DynamoDB Developer Guide</i>.
///
/// </summary>
public int ScannedCount
{
get { return this.scannedCount ?? default(int); }
set { this.scannedCount = value; }
}
/// <summary>
/// Sets the ScannedCount property
/// </summary>
/// <param name="scannedCount">The value to set for the ScannedCount property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public ScanResult WithScannedCount(int scannedCount)
{
this.scannedCount = scannedCount;
return this;
}
// Check to see if ScannedCount property is set
internal bool IsSetScannedCount()
{
return this.scannedCount.HasValue;
}
/// <summary>
/// The primary key of the item where the operation stopped, inclusive of the previous result set. Use this value to start a new operation,
/// excluding this value in the new request. <i>LastEvaluatedKey</i> is null when the entire result set is complete (in other words, when the
/// operation processed the "last page" of results). If you are performing a parallel scan, <i>LastEvaluatedKey</i> is null if the requested
/// <i>Segment</i> has been completely scanned. It does not indicate that any other segments have been scanned.
///
/// </summary>
public Dictionary<string,AttributeValue> LastEvaluatedKey
{
get { return this.lastEvaluatedKey; }
set { this.lastEvaluatedKey = value; }
}
/// <summary>
/// Adds the KeyValuePairs to the LastEvaluatedKey dictionary.
/// </summary>
/// <param name="pairs">The pairs to be added to the LastEvaluatedKey dictionary.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public ScanResult WithLastEvaluatedKey(params KeyValuePair<string, AttributeValue>[] pairs)
{
foreach (KeyValuePair<string, AttributeValue> pair in pairs)
{
this.LastEvaluatedKey[pair.Key] = pair.Value;
}
return this;
}
// Check to see if LastEvaluatedKey property is set
internal bool IsSetLastEvaluatedKey()
{
return this.lastEvaluatedKey != null;
}
/// <summary>
/// The table name that consumed provisioned throughput, and the number of capacity units consumed by it. <i>ConsumedCapacity</i> is only
/// returned if it was asked for in the request. For more information, see <a
/// href="http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ProvisionedThroughputIntro.html">Provisioned Throughput</a> in the
/// <i>Amazon DynamoDB Developer Guide</i>.
///
/// </summary>
public ConsumedCapacity ConsumedCapacity
{
get { return this.consumedCapacity; }
set { this.consumedCapacity = value; }
}
/// <summary>
/// Sets the ConsumedCapacity property
/// </summary>
/// <param name="consumedCapacity">The value to set for the ConsumedCapacity property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public ScanResult WithConsumedCapacity(ConsumedCapacity consumedCapacity)
{
this.consumedCapacity = consumedCapacity;
return this;
}
// Check to see if ConsumedCapacity property is set
internal bool IsSetConsumedCapacity()
{
return this.consumedCapacity != null;
}
}
}
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.DotNet.BuildServer;
using Microsoft.DotNet.Cli;
using Microsoft.DotNet.Cli.CommandLine;
using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.Tools.BuildServer;
using Microsoft.DotNet.Tools.BuildServer.Shutdown;
using Microsoft.DotNet.Tools.Test.Utilities;
using Moq;
using Xunit;
using Parser = Microsoft.DotNet.Cli.Parser;
using LocalizableStrings = Microsoft.DotNet.Tools.BuildServer.Shutdown.LocalizableStrings;
namespace Microsoft.DotNet.Tests.Commands
{
public class BuildServerShutdownCommandTests
{
private readonly BufferedReporter _reporter = new BufferedReporter();
[Fact]
public void GivenNoOptionsAllManagersArePresent()
{
var command = CreateCommand();
command.Managers.Select(m => m.ServerName).Should().Equal(
DotNet.BuildServer.LocalizableStrings.MSBuildServer,
DotNet.BuildServer.LocalizableStrings.VBCSCompilerServer,
DotNet.BuildServer.LocalizableStrings.RazorServer
);
}
[Fact]
public void GivenMSBuildOptionOnlyItIsTheOnlyManager()
{
var command = CreateCommand("--msbuild");
command.Managers.Select(m => m.ServerName).Should().Equal(
DotNet.BuildServer.LocalizableStrings.MSBuildServer
);
}
[Fact]
public void GivenVBCSCompilerOptionOnlyItIsTheOnlyManager()
{
var command = CreateCommand("--vbcscompiler");
command.Managers.Select(m => m.ServerName).Should().Equal(
DotNet.BuildServer.LocalizableStrings.VBCSCompilerServer
);
}
[Fact]
public void GivenRazorOptionOnlyItIsTheOnlyManager()
{
var command = CreateCommand("--razor");
command.Managers.Select(m => m.ServerName).Should().Equal(
DotNet.BuildServer.LocalizableStrings.RazorServer
);
}
[Fact]
public void GivenSuccessfulShutdownsItPrintsSuccess()
{
var mocks = new[] {
CreateManagerMock("first", new Result(ResultKind.Success)),
CreateManagerMock("second", new Result(ResultKind.Success)),
CreateManagerMock("third", new Result(ResultKind.Success))
};
var command = CreateCommand(managers: mocks.Select(m => m.Object));
command.Execute().Should().Be(0);
_reporter.Lines.Should().Equal(
FormatShuttingDownMessage(mocks[0].Object),
FormatShuttingDownMessage(mocks[1].Object),
FormatShuttingDownMessage(mocks[2].Object),
FormatSuccessMessage(mocks[0].Object),
FormatSuccessMessage(mocks[1].Object),
FormatSuccessMessage(mocks[2].Object));
VerifyShutdownCalls(mocks);
}
[Fact]
public void GivenAFailingShutdownItPrintsFailureMessage()
{
const string FailureMessage = "failed!";
var mocks = new[] {
CreateManagerMock("first", new Result(ResultKind.Success)),
CreateManagerMock("second", new Result(ResultKind.Failure, FailureMessage)),
CreateManagerMock("third", new Result(ResultKind.Success))
};
var command = CreateCommand(managers: mocks.Select(m => m.Object));
command.Execute().Should().Be(1);
_reporter.Lines.Should().Equal(
FormatShuttingDownMessage(mocks[0].Object),
FormatShuttingDownMessage(mocks[1].Object),
FormatShuttingDownMessage(mocks[2].Object),
FormatSuccessMessage(mocks[0].Object),
FormatFailureMessage(mocks[1].Object, FailureMessage),
FormatSuccessMessage(mocks[2].Object));
VerifyShutdownCalls(mocks);
}
[Fact]
public void GivenASkippedShutdownItPrintsSkipMessage()
{
const string SkipMessage = "skipped!";
var mocks = new[] {
CreateManagerMock("first", new Result(ResultKind.Success)),
CreateManagerMock("second", new Result(ResultKind.Success)),
CreateManagerMock("third", new Result(ResultKind.Skipped, SkipMessage))
};
var command = CreateCommand(managers: mocks.Select(m => m.Object));
command.Execute().Should().Be(0);
_reporter.Lines.Should().Equal(
FormatShuttingDownMessage(mocks[0].Object),
FormatShuttingDownMessage(mocks[1].Object),
FormatShuttingDownMessage(mocks[2].Object),
FormatSuccessMessage(mocks[0].Object),
FormatSuccessMessage(mocks[1].Object),
FormatSkippedMessage(mocks[2].Object, SkipMessage));
VerifyShutdownCalls(mocks);
}
[Fact]
public void GivenSuccessFailureAndSkippedItPrintsAllThree()
{
const string FailureMessage = "failed!";
const string SkipMessage = "skipped!";
var mocks = new[] {
CreateManagerMock("first", new Result(ResultKind.Success)),
CreateManagerMock("second", new Result(ResultKind.Failure, FailureMessage)),
CreateManagerMock("third", new Result(ResultKind.Skipped, SkipMessage))
};
var command = CreateCommand(managers: mocks.Select(m => m.Object));
command.Execute().Should().Be(1);
_reporter.Lines.Should().Equal(
FormatShuttingDownMessage(mocks[0].Object),
FormatShuttingDownMessage(mocks[1].Object),
FormatShuttingDownMessage(mocks[2].Object),
FormatSuccessMessage(mocks[0].Object),
FormatFailureMessage(mocks[1].Object, FailureMessage),
FormatSkippedMessage(mocks[2].Object, SkipMessage));
VerifyShutdownCalls(mocks);
}
private BuildServerShutdownCommand CreateCommand(string options = "", IEnumerable<IBuildServerManager> managers = null)
{
ParseResult result = Parser.Instance.Parse("dotnet buildserver shutdown " + options);
return new BuildServerShutdownCommand(
options: result["dotnet"]["buildserver"]["shutdown"],
result: result,
managers: managers,
useOrderedWait: true,
reporter: _reporter);
}
private Mock<IBuildServerManager> CreateManagerMock(string serverName, Result result)
{
var mock = new Mock<IBuildServerManager>(MockBehavior.Strict);
mock.SetupGet(m => m.ServerName).Returns(serverName);
mock.Setup(m => m.ShutdownServerAsync()).Returns(Task.FromResult(result));
return mock;
}
private void VerifyShutdownCalls(IEnumerable<Mock<IBuildServerManager>> mocks)
{
foreach (var mock in mocks)
{
mock.Verify(m => m.ShutdownServerAsync(), Times.Once());
}
}
private static string FormatShuttingDownMessage(IBuildServerManager manager)
{
return string.Format(LocalizableStrings.ShuttingDownServer, manager.ServerName);
}
private static string FormatSuccessMessage(IBuildServerManager manager)
{
return string.Format(LocalizableStrings.ShutDownSucceeded, manager.ServerName).Green();
}
private static string FormatFailureMessage(IBuildServerManager manager, string message)
{
return string.Format(LocalizableStrings.ShutDownFailed, manager.ServerName, message).Red();
}
private static string FormatSkippedMessage(IBuildServerManager manager, string message)
{
return string.Format(LocalizableStrings.ShutDownSkipped, manager.ServerName, message).Cyan();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
** Purpose: Some floating-point math operations
**
**
===========================================================*/
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
namespace System
{
public static class Math
{
private static double s_doubleRoundLimit = 1e16d;
private const int maxRoundingDigits = 15;
// This table is required for the Round function which can specify the number of digits to round to
private static double[] s_roundPower10Double = new double[] {
1E0, 1E1, 1E2, 1E3, 1E4, 1E5, 1E6, 1E7, 1E8,
1E9, 1E10, 1E11, 1E12, 1E13, 1E14, 1E15
};
public const double PI = 3.14159265358979323846;
public const double E = 2.7182818284590452354;
#if CORERT
[Intrinsic]
#endif
public static double Acos(double d)
{
return RuntimeImports.acos(d);
}
#if CORERT
[Intrinsic]
#endif
public static double Asin(double d)
{
return RuntimeImports.asin(d);
}
#if CORERT
[Intrinsic]
#endif
public static double Atan(double d)
{
return RuntimeImports.atan(d);
}
#if CORERT
[Intrinsic]
#endif
public static double Atan2(double y, double x)
{
if (Double.IsInfinity(x) && Double.IsInfinity(y))
return Double.NaN;
return RuntimeImports.atan2(y, x);
}
public static Decimal Ceiling(Decimal d)
{
return Decimal.Ceiling(d);
}
#if CORERT
[Intrinsic]
#endif
public static double Ceiling(double a)
{
return RuntimeImports.ceil(a);
}
#if CORERT
[Intrinsic]
#endif
public static double Cos(double d)
{
return RuntimeImports.cos(d);
}
#if CORERT
[Intrinsic]
#endif
public static double Cosh(double value)
{
return RuntimeImports.cosh(value);
}
public static Decimal Floor(Decimal d)
{
return Decimal.Floor(d);
}
#if CORERT
[Intrinsic]
#endif
public static double Floor(double d)
{
return RuntimeImports.floor(d);
}
private static unsafe double InternalRound(double value, int digits, MidpointRounding mode)
{
if (Abs(value) < s_doubleRoundLimit)
{
Double power10 = s_roundPower10Double[digits];
value *= power10;
if (mode == MidpointRounding.AwayFromZero)
{
double fraction = RuntimeImports.modf(value, &value);
if (Abs(fraction) >= 0.5d)
{
value += Sign(fraction);
}
}
else
{
// On X86 this can be inlined to just a few instructions
value = Round(value);
}
value /= power10;
}
return value;
}
#if CORERT
[Intrinsic]
#endif
public static double Sin(double a)
{
return RuntimeImports.sin(a);
}
#if CORERT
[Intrinsic]
#endif
public static double Tan(double a)
{
return RuntimeImports.tan(a);
}
#if CORERT
[Intrinsic]
#endif
public static double Sinh(double value)
{
return RuntimeImports.sinh(value);
}
#if CORERT
[Intrinsic]
#endif
public static double Tanh(double value)
{
return RuntimeImports.tanh(value);
}
#if CORERT
[Intrinsic]
#endif
public static double Round(double a)
{
// If the number has no fractional part do nothing
// This shortcut is necessary to workaround precision loss in borderline cases on some platforms
if (a == (double)(Int64)a)
return a;
double tempVal = a + 0.5;
// We had a number that was equally close to 2 integers.
// We need to return the even one.
double flrTempVal = RuntimeImports.floor(tempVal);
if (flrTempVal == tempVal)
{
if (0.0 != RuntimeImports.fmod(tempVal, 2.0))
{
flrTempVal -= 1.0;
}
}
if (flrTempVal == 0 && Double.IsNegative(a))
{
flrTempVal = Double.NegativeZero;
}
return flrTempVal;
}
public static double Round(double value, int digits)
{
if ((digits < 0) || (digits > maxRoundingDigits))
throw new ArgumentOutOfRangeException("digits", SR.ArgumentOutOfRange_RoundingDigits);
Contract.EndContractBlock();
return InternalRound(value, digits, MidpointRounding.ToEven);
}
public static double Round(double value, MidpointRounding mode)
{
return Round(value, 0, mode);
}
public static double Round(double value, int digits, MidpointRounding mode)
{
if ((digits < 0) || (digits > maxRoundingDigits))
throw new ArgumentOutOfRangeException("digits", SR.ArgumentOutOfRange_RoundingDigits);
if (mode < MidpointRounding.ToEven || mode > MidpointRounding.AwayFromZero)
{
throw new ArgumentException(SR.Format(SR.Argument_InvalidEnumValue, mode, "MidpointRounding"), "mode");
}
Contract.EndContractBlock();
return InternalRound(value, digits, mode);
}
public static Decimal Round(Decimal d)
{
return Decimal.Round(d, 0);
}
public static Decimal Round(Decimal d, int decimals)
{
return Decimal.Round(d, decimals);
}
public static Decimal Round(Decimal d, MidpointRounding mode)
{
return Decimal.Round(d, 0, mode);
}
public static Decimal Round(Decimal d, int decimals, MidpointRounding mode)
{
return Decimal.Round(d, decimals, mode);
}
public static Decimal Truncate(Decimal d)
{
return Decimal.Truncate(d);
}
public static unsafe double Truncate(double d)
{
double intpart;
RuntimeImports.modf(d, &intpart);
return intpart;
}
#if CORERT
[Intrinsic]
#endif
public static double Sqrt(double d)
{
return RuntimeImports.sqrt(d);
}
#if CORERT
[Intrinsic]
#endif
public static double Log(double d)
{
return RuntimeImports.log(d);
}
#if CORERT
[Intrinsic]
#endif
public static double Log10(double d)
{
return RuntimeImports.log10(d);
}
#if CORERT
[Intrinsic]
#endif
public static double Exp(double d)
{
if (Double.IsInfinity(d))
{
if (d < 0)
return +0.0;
return d;
}
return RuntimeImports.exp(d);
}
#if CORERT
[Intrinsic]
#endif
public static double Pow(double x, double y)
{
if (Double.IsNaN(y))
return y;
if (Double.IsNaN(x))
return x;
if (Double.IsInfinity(y))
{
if (x == 1.0)
{
return x;
}
if (x == -1.0)
{
return Double.NaN;
}
}
return RuntimeImports.pow(x, y);
}
public static double IEEERemainder(double x, double y)
{
if (Double.IsNaN(x))
{
return x; // IEEE 754-2008: NaN payload must be preserved
}
if (Double.IsNaN(y))
{
return y; // IEEE 754-2008: NaN payload must be preserved
}
double regularMod = x % y;
if (Double.IsNaN(regularMod))
{
return Double.NaN;
}
if (regularMod == 0)
{
if (Double.IsNegative(x))
{
return Double.NegativeZero;
}
}
double alternativeResult;
alternativeResult = regularMod - (Math.Abs(y) * Math.Sign(x));
if (Math.Abs(alternativeResult) == Math.Abs(regularMod))
{
double divisionResult = x / y;
double roundedResult = Math.Round(divisionResult);
if (Math.Abs(roundedResult) > Math.Abs(divisionResult))
{
return alternativeResult;
}
else
{
return regularMod;
}
}
if (Math.Abs(alternativeResult) < Math.Abs(regularMod))
{
return alternativeResult;
}
else
{
return regularMod;
}
}
/*================================Abs=========================================
**Returns the absolute value of it's argument.
============================================================================*/
#if CORERT
[CLSCompliant(false)]
public static sbyte Abs(sbyte value)
{
if (value >= 0)
return value;
else
return AbsHelper(value);
}
private static sbyte AbsHelper(sbyte value)
{
Contract.Requires(value < 0, "AbsHelper should only be called for negative values!");
if (value == SByte.MinValue)
throw new OverflowException(SR.Overflow_NegateTwosCompNum);
Contract.EndContractBlock();
return ((sbyte)(-value));
}
public static short Abs(short value)
{
if (value >= 0)
return value;
else
return AbsHelper(value);
}
private static short AbsHelper(short value)
{
Contract.Requires(value < 0, "AbsHelper should only be called for negative values!");
if (value == Int16.MinValue)
throw new OverflowException(SR.Overflow_NegateTwosCompNum);
Contract.EndContractBlock();
return (short)-value;
}
public static int Abs(int value)
{
if (value >= 0)
return value;
else
return AbsHelper(value);
}
private static int AbsHelper(int value)
{
Contract.Requires(value < 0, "AbsHelper should only be called for negative values!");
if (value == Int32.MinValue)
throw new OverflowException(SR.Overflow_NegateTwosCompNum);
Contract.EndContractBlock();
return -value;
}
public static long Abs(long value)
{
if (value >= 0)
return value;
else
return AbsHelper(value);
}
private static long AbsHelper(long value)
{
Contract.Requires(value < 0, "AbsHelper should only be called for negative values!");
if (value == Int64.MinValue)
throw new OverflowException(SR.Overflow_NegateTwosCompNum);
Contract.EndContractBlock();
return -value;
}
[Intrinsic]
public static float Abs(float value)
{
return (float)RuntimeImports.fabs(value);
}
[Intrinsic]
public static double Abs(double value)
{
return RuntimeImports.fabs(value);
}
#else // CORERT
[CLSCompliant(false)]
[Intrinsic]
public static sbyte Abs(sbyte value)
{
// This is actually an intrinsic and not a recursive function call.
// We have it here so that you can do "ldftn" on the method or reflection invoke it.
return Abs(value);
}
[Intrinsic]
public static short Abs(short value)
{
// This is actually an intrinsic and not a recursive function call.
// We have it here so that you can do "ldftn" on the method or reflection invoke it.
return Abs(value);
}
[Intrinsic]
public static int Abs(int value)
{
// This is actually an intrinsic and not a recursive function call.
// We have it here so that you can do "ldftn" on the method or reflection invoke it.
return Abs(value);
}
[Intrinsic]
public static long Abs(long value)
{
// This is actually an intrinsic and not a recursive function call.
// We have it here so that you can do "ldftn" on the method or reflection invoke it.
return Abs(value);
}
[Intrinsic]
public static float Abs(float value)
{
// This is actually an intrinsic and not a recursive function call.
// We have it here so that you can do "ldftn" on the method or reflection invoke it.
return Abs(value);
}
[Intrinsic]
public static double Abs(double value)
{
// This is actually an intrinsic and not a recursive function call.
// We have it here so that you can do "ldftn" on the method or reflection invoke it.
return Abs(value);
}
#endif // CORERT
public static Decimal Abs(Decimal value)
{
return Decimal.Abs(value);
}
/*================================MAX=========================================
**Returns the larger of val1 and val2
============================================================================*/
[CLSCompliant(false)]
[NonVersionable]
public static sbyte Max(sbyte val1, sbyte val2)
{
return (val1 >= val2) ? val1 : val2;
}
[NonVersionable]
public static byte Max(byte val1, byte val2)
{
return (val1 >= val2) ? val1 : val2;
}
[NonVersionable]
public static short Max(short val1, short val2)
{
return (val1 >= val2) ? val1 : val2;
}
[CLSCompliant(false)]
[NonVersionable]
public static ushort Max(ushort val1, ushort val2)
{
return (val1 >= val2) ? val1 : val2;
}
[NonVersionable]
public static int Max(int val1, int val2)
{
return (val1 >= val2) ? val1 : val2;
}
[CLSCompliant(false)]
[NonVersionable]
public static uint Max(uint val1, uint val2)
{
return (val1 >= val2) ? val1 : val2;
}
[NonVersionable]
public static long Max(long val1, long val2)
{
return (val1 >= val2) ? val1 : val2;
}
[CLSCompliant(false)]
[NonVersionable]
public static ulong Max(ulong val1, ulong val2)
{
return (val1 >= val2) ? val1 : val2;
}
public static float Max(float val1, float val2)
{
if (val1 > val2)
return val1;
if (Single.IsNaN(val1))
return val1;
return val2;
}
public static double Max(double val1, double val2)
{
if (val1 > val2)
return val1;
if (Double.IsNaN(val1))
return val1;
return val2;
}
public static Decimal Max(Decimal val1, Decimal val2)
{
return Decimal.Max(val1, val2);
}
/*================================MIN=========================================
**Returns the smaller of val1 and val2.
============================================================================*/
[CLSCompliant(false)]
[NonVersionable]
public static sbyte Min(sbyte val1, sbyte val2)
{
return (val1 <= val2) ? val1 : val2;
}
[NonVersionable]
public static byte Min(byte val1, byte val2)
{
return (val1 <= val2) ? val1 : val2;
}
[NonVersionable]
public static short Min(short val1, short val2)
{
return (val1 <= val2) ? val1 : val2;
}
[CLSCompliant(false)]
[NonVersionable]
public static ushort Min(ushort val1, ushort val2)
{
return (val1 <= val2) ? val1 : val2;
}
[NonVersionable]
public static int Min(int val1, int val2)
{
return (val1 <= val2) ? val1 : val2;
}
[CLSCompliant(false)]
[NonVersionable]
public static uint Min(uint val1, uint val2)
{
return (val1 <= val2) ? val1 : val2;
}
[NonVersionable]
public static long Min(long val1, long val2)
{
return (val1 <= val2) ? val1 : val2;
}
[CLSCompliant(false)]
[NonVersionable]
public static ulong Min(ulong val1, ulong val2)
{
return (val1 <= val2) ? val1 : val2;
}
public static float Min(float val1, float val2)
{
if (val1 < val2)
return val1;
if (Single.IsNaN(val1))
return val1;
return val2;
}
public static double Min(double val1, double val2)
{
if (val1 < val2)
return val1;
if (Double.IsNaN(val1))
return val1;
return val2;
}
public static Decimal Min(Decimal val1, Decimal val2)
{
return Decimal.Min(val1, val2);
}
/*=====================================Log======================================
**
==============================================================================*/
public static double Log(double a, double newBase)
{
if (Double.IsNaN(a))
{
return a; // IEEE 754-2008: NaN payload must be preserved
}
if (Double.IsNaN(newBase))
{
return newBase; // IEEE 754-2008: NaN payload must be preserved
}
if (newBase == 1)
return Double.NaN;
if (a != 1 && (newBase == 0 || Double.IsPositiveInfinity(newBase)))
return Double.NaN;
return (Log(a) / Log(newBase));
}
// Sign function for VB. Returns -1, 0, or 1 if the sign of the number
// is negative, 0, or positive. Throws for floating point NaN's.
[CLSCompliant(false)]
public static int Sign(sbyte value)
{
if (value < 0)
return -1;
else if (value > 0)
return 1;
else
return 0;
}
// Sign function for VB. Returns -1, 0, or 1 if the sign of the number
// is negative, 0, or positive. Throws for floating point NaN's.
public static int Sign(short value)
{
if (value < 0)
return -1;
else if (value > 0)
return 1;
else
return 0;
}
// Sign function for VB. Returns -1, 0, or 1 if the sign of the number
// is negative, 0, or positive. Throws for floating point NaN's.
public static int Sign(int value)
{
if (value < 0)
return -1;
else if (value > 0)
return 1;
else
return 0;
}
public static int Sign(long value)
{
if (value < 0)
return -1;
else if (value > 0)
return 1;
else
return 0;
}
public static int Sign(float value)
{
if (value < 0)
return -1;
else if (value > 0)
return 1;
else if (value == 0)
return 0;
throw new ArithmeticException(SR.Arithmetic_NaN);
}
public static int Sign(double value)
{
if (value < 0)
return -1;
else if (value > 0)
return 1;
else if (value == 0)
return 0;
throw new ArithmeticException(SR.Arithmetic_NaN);
}
public static int Sign(Decimal value)
{
if (value < 0)
return -1;
else if (value > 0)
return 1;
else
return 0;
}
}
}
| |
namespace NArrange.Tests.Core
{
using System;
using System.IO;
using NArrange.Core;
using NArrange.Core.CodeElements;
using NArrange.Core.Configuration;
using NUnit.Framework;
/// <summary>
/// Test fixture for the ConditionExpressionEvaluator class.
/// </summary>
[TestFixture]
public class ConditionExpressionEvaluatorTests
{
#region Methods
/// <summary>
/// Tests the Evaluate method with an And expression.
/// </summary>
[Test]
public void EvaluateAndTest()
{
IConditionExpression nameExpression = new BinaryOperatorExpression(
BinaryExpressionOperator.Equal,
new ElementAttributeExpression(ElementAttributeType.Name),
new StringExpression("Test"));
IConditionExpression attributeExpression = new BinaryOperatorExpression(
BinaryExpressionOperator.Equal,
new ElementAttributeExpression(ElementAttributeType.Access),
new StringExpression("Protected"));
IConditionExpression expression = new BinaryOperatorExpression(
BinaryExpressionOperator.And, nameExpression, attributeExpression);
FieldElement element = new FieldElement();
element.Name = "Test";
element.Access = CodeAccess.Protected;
bool result = ConditionExpressionEvaluator.Instance.Evaluate(
expression, element);
Assert.IsTrue(result, "Unexpected expression evaluation result.");
element.Name = "Foo";
result = ConditionExpressionEvaluator.Instance.Evaluate(
expression, element);
Assert.IsFalse(result, "Unexpected expression evaluation result.");
element.Name = "Test";
element.Access = CodeAccess.Private;
result = ConditionExpressionEvaluator.Instance.Evaluate(
expression, element);
Assert.IsFalse(result, "Unexpected expression evaluation result.");
}
/// <summary>
/// Tests the Evaluate method with a null expression.
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void EvaluateElementExpressionNullTest()
{
bool result = ConditionExpressionEvaluator.Instance.Evaluate(
null, new FieldElement());
}
/// <summary>
/// Tests the Evaluate method with a Contains expression.
/// </summary>
[Test]
public void EvaluateElementNameContainsTest()
{
IConditionExpression expression = new BinaryOperatorExpression(
BinaryExpressionOperator.Contains,
new ElementAttributeExpression(ElementAttributeType.Name),
new StringExpression("Test"));
FieldElement element = new FieldElement();
element.Name = "Test";
bool result = ConditionExpressionEvaluator.Instance.Evaluate(
expression, element);
Assert.IsTrue(result, "Unexpected expression evaluation result.");
element.Name = "OnTest1";
result = ConditionExpressionEvaluator.Instance.Evaluate(
expression, element);
Assert.IsTrue(result, "Unexpected expression evaluation result.");
element.Name = "Foo";
result = ConditionExpressionEvaluator.Instance.Evaluate(
expression, element);
Assert.IsFalse(result, "Unexpected expression evaluation result.");
}
/// <summary>
/// Tests the Evaluate method with an Equal expression.
/// </summary>
[Test]
public void EvaluateElementNameEqualTest()
{
IConditionExpression expression = new BinaryOperatorExpression(
BinaryExpressionOperator.Equal,
new ElementAttributeExpression(ElementAttributeType.Name),
new StringExpression("Test"));
FieldElement element = new FieldElement();
element.Name = "Test";
bool result = ConditionExpressionEvaluator.Instance.Evaluate(
expression, element);
Assert.IsTrue(result, "Unexpected expression evaluation result.");
element.Name = "Test1";
result = ConditionExpressionEvaluator.Instance.Evaluate(
expression, element);
Assert.IsFalse(result, "Unexpected expression evaluation result.");
}
/// <summary>
/// Tests the Evaluate method with a Matches expression.
/// </summary>
[Test]
public void EvaluateElementNameMatchesTest()
{
IConditionExpression expression = new BinaryOperatorExpression(
BinaryExpressionOperator.Matches,
new ElementAttributeExpression(ElementAttributeType.Name),
new StringExpression("IDisposable\\..*"));
MethodElement element = new MethodElement();
element.Name = "IDisposable.Dispose";
bool result = ConditionExpressionEvaluator.Instance.Evaluate(
expression, element);
Assert.IsTrue(result, "Unexpected expression evaluation result.");
element.Name = "IDisposable.Test";
result = ConditionExpressionEvaluator.Instance.Evaluate(
expression, element);
Assert.IsTrue(result, "Unexpected expression evaluation result.");
element.Name = "IDisposable";
result = ConditionExpressionEvaluator.Instance.Evaluate(
expression, element);
Assert.IsFalse(result, "Unexpected expression evaluation result.");
}
/// <summary>
/// Tests the Evaluate method with a not equal expression.
/// </summary>
[Test]
public void EvaluateElementNameNotEqualTest()
{
IConditionExpression expression = new BinaryOperatorExpression(
BinaryExpressionOperator.NotEqual,
new ElementAttributeExpression(ElementAttributeType.Name),
new StringExpression("Test"));
FieldElement element = new FieldElement();
element.Name = "Test";
bool result = ConditionExpressionEvaluator.Instance.Evaluate(
expression, element);
Assert.IsFalse(result, "Unexpected expression evaluation result.");
element.Name = "Temp";
result = ConditionExpressionEvaluator.Instance.Evaluate(
expression, element);
Assert.IsTrue(result, "Unexpected expression evaluation result.");
}
/// <summary>
/// Tests the Evaluate method with a null element.
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void EvaluateElementNullTest()
{
IConditionExpression expression = new BinaryOperatorExpression(
BinaryExpressionOperator.Equal,
new ElementAttributeExpression(ElementAttributeType.Name),
new StringExpression("Test"));
bool result = ConditionExpressionEvaluator.Instance.Evaluate(
expression, null as ICodeElement);
}
/// <summary>
/// Tests the Evaluate method with a Contains expression and a parent scope.
/// </summary>
[Test]
public void EvaluateElementParentAttributesContainsTest()
{
IConditionExpression expression = new BinaryOperatorExpression(
BinaryExpressionOperator.Contains,
new ElementAttributeExpression(ElementAttributeType.Attributes, ElementAttributeScope.Parent),
new StringExpression("Attribute2"));
FieldElement element = new FieldElement();
element.Name = "Test";
TypeElement typeElement = new TypeElement();
typeElement.Type = TypeElementType.Structure;
typeElement.Name = "TestType";
typeElement.AddChild(element);
typeElement.AddAttribute(new AttributeElement("Attribute1"));
typeElement.AddAttribute(new AttributeElement("Attribute24"));
bool result = ConditionExpressionEvaluator.Instance.Evaluate(
expression, element);
Assert.IsTrue(result, "Unexpected expression evaluation result.");
typeElement.ClearAttributes();
result = ConditionExpressionEvaluator.Instance.Evaluate(
expression, element);
Assert.IsFalse(result, "Unexpected expression evaluation result.");
}
/// <summary>
/// Tests the Evaluate method with an Attributes Contains expression.
/// </summary>
[Test]
public void EvaluateFileAttributesContainsTest()
{
string testFile = Path.GetTempFileName();
try
{
IConditionExpression expression = new BinaryOperatorExpression(
BinaryExpressionOperator.Contains,
new FileAttributeExpression(FileAttributeType.Attributes),
new StringExpression("ReadOnly"));
FileInfo file = new FileInfo(testFile);
file.Attributes = FileAttributes.ReadOnly | FileAttributes.Hidden;
bool result = ConditionExpressionEvaluator.Instance.Evaluate(
expression, file);
Assert.IsTrue(result, "Unexpected expression evaluation result.");
file.Attributes = FileAttributes.Normal;
file = new FileInfo(testFile);
result = ConditionExpressionEvaluator.Instance.Evaluate(
expression, file);
Assert.IsFalse(result, "Unexpected expression evaluation result.");
}
finally
{
try
{
File.Delete(testFile);
}
catch
{
}
}
}
/// <summary>
/// Tests the Evaluate method with a null expression.
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void EvaluateFileExpressionNullTest()
{
bool result = ConditionExpressionEvaluator.Instance.Evaluate(
null, new FileInfo("Test"));
}
/// <summary>
/// Tests the Evaluate method with a Contains expression.
/// </summary>
[Test]
public void EvaluateFileNameContainsTest()
{
IConditionExpression expression = new BinaryOperatorExpression(
BinaryExpressionOperator.Contains,
new FileAttributeExpression(FileAttributeType.Name),
new StringExpression("Test"));
FileInfo file = new FileInfo("Test");
bool result = ConditionExpressionEvaluator.Instance.Evaluate(
expression, file);
Assert.IsTrue(result, "Unexpected expression evaluation result.");
file = new FileInfo("Blah");
result = ConditionExpressionEvaluator.Instance.Evaluate(
expression, file);
Assert.IsFalse(result, "Unexpected expression evaluation result.");
}
/// <summary>
/// Tests the Evaluate method with a null file.
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void EvaluateFileNullTest()
{
IConditionExpression expression = new BinaryOperatorExpression(
BinaryExpressionOperator.Equal,
new FileAttributeExpression(FileAttributeType.Name),
new StringExpression("Test"));
bool result = ConditionExpressionEvaluator.Instance.Evaluate(
expression, null as FileInfo);
}
/// <summary>
/// Tests the Evaluate method with an Path Contains expression.
/// </summary>
[Test]
public void EvaluateFilePathContainsTest()
{
string testFile1 = Path.GetTempFileName();
string testFile2 = Path.GetTempFileName();
try
{
IConditionExpression expression = new BinaryOperatorExpression(
BinaryExpressionOperator.Contains,
new FileAttributeExpression(FileAttributeType.Path),
new StringExpression(Path.Combine(Path.GetTempPath(), Path.GetFileNameWithoutExtension(testFile1))));
FileInfo file = new FileInfo(testFile1);
bool result = ConditionExpressionEvaluator.Instance.Evaluate(
expression, file);
Assert.IsTrue(result, "Unexpected expression evaluation result.");
file = new FileInfo(testFile2);
result = ConditionExpressionEvaluator.Instance.Evaluate(
expression, file);
Assert.IsFalse(result, "Unexpected expression evaluation result.");
}
finally
{
try
{
File.Delete(testFile1);
File.Delete(testFile2);
}
catch
{
}
}
}
/// <summary>
/// Tests the Evaluate method with a an operator element that has an
/// unknown operator type.
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void EvaluateInvalidOperatorTest()
{
IConditionExpression expression = new BinaryOperatorExpression(
(BinaryExpressionOperator)int.MinValue,
new ElementAttributeExpression(ElementAttributeType.Name),
new StringExpression("Test"));
FieldElement element = new FieldElement();
element.Name = "Test";
bool result = ConditionExpressionEvaluator.Instance.Evaluate(
expression, element);
}
/// <summary>
/// Tests the Evaluate method with an Or expression.
/// </summary>
[Test]
public void EvaluateOrTest()
{
IConditionExpression nameExpression = new BinaryOperatorExpression(
BinaryExpressionOperator.Equal,
new ElementAttributeExpression(ElementAttributeType.Name),
new StringExpression("Test"));
IConditionExpression accessExpression = new BinaryOperatorExpression(
BinaryExpressionOperator.Equal,
new ElementAttributeExpression(ElementAttributeType.Access),
new StringExpression("Protected"));
IConditionExpression expression =
new BinaryOperatorExpression(BinaryExpressionOperator.Or, nameExpression, accessExpression);
FieldElement element = new FieldElement();
element.Name = "Test";
element.Access = CodeAccess.Protected;
bool result = ConditionExpressionEvaluator.Instance.Evaluate(
expression, element);
Assert.IsTrue(result, "Unexpected expression evaluation result.");
element.Name = "Foo";
result = ConditionExpressionEvaluator.Instance.Evaluate(
expression, element);
Assert.IsTrue(result, "Unexpected expression evaluation result.");
element.Name = "Test";
element.Access = CodeAccess.Private;
result = ConditionExpressionEvaluator.Instance.Evaluate(
expression, element);
Assert.IsTrue(result, "Unexpected expression evaluation result.");
element.Name = "Foo";
result = ConditionExpressionEvaluator.Instance.Evaluate(
expression, element);
Assert.IsFalse(result, "Unexpected expression evaluation result.");
}
#endregion Methods
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
using NSubstitute;
using NSubstitute.ExceptionExtensions;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
using Twilio.Rest.IpMessaging.V1;
namespace Twilio.Tests.Rest.IpMessaging.V1
{
[TestFixture]
public class CredentialTest : TwilioTest
{
[Test]
public void TestReadRequest()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
var request = new Request(
HttpMethod.Get,
Twilio.Rest.Domain.IpMessaging,
"/v1/Credentials",
""
);
twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content"));
try
{
CredentialResource.Read(client: twilioRestClient);
Assert.Fail("Expected TwilioException to be thrown for 500");
}
catch (ApiException) {}
twilioRestClient.Received().Request(request);
}
[Test]
public void TestReadFullResponse()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
twilioRestClient.Request(Arg.Any<Request>())
.Returns(new Response(
System.Net.HttpStatusCode.OK,
"{\"credentials\": [{\"sid\": \"CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"friendly_name\": \"Test slow create\",\"type\": \"apn\",\"sandbox\": \"False\",\"date_created\": \"2015-10-07T17:50:01Z\",\"date_updated\": \"2015-10-07T17:50:01Z\",\"url\": \"https://ip-messaging.twilio.com/v1/Credentials/CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}],\"meta\": {\"page\": 0,\"page_size\": 1,\"first_page_url\": \"https://ip-messaging.twilio.com/v1/Credentials?PageSize=1&Page=0\",\"previous_page_url\": null,\"url\": \"https://ip-messaging.twilio.com/v1/Credentials?PageSize=1&Page=0\",\"next_page_url\": null,\"key\": \"credentials\"}}"
));
var response = CredentialResource.Read(client: twilioRestClient);
Assert.NotNull(response);
}
[Test]
public void TestReadEmptyResponse()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
twilioRestClient.Request(Arg.Any<Request>())
.Returns(new Response(
System.Net.HttpStatusCode.OK,
"{\"credentials\": [],\"meta\": {\"page\": 0,\"page_size\": 1,\"first_page_url\": \"https://ip-messaging.twilio.com/v1/Credentials?PageSize=1&Page=0\",\"previous_page_url\": null,\"url\": \"https://ip-messaging.twilio.com/v1/Credentials?PageSize=1&Page=0\",\"next_page_url\": null,\"key\": \"credentials\"}}"
));
var response = CredentialResource.Read(client: twilioRestClient);
Assert.NotNull(response);
}
[Test]
public void TestCreateRequest()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
var request = new Request(
HttpMethod.Post,
Twilio.Rest.Domain.IpMessaging,
"/v1/Credentials",
""
);
request.AddPostParam("Type", Serialize(CredentialResource.PushServiceEnum.Gcm));
twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content"));
try
{
CredentialResource.Create(CredentialResource.PushServiceEnum.Gcm, client: twilioRestClient);
Assert.Fail("Expected TwilioException to be thrown for 500");
}
catch (ApiException) {}
twilioRestClient.Received().Request(request);
}
[Test]
public void TestCreateResponse()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
twilioRestClient.Request(Arg.Any<Request>())
.Returns(new Response(
System.Net.HttpStatusCode.Created,
"{\"sid\": \"CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"friendly_name\": \"Test slow create\",\"type\": \"apn\",\"sandbox\": \"False\",\"date_created\": \"2015-10-07T17:50:01Z\",\"date_updated\": \"2015-10-07T17:50:01Z\",\"url\": \"https://ip-messaging.twilio.com/v1/Credentials/CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}"
));
var response = CredentialResource.Create(CredentialResource.PushServiceEnum.Gcm, client: twilioRestClient);
Assert.NotNull(response);
}
[Test]
public void TestFetchRequest()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
var request = new Request(
HttpMethod.Get,
Twilio.Rest.Domain.IpMessaging,
"/v1/Credentials/CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
""
);
twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content"));
try
{
CredentialResource.Fetch("CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.Fail("Expected TwilioException to be thrown for 500");
}
catch (ApiException) {}
twilioRestClient.Received().Request(request);
}
[Test]
public void TestFetchResponse()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
twilioRestClient.Request(Arg.Any<Request>())
.Returns(new Response(
System.Net.HttpStatusCode.OK,
"{\"sid\": \"CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"friendly_name\": \"Test slow create\",\"type\": \"apn\",\"sandbox\": \"False\",\"date_created\": \"2015-10-07T17:50:01Z\",\"date_updated\": \"2015-10-07T17:50:01Z\",\"url\": \"https://ip-messaging.twilio.com/v1/Credentials/CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}"
));
var response = CredentialResource.Fetch("CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.NotNull(response);
}
[Test]
public void TestUpdateRequest()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
var request = new Request(
HttpMethod.Post,
Twilio.Rest.Domain.IpMessaging,
"/v1/Credentials/CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
""
);
twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content"));
try
{
CredentialResource.Update("CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.Fail("Expected TwilioException to be thrown for 500");
}
catch (ApiException) {}
twilioRestClient.Received().Request(request);
}
[Test]
public void TestUpdateResponse()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
twilioRestClient.Request(Arg.Any<Request>())
.Returns(new Response(
System.Net.HttpStatusCode.OK,
"{\"sid\": \"CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"friendly_name\": \"Test slow create\",\"type\": \"apn\",\"sandbox\": \"False\",\"date_created\": \"2015-10-07T17:50:01Z\",\"date_updated\": \"2015-10-07T17:50:01Z\",\"url\": \"https://ip-messaging.twilio.com/v1/Credentials/CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}"
));
var response = CredentialResource.Update("CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.NotNull(response);
}
[Test]
public void TestDeleteRequest()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
var request = new Request(
HttpMethod.Delete,
Twilio.Rest.Domain.IpMessaging,
"/v1/Credentials/CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
""
);
twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content"));
try
{
CredentialResource.Delete("CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.Fail("Expected TwilioException to be thrown for 500");
}
catch (ApiException) {}
twilioRestClient.Received().Request(request);
}
[Test]
public void TestDeleteResponse()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
twilioRestClient.Request(Arg.Any<Request>())
.Returns(new Response(
System.Net.HttpStatusCode.NoContent,
"null"
));
var response = CredentialResource.Delete("CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.NotNull(response);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.