context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Concurrent;
using System.Globalization;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Management.Automation.Remoting;
using System.Management.Automation.Remoting.Internal;
using System.Threading;
using Microsoft.Management.Infrastructure;
using Microsoft.Management.Infrastructure.Options;
using Microsoft.PowerShell.Cim;
using Dbg = System.Management.Automation.Diagnostics;
namespace Microsoft.PowerShell.Cmdletization.Cim
{
/// <summary>
/// Base class for all child jobs that wrap CIM operations.
/// </summary>
internal abstract class CimChildJobBase<T> :
StartableJob,
IObserver<T>
{
private static long s_globalJobNumberCounter;
private readonly long _myJobNumber = Interlocked.Increment(ref s_globalJobNumberCounter);
private const string CIMJobType = "CimJob";
internal CimJobContext JobContext
{
get
{
return _jobContext;
}
}
private readonly CimJobContext _jobContext;
internal CimChildJobBase(CimJobContext jobContext)
: base(Job.GetCommandTextFromInvocationInfo(jobContext.CmdletInvocationInfo), " " /* temporary name - reset below */)
{
_jobContext = jobContext;
this.PSJobTypeName = CIMJobType;
this.Name = this.GetType().Name + _myJobNumber.ToString(CultureInfo.InvariantCulture);
UsesResultsCollection = true;
lock (s_globalRandom)
{
_random = new Random(s_globalRandom.Next());
}
_jobSpecificCustomOptions = new Lazy<CimCustomOptionsDictionary>(this.CalculateJobSpecificCustomOptions);
}
private CimSensitiveValueConverter _cimSensitiveValueConverter = new CimSensitiveValueConverter();
internal CimSensitiveValueConverter CimSensitiveValueConverter { get { return _cimSensitiveValueConverter; } }
internal abstract IObservable<T> GetCimOperation();
public abstract void OnNext(T item);
// copied from sdpublic\sdk\inc\wsmerror.h
private enum WsManErrorCode : uint
{
ERROR_WSMAN_QUOTA_MAX_SHELLS = 0x803381A5,
ERROR_WSMAN_QUOTA_MAX_OPERATIONS = 0x803381A6,
ERROR_WSMAN_QUOTA_USER = 0x803381A7,
ERROR_WSMAN_QUOTA_SYSTEM = 0x803381A8,
ERROR_WSMAN_QUOTA_MAX_SHELLUSERS = 0x803381AB,
ERROR_WSMAN_QUOTA_MAX_SHELLS_PPQ = 0x803381E4,
ERROR_WSMAN_QUOTA_MAX_USERS_PPQ = 0x803381E5,
ERROR_WSMAN_QUOTA_MAX_PLUGINSHELLS_PPQ = 0x803381E6,
ERROR_WSMAN_QUOTA_MAX_PLUGINOPERATIONS_PPQ = 0x803381E7,
ERROR_WSMAN_QUOTA_MAX_OPERATIONS_USER_PPQ = 0x803381E8,
ERROR_WSMAN_QUOTA_MAX_COMMANDS_PER_SHELL_PPQ = 0x803381E9,
ERROR_WSMAN_QUOTA_MIN_REQUIREMENT_NOT_AVAILABLE_PPQ = 0x803381EA,
}
private static bool IsWsManQuotaReached(Exception exception)
{
var cimException = exception as CimException;
if (cimException == null)
{
return false;
}
if (cimException.NativeErrorCode != NativeErrorCode.ServerLimitsExceeded)
{
return false;
}
CimInstance cimError = cimException.ErrorData;
if (cimError == null)
{
return false;
}
CimProperty errorCodeProperty = cimError.CimInstanceProperties["error_Code"];
if (errorCodeProperty == null)
{
return false;
}
if (errorCodeProperty.CimType != CimType.UInt32)
{
return false;
}
WsManErrorCode wsManErrorCode = (WsManErrorCode)(UInt32)(errorCodeProperty.Value);
switch (wsManErrorCode) // error codes that should result in sleep-and-retry are based on an email from Ryan
{
case WsManErrorCode.ERROR_WSMAN_QUOTA_MAX_SHELLS:
case WsManErrorCode.ERROR_WSMAN_QUOTA_MAX_OPERATIONS:
case WsManErrorCode.ERROR_WSMAN_QUOTA_USER:
case WsManErrorCode.ERROR_WSMAN_QUOTA_SYSTEM:
case WsManErrorCode.ERROR_WSMAN_QUOTA_MAX_SHELLUSERS:
case WsManErrorCode.ERROR_WSMAN_QUOTA_MAX_SHELLS_PPQ:
case WsManErrorCode.ERROR_WSMAN_QUOTA_MAX_USERS_PPQ:
case WsManErrorCode.ERROR_WSMAN_QUOTA_MAX_PLUGINSHELLS_PPQ:
case WsManErrorCode.ERROR_WSMAN_QUOTA_MAX_PLUGINOPERATIONS_PPQ:
case WsManErrorCode.ERROR_WSMAN_QUOTA_MAX_OPERATIONS_USER_PPQ:
case WsManErrorCode.ERROR_WSMAN_QUOTA_MAX_COMMANDS_PER_SHELL_PPQ:
case WsManErrorCode.ERROR_WSMAN_QUOTA_MIN_REQUIREMENT_NOT_AVAILABLE_PPQ:
return true;
default:
return false;
}
}
public virtual void OnError(Exception exception)
{
this.ExceptionSafeWrapper(
delegate
{
if (IsWsManQuotaReached(exception))
{
this.SleepAndRetry();
return;
}
var cje = CimJobException.CreateFromAnyException(this.GetDescription(), this.JobContext, exception);
this.ReportJobFailure(cje);
});
}
public virtual void OnCompleted()
{
this.ExceptionSafeWrapper(
delegate
{
this.SetCompletedJobState(JobState.Completed, null);
});
}
private static readonly Random s_globalRandom = new Random();
private readonly Random _random;
private int _sleepAndRetryDelayRangeMs = 1000;
private int _sleepAndRetryExtraDelayMs = 0;
private const int MaxRetryDelayMs = 15 * 1000;
private const int MinRetryDelayMs = 100;
private Timer _sleepAndRetryTimer;
private void SleepAndRetry_OnWakeup(object state)
{
this.ExceptionSafeWrapper(
delegate
{
lock (_jobStateLock)
{
if (_sleepAndRetryTimer != null)
{
_sleepAndRetryTimer.Dispose();
_sleepAndRetryTimer = null;
}
if (_jobWasStopped)
{
this.SetCompletedJobState(JobState.Stopped, null);
return;
}
}
this.StartJob();
});
}
private void SleepAndRetry()
{
int tmpRandomDelay = _random.Next(0, _sleepAndRetryDelayRangeMs);
int delay = MinRetryDelayMs + _sleepAndRetryExtraDelayMs + tmpRandomDelay;
_sleepAndRetryExtraDelayMs = _sleepAndRetryDelayRangeMs - tmpRandomDelay;
if (_sleepAndRetryDelayRangeMs < MaxRetryDelayMs)
{
_sleepAndRetryDelayRangeMs *= 2;
}
string verboseMessage = string.Format(
CultureInfo.InvariantCulture,
CmdletizationResources.CimJob_SleepAndRetryVerboseMessage,
this.JobContext.CmdletInvocationInfo.InvocationName,
this.JobContext.Session.ComputerName ?? "localhost",
delay / 1000.0);
this.WriteVerbose(verboseMessage);
lock (_jobStateLock)
{
if (_jobWasStopped)
{
this.SetCompletedJobState(JobState.Stopped, null);
}
else
{
Dbg.Assert(_sleepAndRetryTimer == null, "There should be only 1 active _sleepAndRetryTimer");
_sleepAndRetryTimer = new Timer(
state: null,
dueTime: delay,
period: Timeout.Infinite,
callback: SleepAndRetry_OnWakeup);
}
}
}
/// <summary>
/// Indicates a location where this job is running.
/// </summary>
public override string Location
{
get
{
// this.JobContext is set in the constructor of CimChildJobBase,
// but the constructor of Job wants to access Location property
// before CimChildJobBase is fully initialized
if (this.JobContext == null)
{
return null;
}
string location = this.JobContext.Session.ComputerName ?? Environment.MachineName;
return location;
}
}
/// <summary>
/// Status message associated with the Job.
/// </summary>
public override string StatusMessage
{
get
{
return this.JobStateInfo.State.ToString();
}
}
/// <summary>
/// Indicates if job has more data available.
/// </summary>
public override bool HasMoreData
{
get
{
return (Results.IsOpen || Results.Count > 0);
}
}
internal void WriteVerboseStartOfCimOperation()
{
if (this.JobContext.CmdletInvocationContext.CmdletDefinitionContext.ClientSideWriteVerbose)
{
string verboseMessage = string.Format(
CultureInfo.CurrentCulture,
CmdletizationResources.CimJob_VerboseExecutionMessage,
this.GetDescription());
this.WriteVerbose(verboseMessage);
}
}
internal override void StartJob()
{
lock (_jobStateLock)
{
if (_jobWasStopped)
{
this.SetCompletedJobState(JobState.Stopped, null);
return;
}
Dbg.Assert(!_alreadyReachedCompletedState, "Job shouldn't reach completed state, before ThrottlingJob has a chance to register for job-completed/failed events");
TerminatingErrorTracker tracker = TerminatingErrorTracker.GetTracker(this.JobContext.CmdletInvocationInfo);
if (tracker.IsSessionTerminated(this.JobContext.Session))
{
this.SetCompletedJobState(JobState.Failed, new OperationCanceledException());
return;
}
if (!_jobWasStarted)
{
_jobWasStarted = true;
this.SetJobState(JobState.Running);
}
}
// This invocation can block (i.e. by calling Job.ShouldProcess) and wait for pipeline thread to unblock it
// Therefore we have to do the invocation outside of the pipeline thread.
ThreadPool.QueueUserWorkItem(delegate
{
this.ExceptionSafeWrapper(delegate
{
IObservable<T> observable = this.GetCimOperation();
if (observable != null)
{
observable.Subscribe(this);
}
});
});
}
internal string GetDescription()
{
try
{
return this.Description;
}
catch (Exception)
{
return this.FailSafeDescription;
}
}
internal abstract string Description { get; }
internal abstract string FailSafeDescription { get; }
internal void ExceptionSafeWrapper(Action action)
{
try
{
try
{
Dbg.Assert(action != null, "Caller should verify action != null");
action();
}
catch (CimJobException e)
{
this.ReportJobFailure(e);
}
catch (PSInvalidCastException e)
{
this.ReportJobFailure(e);
}
catch (CimException e)
{
var cje = CimJobException.CreateFromCimException(this.GetDescription(), this.JobContext, e);
this.ReportJobFailure(cje);
}
catch (PSInvalidOperationException)
{
lock (_jobStateLock)
{
bool everythingIsOk = false;
if (_jobWasStopped)
{
everythingIsOk = true;
}
if (_alreadyReachedCompletedState && _jobHadErrors)
{
everythingIsOk = true;
}
if (!everythingIsOk)
{
Dbg.Assert(false, "PSInvalidOperationException should only happen in certain job states");
throw;
}
}
}
}
catch (Exception e)
{
var cje = CimJobException.CreateFromAnyException(this.GetDescription(), this.JobContext, e);
this.ReportJobFailure(cje);
}
}
#region Operation options
internal virtual string GetProviderVersionExpectedByJob()
{
return this.JobContext.CmdletInvocationContext.CmdletDefinitionContext.CmdletizationClassVersion;
}
internal CimOperationOptions CreateOperationOptions()
{
var operationOptions = new CimOperationOptions(mustUnderstand: false)
{
CancellationToken = _cancellationTokenSource.Token,
WriteProgress = this.WriteProgressCallback,
WriteMessage = this.WriteMessageCallback,
WriteError = this.WriteErrorCallback,
PromptUser = this.PromptUserCallback,
};
operationOptions.SetOption("__MI_OPERATIONOPTIONS_IMPROVEDPERF_STREAMING", 1);
operationOptions.Flags |= this.JobContext.CmdletInvocationContext.CmdletDefinitionContext.SchemaConformanceLevel;
if (this.JobContext.CmdletInvocationContext.CmdletDefinitionContext.ResourceUri != null)
{
operationOptions.ResourceUri = this.JobContext.CmdletInvocationContext.CmdletDefinitionContext.ResourceUri;
}
if ((
(_jobContext.WarningActionPreference == ActionPreference.SilentlyContinue) ||
(_jobContext.WarningActionPreference == ActionPreference.Ignore)
) && (!_jobContext.IsRunningInBackground))
{
operationOptions.DisableChannel((UInt32)MessageChannel.Warning);
}
else
{
operationOptions.EnableChannel((UInt32)MessageChannel.Warning);
}
if ((
(_jobContext.VerboseActionPreference == ActionPreference.SilentlyContinue) ||
(_jobContext.VerboseActionPreference == ActionPreference.Ignore)
) && (!_jobContext.IsRunningInBackground))
{
operationOptions.DisableChannel((UInt32)MessageChannel.Verbose);
}
else
{
operationOptions.EnableChannel((UInt32)MessageChannel.Verbose);
}
if ((
(_jobContext.DebugActionPreference == ActionPreference.SilentlyContinue) ||
(_jobContext.DebugActionPreference == ActionPreference.Ignore)
) && (!_jobContext.IsRunningInBackground))
{
operationOptions.DisableChannel((UInt32)MessageChannel.Debug);
}
else
{
operationOptions.EnableChannel((UInt32)MessageChannel.Debug);
}
switch (this.JobContext.ShouldProcessOptimization)
{
case MshCommandRuntime.ShouldProcessPossibleOptimization.AutoNo_CanCallShouldProcessAsynchronously:
operationOptions.SetPromptUserRegularMode(CimCallbackMode.Report, automaticConfirmation: false);
break;
case MshCommandRuntime.ShouldProcessPossibleOptimization.AutoYes_CanCallShouldProcessAsynchronously:
operationOptions.SetPromptUserRegularMode(CimCallbackMode.Report, automaticConfirmation: true);
break;
case MshCommandRuntime.ShouldProcessPossibleOptimization.AutoYes_CanSkipShouldProcessCall:
operationOptions.SetPromptUserRegularMode(CimCallbackMode.Ignore, automaticConfirmation: true);
break;
case MshCommandRuntime.ShouldProcessPossibleOptimization.NoOptimizationPossible:
default:
operationOptions.PromptUserMode = CimCallbackMode.Inquire;
break;
}
switch (this.JobContext.ErrorActionPreference)
{
case ActionPreference.Continue:
case ActionPreference.SilentlyContinue:
case ActionPreference.Ignore:
operationOptions.WriteErrorMode = CimCallbackMode.Report;
break;
case ActionPreference.Stop:
case ActionPreference.Inquire:
default:
operationOptions.WriteErrorMode = CimCallbackMode.Inquire;
break;
}
if (!string.IsNullOrWhiteSpace(this.GetProviderVersionExpectedByJob()))
{
CimOperationOptionsHelper.SetCustomOption(
operationOptions,
"MI_OPERATIONOPTIONS_PROVIDERVERSION",
this.GetProviderVersionExpectedByJob(),
CimSensitiveValueConverter);
}
if (this.JobContext.CmdletizationModuleVersion != null)
{
CimOperationOptionsHelper.SetCustomOption(
operationOptions,
"MI_OPERATIONOPTIONS_POWERSHELL_MODULEVERSION",
this.JobContext.CmdletizationModuleVersion,
CimSensitiveValueConverter);
}
CimOperationOptionsHelper.SetCustomOption(
operationOptions,
"MI_OPERATIONOPTIONS_POWERSHELL_CMDLETNAME",
this.JobContext.CmdletInvocationInfo.MyCommand.Name,
CimSensitiveValueConverter);
if (!string.IsNullOrWhiteSpace(this.JobContext.Session.ComputerName))
{
CimOperationOptionsHelper.SetCustomOption(
operationOptions,
"MI_OPERATIONOPTIONS_POWERSHELL_COMPUTERNAME",
this.JobContext.Session.ComputerName,
CimSensitiveValueConverter);
}
CimCustomOptionsDictionary jobSpecificCustomOptions = this.GetJobSpecificCustomOptions();
if (jobSpecificCustomOptions != null)
{
jobSpecificCustomOptions.Apply(operationOptions, CimSensitiveValueConverter);
}
return operationOptions;
}
private readonly Lazy<CimCustomOptionsDictionary> _jobSpecificCustomOptions;
internal abstract CimCustomOptionsDictionary CalculateJobSpecificCustomOptions();
private CimCustomOptionsDictionary GetJobSpecificCustomOptions()
{
return _jobSpecificCustomOptions.Value;
}
#endregion
#region Controlling job state
private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
/// <summary>
/// Stops this job.
/// </summary>
public override void StopJob()
{
lock (_jobStateLock)
{
if (_jobWasStopped || _alreadyReachedCompletedState)
{
return;
}
_jobWasStopped = true;
if (!_jobWasStarted)
{
this.SetCompletedJobState(JobState.Stopped, null);
}
else if (_sleepAndRetryTimer != null)
{
_sleepAndRetryTimer.Dispose();
_sleepAndRetryTimer = null;
this.SetCompletedJobState(JobState.Stopped, null);
}
else
{
this.SetJobState(JobState.Stopping);
}
}
_cancellationTokenSource.Cancel();
}
private readonly object _jobStateLock = new object();
private bool _jobHadErrors;
private bool _jobWasStarted;
private bool _jobWasStopped;
private bool _alreadyReachedCompletedState;
internal bool JobHadErrors
{
get
{
lock (_jobStateLock)
{
return _jobHadErrors;
}
}
}
internal void ReportJobFailure(IContainsErrorRecord exception)
{
TerminatingErrorTracker terminatingErrorTracker = TerminatingErrorTracker.GetTracker(this.JobContext.CmdletInvocationInfo);
bool sessionWasAlreadyTerminated = false;
bool isThisTerminatingError = false;
Exception brokenSessionException = null;
lock (_jobStateLock)
{
if (!_jobWasStopped)
{
brokenSessionException = terminatingErrorTracker.GetExceptionIfBrokenSession(
this.JobContext.Session,
this.JobContext.CmdletInvocationContext.CmdletDefinitionContext.SkipTestConnection,
out sessionWasAlreadyTerminated);
}
}
if (brokenSessionException != null)
{
string brokenSessionMessage = string.Format(
CultureInfo.InvariantCulture,
CmdletizationResources.CimJob_BrokenSession,
brokenSessionException.Message);
exception = CimJobException.CreateWithFullControl(
this.JobContext,
brokenSessionMessage,
"CimJob_BrokenCimSession",
ErrorCategory.ResourceUnavailable,
brokenSessionException);
isThisTerminatingError = true;
}
else
{
CimJobException cje = exception as CimJobException;
if ((cje != null) && (cje.IsTerminatingError))
{
terminatingErrorTracker.MarkSessionAsTerminated(this.JobContext.Session, out sessionWasAlreadyTerminated);
isThisTerminatingError = true;
}
}
bool writeError = !sessionWasAlreadyTerminated;
if (writeError)
{
lock (_jobStateLock)
{
if (_jobWasStopped)
{
writeError = false;
}
}
}
ErrorRecord errorRecord = exception.ErrorRecord;
errorRecord.SetInvocationInfo(this.JobContext.CmdletInvocationInfo);
errorRecord.PreserveInvocationInfoOnce = true;
if (writeError)
{
lock (_jobStateLock)
{
if (!_alreadyReachedCompletedState)
{
if (isThisTerminatingError)
{
this.Error.Add(errorRecord);
CmdletMethodInvoker<bool> methodInvoker = terminatingErrorTracker.GetErrorReportingDelegate(errorRecord);
this.Results.Add(new PSStreamObject(PSStreamObjectType.ShouldMethod, methodInvoker));
}
else
{
this.WriteError(errorRecord);
}
}
}
}
this.SetCompletedJobState(JobState.Failed, errorRecord.Exception);
}
internal override void WriteWarning(string message)
{
message = this.JobContext.PrependComputerNameToMessage(message);
base.WriteWarning(message);
}
internal override void WriteVerbose(string message)
{
message = this.JobContext.PrependComputerNameToMessage(message);
base.WriteVerbose(message);
}
internal override void WriteDebug(string message)
{
message = this.JobContext.PrependComputerNameToMessage(message);
base.WriteDebug(message);
}
internal void SetCompletedJobState(JobState state, Exception reason)
{
lock (_jobStateLock)
{
if (_alreadyReachedCompletedState)
{
return;
}
_alreadyReachedCompletedState = true;
if ((state == JobState.Failed) || (reason != null))
{
_jobHadErrors = true;
}
if (_jobWasStopped)
{
state = JobState.Stopped;
}
else if (_jobHadErrors)
{
state = JobState.Failed;
}
}
this.FinishProgressReporting();
this.SetJobState(state, reason);
this.CloseAllStreams();
_cancellationTokenSource.Cancel();
}
#endregion
#region Support for progress reporting
private readonly ConcurrentDictionary<int, ProgressRecord> _activityIdToLastProgressRecord = new ConcurrentDictionary<int, ProgressRecord>();
internal override void WriteProgress(ProgressRecord progressRecord)
{
progressRecord.Activity = this.JobContext.PrependComputerNameToMessage(progressRecord.Activity);
_activityIdToLastProgressRecord.AddOrUpdate(
progressRecord.ActivityId,
progressRecord,
(activityId, oldProgressRecord) => progressRecord);
base.WriteProgress(progressRecord);
}
internal void FinishProgressReporting()
{
foreach (ProgressRecord lastProgressRecord in _activityIdToLastProgressRecord.Values)
{
if (lastProgressRecord.RecordType != ProgressRecordType.Completed)
{
var newProgressRecord = new ProgressRecord(lastProgressRecord.ActivityId, lastProgressRecord.Activity, lastProgressRecord.StatusDescription);
newProgressRecord.RecordType = ProgressRecordType.Completed;
newProgressRecord.PercentComplete = 100;
newProgressRecord.SecondsRemaining = 0;
this.WriteProgress(newProgressRecord);
}
}
}
#endregion
#region Handling extended semantics callbacks
private void WriteProgressCallback(string activity, string currentOperation, string statusDescription, UInt32 percentageCompleted, UInt32 secondsRemaining)
{
if (string.IsNullOrEmpty(activity))
{
activity = this.GetDescription();
}
if (string.IsNullOrEmpty(statusDescription))
{
statusDescription = this.StatusMessage;
}
Int32 signedSecondsRemaining;
if (secondsRemaining == UInt32.MaxValue)
{
signedSecondsRemaining = -1;
}
else if (secondsRemaining <= Int32.MaxValue)
{
signedSecondsRemaining = (Int32)secondsRemaining;
}
else
{
signedSecondsRemaining = Int32.MaxValue;
}
Int32 signedPercentageComplete;
if (percentageCompleted == UInt32.MaxValue)
{
signedPercentageComplete = -1;
}
else if (percentageCompleted <= 100)
{
signedPercentageComplete = (Int32)percentageCompleted;
}
else
{
signedPercentageComplete = 100;
}
var progressRecord = new ProgressRecord(unchecked((int)(_myJobNumber % int.MaxValue)), activity, statusDescription)
{
CurrentOperation = currentOperation,
PercentComplete = signedPercentageComplete,
SecondsRemaining = signedSecondsRemaining,
RecordType = ProgressRecordType.Processing,
};
this.ExceptionSafeWrapper(
delegate
{
this.WriteProgress(progressRecord);
});
}
private enum MessageChannel
{
Warning = 0,
Verbose = 1,
Debug = 2,
}
private void WriteMessageCallback(UInt32 channel, string message)
{
this.ExceptionSafeWrapper(
delegate
{
switch ((MessageChannel)channel)
{
case MessageChannel.Warning:
this.WriteWarning(message);
break;
case MessageChannel.Verbose:
this.WriteVerbose(message);
break;
case MessageChannel.Debug:
this.WriteDebug(message);
break;
default:
Dbg.Assert(false, "We shouldn't get messages in channels that we didn't register for");
break;
}
});
}
private CimResponseType BlockingWriteError(ErrorRecord errorRecord)
{
Exception exceptionThrownOnCmdletThread = null;
this.ExceptionSafeWrapper(
delegate
{
this.WriteError(errorRecord, out exceptionThrownOnCmdletThread);
});
return (exceptionThrownOnCmdletThread != null)
? CimResponseType.NoToAll
: CimResponseType.Yes;
}
private CimResponseType WriteErrorCallback(CimInstance cimError)
{
lock (_jobStateLock)
{
_jobHadErrors = true;
}
var cimException = new CimException(cimError);
var jobException = CimJobException.CreateFromCimException(this.GetDescription(), this.JobContext, cimException);
var errorRecord = jobException.ErrorRecord;
switch (this.JobContext.ErrorActionPreference)
{
case ActionPreference.Stop:
case ActionPreference.Inquire:
return this.BlockingWriteError(errorRecord);
default:
this.WriteError(errorRecord);
return CimResponseType.Yes;
}
}
private bool _userWasPromptedForContinuationOfProcessing;
private bool _userRespondedYesToAtLeastOneShouldProcess;
internal bool DidUserSuppressTheOperation
{
get
{
bool didUserSuppressTheOperation = _userWasPromptedForContinuationOfProcessing && (!_userRespondedYesToAtLeastOneShouldProcess);
return didUserSuppressTheOperation;
}
}
internal CimResponseType ShouldProcess(string target, string action)
{
string verboseDescription = StringUtil.Format(CommandBaseStrings.ShouldProcessMessage,
action,
target,
null);
return ShouldProcess(verboseDescription, null, null);
}
internal CimResponseType ShouldProcess(
string verboseDescription,
string verboseWarning,
string caption)
{
if (this.JobContext.IsRunningInBackground)
{
return CimResponseType.YesToAll;
}
if (this.JobContext.ShouldProcessOptimization == MshCommandRuntime.ShouldProcessPossibleOptimization.AutoNo_CanCallShouldProcessAsynchronously)
{
this.NonblockingShouldProcess(verboseDescription, verboseWarning, caption);
return CimResponseType.No;
}
if (this.JobContext.ShouldProcessOptimization == MshCommandRuntime.ShouldProcessPossibleOptimization.AutoYes_CanCallShouldProcessAsynchronously)
{
this.NonblockingShouldProcess(verboseDescription, verboseWarning, caption);
return CimResponseType.Yes;
}
Dbg.Assert(
(this.JobContext.ShouldProcessOptimization != MshCommandRuntime.ShouldProcessPossibleOptimization.AutoYes_CanSkipShouldProcessCall) ||
(this.JobContext.CmdletInvocationContext.CmdletDefinitionContext.ClientSideShouldProcess),
"MI layer should not call us when AutoYes_CanSkipShouldProcessCall optimization is in effect");
Exception exceptionThrownOnCmdletThread;
ShouldProcessReason shouldProcessReason;
bool shouldProcessResponse = this.ShouldProcess(verboseDescription, verboseWarning, caption, out shouldProcessReason, out exceptionThrownOnCmdletThread);
if (exceptionThrownOnCmdletThread != null)
{
return CimResponseType.NoToAll;
}
else if (shouldProcessResponse)
{
return CimResponseType.Yes;
}
else
{
return CimResponseType.No;
}
}
private CimResponseType PromptUserCallback(string message, CimPromptType promptType)
{
message = this.JobContext.PrependComputerNameToMessage(message);
Exception exceptionThrownOnCmdletThread = null;
CimResponseType result = CimResponseType.No;
_userWasPromptedForContinuationOfProcessing = true;
switch (promptType)
{
case CimPromptType.Critical:
this.ExceptionSafeWrapper(
delegate
{
if (this.ShouldContinue(message, null, out exceptionThrownOnCmdletThread))
{
result = CimResponseType.Yes;
}
else
{
result = CimResponseType.No;
}
});
break;
case CimPromptType.Normal:
this.ExceptionSafeWrapper(
delegate
{
result = this.ShouldProcess(message, null, null);
});
break;
default:
Dbg.Assert(false, "Unrecognized CimPromptType");
break;
}
if (exceptionThrownOnCmdletThread != null)
{
result = CimResponseType.NoToAll;
}
if ((result == CimResponseType.Yes) || (result == CimResponseType.YesToAll))
{
_userRespondedYesToAtLeastOneShouldProcess = true;
}
return result;
}
#endregion
internal static bool IsShowComputerNameMarkerPresent(CimInstance cimInstance)
{
PSObject pso = PSObject.AsPSObject(cimInstance);
PSPropertyInfo psShowComputerNameProperty = pso.InstanceMembers[RemotingConstants.ShowComputerNameNoteProperty] as PSPropertyInfo;
if (psShowComputerNameProperty == null)
{
return false;
}
return true.Equals(psShowComputerNameProperty.Value);
}
internal static void AddShowComputerNameMarker(PSObject pso)
{
PSPropertyInfo psShowComputerNameProperty = pso.InstanceMembers[RemotingConstants.ShowComputerNameNoteProperty] as PSPropertyInfo;
if (psShowComputerNameProperty != null)
{
psShowComputerNameProperty.Value = true;
}
else
{
psShowComputerNameProperty = new PSNoteProperty(RemotingConstants.ShowComputerNameNoteProperty, true);
pso.InstanceMembers.Add(psShowComputerNameProperty);
}
}
internal override void WriteObject(object outputObject)
{
CimInstance cimInstance = null;
PSObject pso = null;
if (outputObject is PSObject)
{
pso = PSObject.AsPSObject(outputObject);
cimInstance = pso.BaseObject as CimInstance;
}
else
{
cimInstance = outputObject as CimInstance;
}
if (cimInstance != null)
{
CimCmdletAdapter.AssociateSessionOfOriginWithInstance(cimInstance, this.JobContext.Session);
CimCustomOptionsDictionary.AssociateCimInstanceWithCustomOptions(cimInstance, this.GetJobSpecificCustomOptions());
}
if (this.JobContext.ShowComputerName)
{
if (pso == null)
{
pso = PSObject.AsPSObject(outputObject);
}
AddShowComputerNameMarker(pso);
if (cimInstance == null)
{
pso.Properties.Add(new PSNoteProperty(RemotingConstants.ComputerNameNoteProperty, this.JobContext.Session.ComputerName));
}
}
base.WriteObject(outputObject);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
bool isCompleted;
lock (_jobStateLock)
{
isCompleted = _alreadyReachedCompletedState;
}
if (!isCompleted)
{
this.StopJob();
this.Finished.WaitOne();
}
_cimSensitiveValueConverter.Dispose();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using Microsoft.Deployment.WindowsInstaller;
using sys = System.IO;
namespace WixSharp.Bootstrapper
{
/// <summary>
/// Class for defining a Wix# application for WiX standard Burn-based bootstrapper.
/// <para>It is nothing else but a light container for the WiX metadata associated with the
/// .NET assembly implementing WiX ManagedBootstrapper application.</para>
/// </summary>
public class ManagedBootstrapperApplication : WixStandardBootstrapperApplication
{
/// <summary>
/// The assembly implementing Bootstrapper UI application
/// </summary>
public string AppAssembly = "";
string rawAppAssembly = "";
string bootstrapperCoreConfig = "";
/// <summary>
/// Initializes a new instance of the <see cref="ManagedBootstrapperApplication"/> class.
/// </summary>
/// <param name="appAssembly">The application assembly.</param>
/// <param name="dependencies">The dependencies.</param>
public ManagedBootstrapperApplication(string appAssembly, params string[] dependencies)
{
AppAssembly = appAssembly;
Payloads = Payloads.Add(AppAssembly)
.AddRange(dependencies);
}
/// <summary>
/// Automatically generates required sources files for building the Bootstrapper. It is
/// used to automatically generate the files which, can be generated automatically without
/// user involvement (e.g. BootstrapperCore.config).
/// </summary>
/// <param name="outDir">The output directory.</param>
public override void AutoGenerateSources(string outDir)
{
//NOTE: while it is tempting, AutoGenerateSources cannot be called during initialization as it is too early.
//The call must be triggered by Compiler.Build* calls.
rawAppAssembly = AppAssembly;
if (rawAppAssembly.EndsWith("%this%"))
{
rawAppAssembly = Compiler.ResolveClientAsm(rawAppAssembly, outDir); //NOTE: if a new file is generated then the Compiler takes care for cleaning any temps
if (Payloads.Contains("%this%"))
Payloads = Payloads.Except(new[] { "%this%" }).Concat(new[] { rawAppAssembly }).ToArray();
}
string asmName = Path.GetFileNameWithoutExtension(Utils.OriginalAssemblyFile(rawAppAssembly));
var suppliedConfig = Payloads.FirstOrDefault(x => Path.GetFileName(x).SameAs("BootstrapperCore.config", true));
bootstrapperCoreConfig = suppliedConfig;
if (bootstrapperCoreConfig == null)
{
bootstrapperCoreConfig = Path.Combine(outDir, "BootstrapperCore.config");
sys.File.WriteAllText(bootstrapperCoreConfig,
@"<?xml version=""1.0"" encoding=""utf-8"" ?>
<configuration>
<configSections>
<sectionGroup name=""wix.bootstrapper"" type=""Microsoft.Tools.WindowsInstallerXml.Bootstrapper.BootstrapperSectionGroup, BootstrapperCore"">
<section name=""host"" type=""Microsoft.Tools.WindowsInstallerXml.Bootstrapper.HostSection, BootstrapperCore"" />
</sectionGroup>
</configSections>
<startup useLegacyV2RuntimeActivationPolicy=""true"">
<supportedRuntime version=""v4.0"" />
</startup>
<wix.bootstrapper>
<host assemblyName=""" + asmName + @""">
<supportedFramework version=""v4\Full"" />
<supportedFramework version=""v4\Client"" />
</host>
</wix.bootstrapper>
</configuration>
");
Compiler.TempFiles.Add(bootstrapperCoreConfig);
}
}
/// <summary>
/// Emits WiX XML.
/// </summary>
/// <returns></returns>
public override XContainer[] ToXml()
{
string winInstaller = typeof(Session).Assembly.Location;
var root = new XElement("BootstrapperApplicationRef");
root.SetAttribute("Id", "ManagedBootstrapperApplicationHost");
List<string> files = new List<string> { rawAppAssembly, bootstrapperCoreConfig };
files.AddRange(Payloads.Distinct()); //note %this% it already resolved at this stage into an absolutepath
if(!Payloads.Where(x=>Path.GetFileName(x).SameAs(Path.GetFileName(winInstaller))).Any())
files.Add(winInstaller);
if (files.Any())
files.Distinct().ForEach(p => root.Add(new XElement("Payload", new XAttribute("SourceFile", p))));
return new[] { root };
}
string primaryPackageId;
/// <summary>
/// Gets or sets the IDd of the primary package from the bundle.
/// <para>This ID is used by the application to detect the presence of the package on the target system
/// and trigger either install or uninstall action.</para>
/// <para>If it is not set then it is the Id of the last package in th bundle.</para>
/// </summary>
/// <value>
/// The primary package identifier.
/// </value>
public string PrimaryPackageId
{
get { return primaryPackageId; }
set { primaryPackageId = value; }
}
//public ChainItem DependencyPackage { get; set; }
}
/// <summary>
/// Container class for common members of the Bootstrapper standard applications.
/// </summary>
public abstract class WixStandardBootstrapperApplication : WixEntity
{
/// <summary>
/// Source file of the RTF license file or URL target of the license link.
/// </summary>
public string LicensePath;
/// <summary>
/// Source file of the logo graphic.
/// </summary>
[Xml]
public string LogoFile;
/// <summary>
/// Source file of the theme localization .wxl file.
/// </summary>
[Xml]
public string LocalizationFile;
/// <summary>
/// Emits WiX XML.
/// </summary>
/// <returns></returns>
public abstract XContainer[] ToXml();
/// <summary>
/// Automatically generates required sources files for building the Bootstrapper. It is
/// used to automatically generate the files which, can be generated automatically without
/// user involvement (e.g. BootstrapperCore.config).
/// </summary>
/// <param name="outDir">The output directory.</param>
public virtual void AutoGenerateSources(string outDir)
{
}
/// <summary>
/// Collection of paths to the package dependencies.
/// </summary>
public string[] Payloads = new string[0];
/// <summary>
/// The Bundle string variables associated with the Bootstrapper application.
/// <para>The variables are defined as a named values map.</para>
/// </summary>
/// <example>
/// <code>
/// new ManagedBootstrapperApplication("ManagedBA.dll")
/// {
/// StringVariablesDefinition = "FullInstall=Yes; Silent=No"
/// }
/// </code>
/// </example>
public string StringVariablesDefinition = "";
}
/// <summary>
/// Generic License-based WiX bootstrapper application.
/// <para>Depending on the value of LicensePath compiler will resolve the application in either <c>WixStandardBootstrapperApplication.RtfLicense</c>
/// or <c>WixStandardBootstrapperApplication.HyperlinkLicense</c> standard application.</para>
/// <para>Note: empty LicensePath will suppress displaying the license completely</para>
/// </summary>
/// <example>The following is an example of defining a simple bootstrapper displaying the license as an
/// embedded HTML file.
/// <code>
/// var bootstrapper = new Bundle("My Product",
/// new PackageGroupRef("NetFx40Web"),
/// new MsiPackage(productMsi) { DisplayInternalUI = true });
///
/// bootstrapper.AboutUrl = "https://wixsharp.codeplex.com/";
/// bootstrapper.IconFile = "app_icon.ico";
/// bootstrapper.Version = new Version("1.0.0.0");
/// bootstrapper.UpgradeCode = new Guid("6f330b47-2577-43ad-9095-1861bb25889b");
/// bootstrapper.Application.LogoFile = "logo.png";
/// bootstrapper.Application.LicensePath = "licence.html";
///
/// bootstrapper.Build();
/// </code>
/// </example>
public class LicenseBootstrapperApplication : WixStandardBootstrapperApplication
{
/// <summary>
/// Emits WiX XML.
/// </summary>
/// <returns></returns>
public override XContainer[] ToXml()
{
XNamespace bal = "http://schemas.microsoft.com/wix/BalExtension";
var root = new XElement("BootstrapperApplicationRef");
var app = this.ToXElement(bal + "WixStandardBootstrapperApplication");
if (LicensePath.IsNotEmpty() && LicensePath.EndsWith(".rtf", StringComparison.OrdinalIgnoreCase))
{
root.SetAttribute("Id", "WixStandardBootstrapperApplication.RtfLicense");
app.SetAttribute("LicenseFile", LicensePath);
}
else
{
root.SetAttribute("Id", "WixStandardBootstrapperApplication.HyperlinkLicense");
if (LicensePath.IsEmpty())
{
//cannot use SetAttribute as we want to preserve empty attrs
app.Add(new XAttribute("LicenseUrl", ""));
}
else
{
if (LicensePath.StartsWith("http")) //online HTML file
{
app.SetAttribute("LicenseUrl", LicensePath);
}
else
{
app.SetAttribute("LicenseUrl", System.IO.Path.GetFileName(LicensePath));
root.AddElement("Payload").AddAttributes("SourceFile=" + LicensePath);
}
}
}
root.Add(app);
return new[] { root };
}
}
}
| |
using System;
using NUnit.Framework;
namespace DotSpatial.Projections.Tests.Geographic
{
/// <summary>
/// This class contains all the tests for the Europe category of Geographic coordinate systems
/// </summary>
[TestFixture]
public class Europe
{
[Test]
public void Belge1972_EPSG31370()
{
// see https://dotspatial.codeplex.com/discussions/548133
var source = ProjectionInfo.FromEpsgCode(31370);
var dest = KnownCoordinateSystems.Geographic.World.WGS1984;
double[] vertices = { 156117.21, 133860.06 };
Reproject.ReprojectPoints(vertices, null, source, dest, 0, 1);
Assert.IsTrue(Math.Abs(vertices[0] - 4.455) < 1e-7);
Assert.IsTrue(Math.Abs(vertices[1] - 50.515485) < 1e-7);
}
[Test]
public void Albanian1987()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.Albanian1987;
Tester.TestProjection(pStart);
}
[Test]
public void ATFParis()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.ATFParis;
Tester.TestProjection(pStart);
}
[Test]
public void Belge1950Brussels()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.Belge1950Brussels;
Tester.TestProjection(pStart);
}
[Test]
public void Belge1972()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.Belge1972;
Tester.TestProjection(pStart);
}
[Test]
public void Bern1898()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.Bern1898;
Tester.TestProjection(pStart);
}
[Test]
public void Bern1898Bern()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.Bern1898Bern;
Tester.TestProjection(pStart);
}
[Test]
public void Bern1938()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.Bern1938;
Tester.TestProjection(pStart);
}
[Test]
public void CH1903()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.CH1903;
Tester.TestProjection(pStart);
}
[Test]
public void Datum73()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.Datum73;
Tester.TestProjection(pStart);
}
[Test]
public void DatumLisboaBessel()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.DatumLisboaBessel;
Tester.TestProjection(pStart);
}
[Test]
public void DatumLisboaHayford()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.DatumLisboaHayford;
Tester.TestProjection(pStart);
}
[Test]
public void DealulPiscului1933Romania()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.DealulPiscului1933Romania;
Tester.TestProjection(pStart);
}
[Test]
public void DealulPiscului1970Romania()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.DealulPiscului1970Romania;
Tester.TestProjection(pStart);
}
[Test]
public void DeutscheHauptdreiecksnetz()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.DeutscheHauptdreiecksnetz;
Tester.TestProjection(pStart);
}
[Test, Ignore]
// to be removed eventually, replaced with Amersfoort, DutchRD is to be found in ProjectedCategories.Nationalgrids as it is a Projected coordinate system
public void DutchRD()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.DutchRD;
Tester.TestProjection(pStart);
}
[Test]
public void Amersfoort()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.Amersfoort;
Tester.TestProjection(pStart);
}
[Test]
public void Estonia1937()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.Estonia1937;
Tester.TestProjection(pStart);
}
[Test]
public void Estonia1992()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.Estonia1992;
Tester.TestProjection(pStart);
}
[Test]
public void Estonia1997()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.Estonia1997;
Tester.TestProjection(pStart);
}
[Test]
public void ETRF1989()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.ETRF1989;
Tester.TestProjection(pStart);
}
[Test]
public void ETRS1989()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.ETRS1989;
Tester.TestProjection(pStart);
}
[Test]
public void EUREFFIN()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.EUREFFIN;
Tester.TestProjection(pStart);
}
[Test]
public void European1979()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.European1979;
Tester.TestProjection(pStart);
}
[Test]
public void EuropeanDatum1950()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.EuropeanDatum1950;
Tester.TestProjection(pStart);
}
[Test]
public void EuropeanDatum1987()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.EuropeanDatum1987;
Tester.TestProjection(pStart);
}
[Test]
[Ignore("Verify this test")]
public void Greek()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.Greek;
Tester.TestProjection(pStart);
}
[Test]
[Ignore("Verify this test")]
public void GreekAthens()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.GreekAthens;
Tester.TestProjection(pStart);
}
[Test]
public void GreekGeodeticRefSystem1987()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.GreekGeodeticRefSystem1987;
Tester.TestProjection(pStart);
}
[Test]
public void Hermannskogel()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.Hermannskogel;
Tester.TestProjection(pStart);
}
[Test]
public void Hjorsey1955()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.Hjorsey1955;
Tester.TestProjection(pStart);
}
[Test]
public void HungarianDatum1972()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.HungarianDatum1972;
Tester.TestProjection(pStart);
}
[Test]
public void IRENET95()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.IRENET95;
Tester.TestProjection(pStart);
}
[Test]
public void ISN1993()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.ISN1993;
Tester.TestProjection(pStart);
}
[Test]
public void Kartastokoordinaattijarjestelma()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.Kartastokoordinaattijarjestelma;
Tester.TestProjection(pStart);
}
[Test]
public void Lisbon()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.Lisbon;
Tester.TestProjection(pStart);
}
[Test]
public void LisbonLisbon()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.LisbonLisbon;
Tester.TestProjection(pStart);
}
[Test]
public void Lisbon1890()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.Lisbon1890;
Tester.TestProjection(pStart);
}
[Test]
public void Lisbon1890Lisbon()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.Lisbon1890Lisbon;
Tester.TestProjection(pStart);
}
[Test]
public void LKS1992()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.LKS1992;
Tester.TestProjection(pStart);
}
[Test]
public void LKS1994()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.LKS1994;
Tester.TestProjection(pStart);
}
[Test]
public void Luxembourg1930()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.Luxembourg1930;
Tester.TestProjection(pStart);
}
[Test]
public void Madrid1870Madrid()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.Madrid1870Madrid;
Tester.TestProjection(pStart);
}
[Test]
public void MGIFerro()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.MGIFerro;
Tester.TestProjection(pStart);
}
[Test]
public void MilitarGeographischeInstitut()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.MilitarGeographischeInstitut;
Tester.TestProjection(pStart);
}
[Test]
public void MonteMario()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.MonteMario;
Tester.TestProjection(pStart);
}
[Test]
public void MonteMarioRome()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.MonteMarioRome;
Tester.TestProjection(pStart);
}
[Test]
public void NGO1948()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.NGO1948;
Tester.TestProjection(pStart);
}
[Test]
public void NGO1948Oslo()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.NGO1948Oslo;
Tester.TestProjection(pStart);
}
[Test]
public void NorddeGuerreParis()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.NorddeGuerreParis;
Tester.TestProjection(pStart);
}
[Test]
public void NouvelleTriangulationFrancaise()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.NouvelleTriangulationFrancaise;
Tester.TestProjection(pStart);
}
[Test]
public void NTFParis()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.NTFParis;
Tester.TestProjection(pStart);
}
[Test]
public void OSSN1980()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.OSSN1980;
Tester.TestProjection(pStart);
}
[Test]
public void OSGB1936()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.OSGB1936;
Tester.TestProjection(pStart);
}
[Test]
public void OSGB1970SN()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.OSGB1970SN;
Tester.TestProjection(pStart);
}
[Test]
public void OSNI1952()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.OSNI1952;
Tester.TestProjection(pStart);
}
[Test]
public void Pulkovo1942()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.Pulkovo1942;
Tester.TestProjection(pStart);
}
[Test]
public void Pulkovo1942Adj1958()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.Pulkovo1942Adj1958;
Tester.TestProjection(pStart);
}
[Test]
public void Pulkovo1942Adj1983()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.Pulkovo1942Adj1983;
Tester.TestProjection(pStart);
}
[Test]
public void Pulkovo1995()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.Pulkovo1995;
Tester.TestProjection(pStart);
}
[Test]
public void Qornoq()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.Qornoq;
Tester.TestProjection(pStart);
}
[Test]
public void ReseauNationalBelge1950()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.ReseauNationalBelge1950;
Tester.TestProjection(pStart);
}
[Test]
public void ReseauNationalBelge1972()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.ReseauNationalBelge1972;
Tester.TestProjection(pStart);
}
[Test]
public void Reykjavik1900()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.Reykjavik1900;
Tester.TestProjection(pStart);
}
[Test]
public void RGF1993()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.RGF1993;
Tester.TestProjection(pStart);
}
[Test]
public void Roma1940()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.Roma1940;
Tester.TestProjection(pStart);
}
[Test]
public void RT1990()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.RT1990;
Tester.TestProjection(pStart);
}
[Test]
public void RT38()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.RT38;
Tester.TestProjection(pStart);
}
[Test]
public void RT38Stockholm()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.RT38Stockholm;
Tester.TestProjection(pStart);
}
[Test]
public void S42Hungary()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.S42Hungary;
Tester.TestProjection(pStart);
}
[Test]
public void SJTSK()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.SJTSK;
Tester.TestProjection(pStart);
}
[Test]
public void SWEREF99()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.SWEREF99;
Tester.TestProjection(pStart);
}
[Test]
public void SwissTRF1995()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.SwissTRF1995;
Tester.TestProjection(pStart);
}
[Test]
public void TM65()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.TM65;
Tester.TestProjection(pStart);
}
[Test]
public void TM75()
{
ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.TM75;
Tester.TestProjection(pStart);
}
}
}
| |
using System;
using System.Diagnostics;
using System.IO;
using System.Data;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
namespace MyGeneration
{
public enum ConnectionTestState
{
Waiting,
Error,
Success
}
/// <summary>
/// Summary description for TestConnectionForm.
/// </summary>
public class TestConnectionForm : System.Windows.Forms.Form
{
delegate void SetTextCallback(string text);
delegate void SetColorCallback(Color color);
delegate void SetCursorCallback(Cursor cursor);
delegate void SetSizeCallback(Size size);
delegate void SetCloseCallback();
private static bool up = true;
private static bool dotUp = true;
private static int dotCount = 0;
private static string connectionType = null;
private static string connectionString = null;
private static string info = null;
private static ConnectionTestState state = ConnectionTestState.Waiting;
private static Process process = null;
private System.Timers.Timer timer = new System.Timers.Timer(100);
private bool isSilent = false;
private System.Windows.Forms.Button buttonCancel;
private System.Windows.Forms.Label labelState;
private System.Windows.Forms.TextBox textBoxErrorMessage;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private int randNumber = 0;
public TestConnectionForm(string connType, string connString, bool isSilent)
{
Random rand = new Random();
randNumber = rand.Next(2);
dotCount=0;
this.isSilent = isSilent;
this.Cursor = Cursors.WaitCursor;
Test(connType, connString);
timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
timer.Enabled = true;
InitializeComponent();
}
private void SetStateText(string text)
{
if (this.labelState.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetStateText);
if (this.IsHandleCreated && !this.IsDisposed)
{
try
{
this.Invoke(d, new object[] { text });
}
catch { }
}
}
else
{
this.labelState.Text = text;
}
}
private void SetStateColor(Color color)
{
if (this.labelState.InvokeRequired)
{
SetColorCallback d = new SetColorCallback(SetStateColor);
if (this.IsHandleCreated && !this.IsDisposed)
{
try
{
this.Invoke(d, new object[] { color });
}
catch { }
}
}
else
{
this.labelState.ForeColor = color;
}
}
private void SetDescriptionText(string text)
{
if (this.textBoxErrorMessage.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetDescriptionText);
if (this.IsHandleCreated && !this.IsDisposed)
{
try
{
this.Invoke(d, new object[] { text });
}
catch { }
}
}
else
{
string nl = "@!!nl@!!";
this.textBoxErrorMessage.Text = text
.Replace("\r\n", nl)
.Replace("\n", nl)
.Replace("\r", nl)
.Replace(nl, Environment.NewLine);
}
}
private void SetButtonText(string text)
{
if (this.buttonCancel.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetButtonText);
if (this.IsHandleCreated && !this.IsDisposed)
{
try
{
this.Invoke(d, new object[] { text });
}
catch { }
}
}
else
{
this.buttonCancel.Text = text;
}
}
private void ChangeCursor(Cursor cursor)
{
if (this.InvokeRequired)
{
SetCursorCallback d = new SetCursorCallback(ChangeCursor);
if (this.IsHandleCreated && !this.IsDisposed)
{
try
{
this.Invoke(d, new object[] { cursor });
}
catch { }
}
}
else
{
this.Cursor = cursor;
}
}
private void ChangeSize(Size size)
{
if (this.InvokeRequired)
{
SetSizeCallback d = new SetSizeCallback(ChangeSize);
if (this.IsHandleCreated && !this.IsDisposed)
{
try
{
this.Invoke(d, new object[] { size });
}
catch { }
}
}
else
{
this.Size = size;
this.MaximumSize = new Size(0, 0);
this.FormBorderStyle = FormBorderStyle.Sizable;
}
}
private void CloseForm()
{
if (this.InvokeRequired)
{
SetCloseCallback d = new SetCloseCallback(CloseForm);
if (this.IsHandleCreated && !this.IsDisposed)
{
try
{
this.Invoke(d, new object[] { });
}
catch { }
}
}
else
{
this.Close();
}
}
private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
ConnectionTestState s = State;
string strState = "";
if (s == ConnectionTestState.Waiting)
{
byte rg = labelState.ForeColor.G;
if (up)
{
if (rg < 160) rg += 20;
else
{
up = false;
}
}
else
{
if (rg > 0) rg -= 20;
else
{
up = true;
}
}
//labelState.ForeColor = Color.FromArgb(0, rg, 255 - rg);
this.SetStateColor(Color.FromArgb(0, rg, 255 - rg));
if (randNumber == 0)
{
if (dotCount == 16) dotUp = false;
else if (dotCount == 0) dotUp = true;
if (dotUp) dotCount++;
else dotCount--;
strState = string.Empty;
for (int i=0; i<dotCount; i++) strState += ".";
strState += "Connecting";
for (int i=0; i<16-dotCount; i++) strState+= ".";
this.SetStateText(strState);
}
else
{
if (dotCount >= 2) dotUp = false;
else if (dotCount <= 0) dotUp = true;
if (dotUp) dotCount++;
else dotCount--;
string text = "Connecting";
foreach (char c in text)
{
for (int i=0; i < dotCount; i++)
{
strState += " ";
}
strState += c;
}
this.SetStateText(strState.Trim());
//labelState.Text = strState.Trim();
}
}
else
{
ChangeCursor(Cursors.Default);
this.timer.Enabled = false;
if (s == ConnectionTestState.Error)
{
this.SetStateText("Connection Error");
this.SetStateColor(Color.Red);
//labelState.Text = "Connection Error";
labelState.ForeColor = Color.Red;
this.SetDescriptionText(info);
//this.textBoxErrorMessage.Text = info;
this.ChangeSize(this.MaximumSize);
}
else if (s == ConnectionTestState.Success)
{
this.SetStateText("Connection Successful!");
this.SetStateColor(Color.Green);
//labelState.Text = "Connection Successful!";
//labelState.ForeColor = Color.Green;
if (this.isSilent)
this.CloseForm();
}
SetButtonText("&Close");
}
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
timer.Enabled = false;
timer.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.buttonCancel = new System.Windows.Forms.Button();
this.labelState = new System.Windows.Forms.Label();
this.textBoxErrorMessage = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// buttonCancel
//
this.buttonCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.buttonCancel.BackColor = System.Drawing.Color.WhiteSmoke;
this.buttonCancel.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.buttonCancel.Location = new System.Drawing.Point(292, 8);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(56, 24);
this.buttonCancel.TabIndex = 0;
this.buttonCancel.Text = "&Cancel";
this.buttonCancel.UseVisualStyleBackColor = false;
this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click);
//
// labelState
//
this.labelState.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.labelState.BackColor = System.Drawing.Color.LemonChiffon;
this.labelState.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelState.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.labelState.ForeColor = System.Drawing.Color.Blue;
this.labelState.Location = new System.Drawing.Point(8, 8);
this.labelState.Name = "labelState";
this.labelState.Size = new System.Drawing.Size(276, 24);
this.labelState.TabIndex = 2;
this.labelState.Text = "Connecting";
this.labelState.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// textBoxErrorMessage
//
this.textBoxErrorMessage.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.textBoxErrorMessage.BackColor = System.Drawing.Color.LemonChiffon;
this.textBoxErrorMessage.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.textBoxErrorMessage.ForeColor = System.Drawing.Color.Red;
this.textBoxErrorMessage.Location = new System.Drawing.Point(8, 40);
this.textBoxErrorMessage.Multiline = true;
this.textBoxErrorMessage.Name = "textBoxErrorMessage";
this.textBoxErrorMessage.ScrollBars = System.Windows.Forms.ScrollBars.Both;
this.textBoxErrorMessage.Size = new System.Drawing.Size(340, 0);
this.textBoxErrorMessage.TabIndex = 4;
//
// TestConnectionForm
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.BackColor = System.Drawing.Color.WhiteSmoke;
this.ClientSize = new System.Drawing.Size(356, 46);
this.ControlBox = false;
this.Controls.Add(this.textBoxErrorMessage);
this.Controls.Add(this.labelState);
this.Controls.Add(this.buttonCancel);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.MaximumSize = new System.Drawing.Size(358, 178);
this.MinimumSize = new System.Drawing.Size(358, 48);
this.Name = "TestConnectionForm";
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
public static void Test(string connectionType, string connectionString)
{
TestConnectionForm.dotCount = 3;
TestConnectionForm.connectionType = connectionType;
TestConnectionForm.connectionString = connectionString;
TestConnectionForm.state = ConnectionTestState.Waiting;
TestConnectionForm.info = null;
string file = Zeus.FileTools.RootFolder + @".\ZeusCmd.exe";
if (!File.Exists(file))
{
file = Zeus.FileTools.RootFolder + @"\..\..\..\..\ZeusCmd\bin\debug\ZeusCmd.exe";
if (!File.Exists(file))
{
file = Zeus.FileTools.RootFolder + @"\..\..\..\..\ZeusCmd\bin\release\ZeusCmd.exe";
}
}
if (File.Exists(file))
{
#if DEBUG
string args = string.Format("-tc \"{0}\" \"{1}\" -l \"{2}\"", connectionType.Replace("\"", "\\\""), connectionString.Replace("\"", "\\\""), "ZeusCmd.log");
#else
string args = string.Format("-tc \"{0}\" \"{1}\"", connectionType.Replace("\"", "\\\""), connectionString.Replace("\"", "\\\""));
#endif
ProcessStartInfo psi = new ProcessStartInfo(file, args);
psi.CreateNoWindow = true;
psi.UseShellExecute = false;
psi.RedirectStandardOutput = true;
process = new Process();
process.StartInfo = psi;
process.Start();
}
else
{
TestConnectionForm.state = ConnectionTestState.Error;
process = null;
}
}
public static ConnectionTestState State
{
get
{
if (process != null)
{
if (state == ConnectionTestState.Waiting)
{
if (process.HasExited)
{
if (process.ExitCode == 0)
{
state = ConnectionTestState.Success;
}
else
{
state = ConnectionTestState.Error;
info = process.StandardOutput.ReadToEnd().TrimEnd();
info = info.Substring(info.IndexOf("ERROR") + 6);
}
}
}
}
return state;
}
}
public static string LastErrorMsg
{
get { return info; }
}
public static void Cancel()
{
if (state == ConnectionTestState.Waiting)
{
state = ConnectionTestState.Error;
info = "Connection Cancelled";
if (process != null)
{
process.Kill();
}
}
}
private void buttonCancel_Click(object sender, System.EventArgs e)
{
Cancel();
this.Close();
}
}
}
| |
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using Thrift;
using Thrift.Protocol;
using Thrift.Transport;
using Evernote.EDAM.Type;
using Evernote.EDAM.UserStore;
using Evernote.EDAM.NoteStore;
using Evernote.EDAM.Error;
using Evernote.EDAM.Limits;
namespace everspaces
{
public class evernote
{
//private String username;
//private String password;
//private String consumerKey;
//private String consumerSecret;
private String authToken;
private NoteStore.Client noteStore;
public evernote(String username, String password, String consumerKey, String consumerSecret)
{
//this.username = username;
//this.password = password;
//this.consumerKey = consumerKey;
//this.consumerSecret = consumerSecret;
String evernoteHost = "sandbox.evernote.com";
String edamBaseUrl = "https://" + evernoteHost;
Uri userStoreUrl = new Uri(edamBaseUrl + "/edam/user");
TTransport userStoreTransport = new THttpClient(userStoreUrl);
TProtocol userStoreProtocol = new TBinaryProtocol(userStoreTransport);
UserStore.Client userStore = new UserStore.Client(userStoreProtocol);
bool versionOK =
userStore.checkVersion("C# EDAMTest",
Evernote.EDAM.UserStore.Constants.EDAM_VERSION_MAJOR,
Evernote.EDAM.UserStore.Constants.EDAM_VERSION_MINOR);
if (!versionOK)
{
throw new Exception("EDAM protocol out-of-date");
}
AuthenticationResult authResult = null;
try
{
authResult = userStore.authenticate(username, password,
consumerKey, consumerSecret);
}
catch (EDAMUserException ex)
{
String parameter = ex.Parameter;
EDAMErrorCode errorCode = ex.ErrorCode;
if (errorCode == EDAMErrorCode.INVALID_AUTH)
{
if (parameter == "consumerKey")
{
throw new Exception("Your consumer key was not accepted by " + evernoteHost);
}
else if (parameter == "username")
{
throw new Exception("You must authenticate using a username and password from " + evernoteHost);
}
else if (parameter == "password")
{
throw new Exception("The password that you entered is incorrect");
}
}
}
User user = authResult.User;
authToken = authResult.AuthenticationToken;
Uri noteStoreUrl = new Uri(edamBaseUrl + "/edam/note/" + user.ShardId);
TTransport noteStoreTransport = new THttpClient(noteStoreUrl);
TProtocol noteStoreProtocol = new TBinaryProtocol(noteStoreTransport);
noteStore = new NoteStore.Client(noteStoreProtocol);
}
public List<Tuple<string, string>> listNotebooks()
{
List<Notebook> notebooks = noteStore.listNotebooks(authToken);
List<Tuple<string, string>> nb = new List<Tuple<string, string>>();
foreach (Notebook notebook in notebooks)
{
nb.Add(new Tuple<string, string>(notebook.Guid, notebook.Name));
}
return nb;
}
public slink getNote(String guid)
{
Note note = noteStore.getNote(authToken, guid, true, true, true, true);
metadata meta = new metadata();
meta.x1 = Convert.ToInt32(noteStore.getNoteApplicationDataEntry(authToken, guid, "xone"));
meta.x2 = Convert.ToInt32(noteStore.getNoteApplicationDataEntry(authToken, guid, "xtwo"));
meta.y1 = Convert.ToInt32(noteStore.getNoteApplicationDataEntry(authToken, guid, "yone"));
meta.y2 = Convert.ToInt32(noteStore.getNoteApplicationDataEntry(authToken, guid, "ytwo"));
slink link = new slink(meta);
link.setNotebookGuid(note.NotebookGuid);
link.setNoteGuid(note.Guid);
link.setTitle(note.Title);
link.setComment(note.Attributes.Source);
link.setTags(note.TagNames);
link.setAppType(note.Attributes.SourceApplication);
link.setUri(note.Attributes.SourceURL);
List<Tuple<byte[], string>> res = null;
List<Resource> resources = note.Resources;
if(resources != null)
{
res = new List<Tuple<byte[], string>>();
foreach (Resource resource in resources)
{
res.Add(new Tuple<byte[], string>(resource.Data.Body, resource.Mime));
}
}
link.setResources(res);
return link;
}
public String createNote(slink link)
{
Note note = new Note();
String content = "";
note.Title = link.getTitle();
if(link.getNotebookGuid() != "")
{
note.NotebookGuid = link.getNotebookGuid();
}
content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">" +
"<en-note>" + link.getComment();
if(link.getResources() != null)
{
content += "<br/>";
note.Resources = new List<Resource>();
foreach (Tuple<byte[], string> resource in link.getResources())
{
byte[] file = resource.Item1;
byte[] hash = new MD5CryptoServiceProvider().ComputeHash(file);
string hashHex = BitConverter.ToString(hash).Replace("-", "").ToLower();
Data data = new Data();
data.Size = file.Length;
data.BodyHash = hash;
data.Body = file;
string mime = resource.Item2;
Resource res = new Resource();
res.Mime = mime;
res.Data = data;
note.Resources.Add(res);
content += "<en-media type=\"" + mime + "\" hash=\"" + hashHex + "\"/><br/>";
}
}
content += "</en-note>";
note.Content = content;
if(link.getTags() != null)
{
note.TagNames = link.getTags();
}
NoteAttributes attributes = new NoteAttributes();
attributes.ContentClass = "ucsd.spaces";
attributes.SourceURL = link.getUri();
attributes.Source = link.getComment();
attributes.SourceApplication = link.getAppType();
note.Attributes = attributes;
note = noteStore.createNote(authToken, note);
metadata meta = new metadata();
meta = link.getMetadata();
noteStore.setNoteApplicationDataEntry(authToken, note.Guid, "xone", meta.x1.ToString());
noteStore.setNoteApplicationDataEntry(authToken, note.Guid, "xtwo", meta.x2.ToString());
noteStore.setNoteApplicationDataEntry(authToken, note.Guid, "yone", meta.y1.ToString());
noteStore.setNoteApplicationDataEntry(authToken, note.Guid, "ytwo", meta.y2.ToString());
return note.Guid;
}
public String createNotebook(String notebookName)
{
Notebook notebook = new Notebook();
notebook.Name = notebookName;
notebook = noteStore.createNotebook(authToken, notebook);
return notebook.Guid;
}
public void deleteNote(String guid)
{
noteStore.expungeNote(authToken, guid);
}
public void deleteNotebook(String guid)
{
noteStore.expungeNotebook(authToken, guid);
}
public List<slink> searchNotes(string searchStr)
{
NoteFilter filter = new NoteFilter();
filter.Words = searchStr;
NoteList noteList = noteStore.findNotes(authToken, filter, 0, Evernote.EDAM.Limits.Constants.EDAM_USER_NOTES_MAX);
List<slink> links = new List<slink>();
foreach (Note note in noteList.Notes)
{
links.Add(getNote(note.Guid));
}
return links;
}
public List<slink> getAllNotes()
{
return searchNotes("*");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
#if NETCORE
using System.Runtime.Loader;
#endif
using Reinforced.Typings.Exceptions;
using Reinforced.Typings.Fluent;
namespace Reinforced.Typings.Cli
{
internal static class CoreTypeExtensions
{
internal static PropertyInfo[] _GetProperties(this Type t, BindingFlags flags)
{
#if NETCORE
return t.GetTypeInfo().GetProperties(flags);
#else
return t.GetProperties(flags);
#endif
}
internal static PropertyInfo _GetProperty(this Type t, string name)
{
#if NETCORE
return t.GetTypeInfo().GetProperty(name);
#else
return t.GetProperty(name);
#endif
}
internal static MethodInfo _GetMethod(this Type t, string name)
{
#if NETCORE
return t.GetTypeInfo().GetMethod(name);
#else
return t.GetMethod(name);
#endif
}
}
internal class ReferenceCacheEntry
{
}
/// <summary>
/// Class for CLI typescript typings utility
/// </summary>
public static class Bootstrapper
{
private static TextReader _profileReader;
private static string _profilePath;
private static AssemblyManager _assemblyManager;
private static HashSet<int> _suppressedWarnings = new HashSet<int>();
/// <summary>
/// Usage: rtcli.exe Assembly.dll [Assembly2.dll Assembly3.dll ... etc] file.ts
/// </summary>
/// <param name="args"></param>
public static void Main(string[] args)
{
Console.WriteLine("Reinforced.Typings CLI generator (c) 2015-2018 by Pavel B. Novikov");
ExporterConsoleParameters parameters = null;
if (args.Length == 0)
{
PrintHelp();
return;
}
try
{
if (string.Compare(args[0], "profile",
#if NETCORE
StringComparison.CurrentCultureIgnoreCase
#else
StringComparison.InvariantCultureIgnoreCase
#endif
) == 0)
{
if (!File.Exists(args[1]))
{
Console.WriteLine("Cannot find profile {0}, exiting", args[1]);
return;
}
parameters = ExtractParametersFromFile(args[1]);
}
else
{
parameters = ExtractParametersFromArgs(args);
}
if (parameters == null)
{
Console.WriteLine("No valid parameters found. Exiting.");
return;
}
_suppressedWarnings = ParseSuppressedWarnings(parameters.SuppressedWarnings);
var settings = InstantiateExportContext(parameters);
ResolveFluentMethod(settings,parameters);
TsExporter exporter = new TsExporter(settings);
exporter.Export();
_assemblyManager.TurnOffAdditionalResolvation();
foreach (var rtWarning in settings.Warnings)
{
var msg = VisualStudioFriendlyErrorMessage.Create(rtWarning);
Console.WriteLine(msg.ToString());
}
ReleaseReferencesTempFile(parameters);
}
catch (RtException rtException)
{
var error = VisualStudioFriendlyErrorMessage.Create(rtException);
Console.WriteLine(error.ToString());
Console.WriteLine(rtException.StackTrace);
ReleaseReferencesTempFile(parameters);
Environment.Exit(1);
}
catch (TargetInvocationException ex)
{
var e = ex.InnerException;
// ReSharper disable once PossibleNullReferenceException
BuildError(e.Message);
Console.WriteLine(e.StackTrace);
Environment.Exit(1);
}
catch (ReflectionTypeLoadException ex)
{
BuildError(ex.Message);
Console.WriteLine(ex.StackTrace);
if (ex.LoaderExceptions != null)
{
foreach (var elo in ex.LoaderExceptions)
{
BuildError(elo.Message);
Console.WriteLine(elo.StackTrace);
}
}
Environment.Exit(1);
}
catch (Exception ex)
{
BuildError(ex.Message);
Console.WriteLine(ex.StackTrace);
Environment.Exit(1);
}
if (_assemblyManager != null)
{
Console.WriteLine("Reinforced.Typings generation finished with total {0} assemblies loaded",
_assemblyManager.TotalLoadedAssemblies);
}
Console.WriteLine("Please build CompileTypeScript task to update javascript sources");
}
private static void ReleaseReferencesTempFile(ExporterConsoleParameters parameters)
{
if (_profileReader != null) _profileReader.Dispose();
if (!string.IsNullOrEmpty(_profilePath)) File.Delete(_profilePath);
if (parameters == null) return;
if (!string.IsNullOrEmpty(parameters.ReferencesTmpFilePath)) File.Delete(parameters.ReferencesTmpFilePath);
}
private static void ResolveFluentMethod(ExportContext context, ExporterConsoleParameters parameters)
{
if (string.IsNullOrEmpty(parameters.ConfigurationMethod)) return;
var methodPath = parameters.ConfigurationMethod;
var path = new Stack<string>(methodPath.Split('.'));
var method = path.Pop();
var fullQualifiedType = string.Join(".", path.Reverse());
bool isFound = false;
foreach (var sourceAssembly in context.SourceAssemblies)
{
var type = sourceAssembly.GetType(fullQualifiedType, false);
if (type != null)
{
var constrMethod = type._GetMethod(method);
if (constrMethod != null && constrMethod.IsStatic)
{
var pars = constrMethod.GetParameters();
if (pars.Length == 1/* && pars[0].ParameterType == typeof(ConfigurationBuilder)*/)
{
isFound = true;
context.ConfigurationMethod = builder => constrMethod.Invoke(null, new object[] { builder });
break;
}
}
}
}
if (!isFound) BuildWarn(ErrorMessages.RTW0009_CannotFindFluentMethod, methodPath);
}
public static ExportContext InstantiateExportContext(ExporterConsoleParameters parameters)
{
_assemblyManager = new AssemblyManager(parameters.SourceAssemblies,_profileReader,parameters.ReferencesTmpFilePath,BuildWarn);
var srcAssemblies = _assemblyManager.GetAssembliesFromArgs();
ExportContext context = new ExportContext(srcAssemblies)
{
Hierarchical = parameters.Hierarchy,
TargetDirectory = parameters.TargetDirectory,
TargetFile = parameters.TargetFile,
DocumentationFilePath = parameters.DocumentationFilePath,
SuppressedWarningCodes = ParseSuppressedWarnings(parameters.SuppressedWarnings)
};
return context;
}
public static void PrintHelp()
{
Console.WriteLine("Available parameters:");
Console.WriteLine();
var t = typeof(ExporterConsoleParameters);
var props = t._GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var propertyInfo in props)
{
var attr = propertyInfo.GetCustomAttribute<ConsoleHelpAttribute>();
if (attr != null)
{
var req = attr.RequiredType;
string requiredText = null;
switch (req)
{
case Required.Not:
requiredText = "(not required)";
break;
case Required.Is:
requiredText = "(required)";
break;
case Required.Partially:
requiredText = "(sometimes required)";
break;
}
Console.WriteLine(propertyInfo.Name + " " + requiredText);
var lines = attr.HelpText.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var line in lines)
{
Console.WriteLine("\t{0}", line);
}
Console.WriteLine();
}
}
}
private static void BuildWarn(ErrorMessage msg, params object[] args)
{
if (_suppressedWarnings.Contains(msg.Code)) return;
VisualStudioFriendlyErrorMessage vsm = VisualStudioFriendlyErrorMessage.Create(msg.Warn(args));
Console.WriteLine(vsm.ToString());
}
private static void BuildError(string message, params object[] args)
{
var errorMessage = string.Format(message, args);
VisualStudioFriendlyErrorMessage vsm = new VisualStudioFriendlyErrorMessage(999, errorMessage, VisualStudioFriendlyMessageType.Error, "Unexpected");
Console.WriteLine(vsm.ToString());
}
public static HashSet<int> ParseSuppressedWarnings(string input)
{
var result = new HashSet<int>();
if (string.IsNullOrEmpty(input)) return result;
var values = input.Split(';');
foreach (var warningCode in values)
{
//for some reason there is no StringSplitOptions for netcoreapp1.0
if (string.IsNullOrEmpty(warningCode)) continue;
var filtered = new string(warningCode.Where(char.IsDigit).ToArray());
bool parsed = int.TryParse(filtered, out int intWarningCode);
if (parsed) result.Add(intWarningCode);
else
{
BuildWarn(ErrorMessages.RTW0010_CannotParseWarningCode,warningCode);
}
}
return result;
}
private static ExporterConsoleParameters ExtractParametersFromFile(string fileName)
{
_profilePath = fileName;
_profileReader = File.OpenText(fileName);
return ExporterConsoleParameters.FromFile(_profileReader);
}
public static ExporterConsoleParameters ExtractParametersFromArgs(string[] args)
{
var t = typeof(ExporterConsoleParameters);
var instance = new ExporterConsoleParameters();
foreach (var s in args)
{
var trimmed = s.TrimStart('-');
var kv = trimmed.Split('=');
if (kv.Length != 2)
{
BuildWarn(ErrorMessages.RTW0011_UnrecognizedConfigurationParameter, s);
continue;
}
var key = kv[0].Trim();
var value = kv[1].Trim().Trim('"');
var prop = t._GetProperty(key);
if (prop == null)
{
BuildWarn(ErrorMessages.RTW0011_UnrecognizedConfigurationParameter, key);
continue;
}
if (prop.PropertyType == typeof(bool))
{
bool parsedValue = Boolean.Parse(value);
prop.SetValue(instance, parsedValue);
continue;
}
if (prop.PropertyType == typeof(string))
{
prop.SetValue(instance, value);
continue;
}
if (prop.PropertyType == typeof(string[]))
{
var parsedValue = value.Split(';');
prop.SetValue(instance, parsedValue);
continue;
}
BuildWarn(ErrorMessages.RTW0012_UnrecognizedConfigurationParameterValue, key);
}
try
{
instance.Validate();
}
catch (Exception ex)
{
BuildError("Parameter validation error: {0}", ex.Message);
PrintHelp();
return null;
}
return instance;
}
}
}
| |
using System.Linq;
using System.Collections.Generic;
using System;
using System.Reflection;
#if VELOX_DB
namespace Velox.DB.Core
#else
namespace Velox.Core
#endif
{
[Flags]
public enum TypeFlags
{
Byte = 1<<0,
SByte = 1<<1,
Int16 = 1<<2,
UInt16 = 1<<3,
Int32 = 1<<4,
UInt32 = 1<<5,
Int64 = 1<<6,
UInt64 = 1<<7,
Single = 1<<8,
Double = 1<<9,
Decimal = 1<<10,
Boolean = 1<<11,
Char = 1<<12,
Enum = 1<<13,
DateTime = 1<<14,
TimeSpan = 1<<15,
DateTimeOffset = 1<<16,
String = 1<<17,
Guid = 1<<18,
Nullable = 1<<24,
ValueType = 1<<25,
CanBeNull = 1<<26,
Array = 1<<27,
Integer8 = Byte|SByte,
Integer16 = Int16|UInt16,
Integer32 = Int32|UInt32,
Integer64 = Int64|UInt64,
SignedInteger = SByte|Int16|Int32|Int64,
UnsignedInteger = Byte|UInt16|UInt32|UInt64,
FloatingPoint = Single|Double|Decimal,
Integer = Integer8|Integer16|Integer32|Integer64,
Numeric = Integer|FloatingPoint,
Primitive = Integer|Boolean|Char|Single|Double
}
public class TypeInspector
{
private readonly TypeInfo _typeInfo;
private readonly TypeInfo _realTypeInfo;
public Type Type { get; }
public Type RealType { get; }
public TypeFlags TypeFlags { get; }
private static readonly Dictionary<Type, TypeFlags> _typeflagsMap = new Dictionary<Type, TypeFlags>()
{
{ typeof(Byte), TypeFlags.Byte},
{ typeof(SByte), TypeFlags.SByte},
{ typeof(Int16), TypeFlags.Int16},
{ typeof(UInt16), TypeFlags.UInt16},
{ typeof(Int32), TypeFlags.Int32},
{ typeof(UInt32), TypeFlags.UInt32},
{ typeof(Int64), TypeFlags.Int64},
{ typeof(UInt64), TypeFlags.UInt64},
{ typeof(Single), TypeFlags.Single},
{ typeof(Double), TypeFlags.Double},
{ typeof(Decimal), TypeFlags.Decimal},
{ typeof(Boolean), TypeFlags.Boolean},
{ typeof(Char), TypeFlags.Char},
{ typeof(DateTime), TypeFlags.DateTime},
{ typeof(TimeSpan), TypeFlags.TimeSpan},
{ typeof(DateTimeOffset), TypeFlags.DateTimeOffset},
{ typeof(String), TypeFlags.String},
{ typeof(Guid), TypeFlags.Guid}
};
public TypeInspector(Type type)
{
Type = type;
RealType = Nullable.GetUnderlyingType(Type) ?? Type;
_typeInfo = type.GetTypeInfo();
_realTypeInfo = RealType.GetTypeInfo();
TypeFlags = BuildTypeFlags();
}
private TypeFlags BuildTypeFlags()
{
TypeFlags flags;
_typeflagsMap.TryGetValue(RealType, out flags);
if (Type != RealType)
flags |= TypeFlags.Nullable | TypeFlags.CanBeNull;
if (_realTypeInfo.IsValueType)
flags |= TypeFlags.ValueType;
else
flags |= TypeFlags.CanBeNull;
if (_realTypeInfo.IsEnum)
{
TypeFlags enumTypeFlags;
if (_typeflagsMap.TryGetValue(Enum.GetUnderlyingType(RealType), out enumTypeFlags))
flags |= enumTypeFlags;
flags |= TypeFlags.Enum;
}
else if (Type.IsArray)
{
flags |= TypeFlags.Array;
TypeFlags arrayTypeFlags;
if (_typeflagsMap.TryGetValue(Type.GetElementType(), out arrayTypeFlags))
flags |= arrayTypeFlags;
}
return flags;
}
private T WalkAndFindSingle<T>(Func<Type, T> f)
{
Type t = Type;
while (t != null)
{
T result = f(t);
if (result != null)
return result;
t = t.GetTypeInfo().BaseType;
}
return default(T);
}
private T[] WalkAndFindMultiple<T>(Func<Type, IEnumerable<T>> f) where T : class
{
var list = new List<T>();
Type t = Type;
while (t != null)
{
IEnumerable<T> result = f(t);
if (result != null)
list.AddRange(result);
t = t.GetTypeInfo().BaseType;
}
return list.ToArray();
}
public bool IsArray => Is(TypeFlags.Array);
public Type ArrayElementType => IsArray ? Type.GetElementType() : null;
public bool IsGenericType => _typeInfo.IsGenericType;
public bool IsGenericTypeDefinition => _typeInfo.IsGenericTypeDefinition;
public bool IsNullable => Is(TypeFlags.Nullable);
public bool CanBeNull => Is(TypeFlags.CanBeNull);
public bool IsPrimitive => Is(TypeFlags.Primitive);
public bool IsValueType => Is(TypeFlags.ValueType);
public Type BaseType => _typeInfo.BaseType;
public bool IsEnum => Is(TypeFlags.Enum);
public bool Is(TypeFlags flags) => (TypeFlags & flags) != 0;
public bool IsSubclassOf(Type type) => WalkAndFindSingle(t => t.GetTypeInfo().BaseType == type);
public object DefaultValue()
{
if (CanBeNull)
return null;
return Activator.CreateInstance(RealType);
}
public MethodInfo GetMethod(string name, Type[] types)
{
return WalkAndFindSingle(t => t.GetTypeInfo().GetDeclaredMethods(name).FirstOrDefault(mi => types.SequenceEqual(mi.GetParameters().Select(p => p.ParameterType))));
}
public MethodInfo GetMethod(string name, BindingFlags bindingFlags)
{
return WalkAndFindSingle(t => t.GetTypeInfo().GetDeclaredMethods(name).FirstOrDefault(mi => mi.Inspector().MatchBindingFlags(bindingFlags)));
}
public bool HasAttribute<T>(bool inherit) where T : Attribute
{
return _typeInfo.IsDefined(typeof(T), inherit);
}
public T GetAttribute<T>(bool inherit) where T : Attribute
{
return _typeInfo.GetCustomAttributes<T>(inherit).FirstOrDefault();
}
public T[] GetAttributes<T>(bool inherit) where T : Attribute
{
return (T[])_typeInfo.GetCustomAttributes(typeof(T), inherit).ToArray();
}
public bool IsAssignableFrom(Type type)
{
return _typeInfo.IsAssignableFrom(type.GetTypeInfo());
}
public ConstructorInfo[] GetConstructors()
{
return _typeInfo.DeclaredConstructors.ToArray();
}
public MemberInfo[] GetMember(string propertyName)
{
return WalkAndFindMultiple(t => t.GetTypeInfo().DeclaredMembers.Where(m => m.Name == propertyName));
}
public PropertyInfo GetIndexer(Type[] types)
{
return WalkAndFindSingle(t => t.GetTypeInfo().DeclaredProperties.FirstOrDefault(pi => pi.Name == "Item" && LazyBinder.MatchParameters(types, pi.GetIndexParameters())));
}
public T[] GetCustomAttributes<T>(bool inherit) where T:Attribute
{
return _typeInfo.GetCustomAttributes<T>(inherit).ToArray();
}
public MethodInfo GetPropertyGetter(string propertyName, Type[] parameterTypes)
{
return GetMethod("get_" + propertyName, parameterTypes);
}
public PropertyInfo GetProperty(string propName)
{
return WalkAndFindSingle(t => t.GetTypeInfo().GetDeclaredProperty(propName));
}
public FieldInfo GetField(string fieldName)
{
return WalkAndFindSingle(t => t.GetTypeInfo().GetDeclaredField(fieldName));
}
public bool ImplementsOrInherits(Type type)
{
if (type.GetTypeInfo().IsGenericTypeDefinition && type.GetTypeInfo().IsInterface)
{
return _typeInfo.ImplementedInterfaces.Any(t => (t.GetTypeInfo().IsGenericType && t.GetTypeInfo().GetGenericTypeDefinition() == type));
}
return type.GetTypeInfo().IsAssignableFrom(_typeInfo);
}
public bool ImplementsOrInherits<T>()
{
return ImplementsOrInherits(typeof (T));
}
public MethodInfo GetMethod(string methodName, BindingFlags bindingFlags, Type[] parameterTypes)
{
return WalkAndFindSingle(t => LazyBinder.SelectBestMethod(t.GetTypeInfo().GetDeclaredMethods(methodName),parameterTypes,bindingFlags));
}
public Type[] GetGenericArguments() => Type.GenericTypeArguments;
public FieldInfo[] GetFields(BindingFlags bindingFlags)
{
if ((bindingFlags & BindingFlags.DeclaredOnly) != 0)
return _typeInfo.DeclaredFields.Where(fi => fi.Inspector().MatchBindingFlags(bindingFlags)).ToArray();
return WalkAndFindMultiple(t => t.GetTypeInfo().DeclaredFields.Where(fi => fi.Inspector().MatchBindingFlags(bindingFlags)));
}
public PropertyInfo[] GetProperties(BindingFlags bindingFlags)
{
if ((bindingFlags & BindingFlags.DeclaredOnly) != 0)
return _typeInfo.DeclaredProperties.Where(pi => pi.Inspector().MatchBindingFlags(bindingFlags)).ToArray();
return WalkAndFindMultiple(t => t.GetTypeInfo().DeclaredProperties.Where(pi => pi.Inspector().MatchBindingFlags(bindingFlags)));
}
public MethodInfo[] GetMethods(BindingFlags bindingFlags)
{
if ((bindingFlags & BindingFlags.DeclaredOnly) != 0)
return _typeInfo.DeclaredMethods.Where(mi => mi.Inspector().MatchBindingFlags(bindingFlags)).ToArray();
return WalkAndFindMultiple(t => t.GetTypeInfo().DeclaredMethods.Where(mi => mi.Inspector().MatchBindingFlags(bindingFlags)));
}
public Type[] GetInterfaces() => _typeInfo.ImplementedInterfaces.ToArray();
public FieldOrPropertyInfo[] GetFieldsAndProperties(BindingFlags bindingFlags)
{
MemberInfo[] members;
if ((bindingFlags & BindingFlags.DeclaredOnly) != 0)
members = _typeInfo.DeclaredFields.Where(fi => fi.Inspector().MatchBindingFlags(bindingFlags)).Union<MemberInfo>(_typeInfo.DeclaredProperties.Where(pi => pi.Inspector().MatchBindingFlags(bindingFlags))).ToArray();
else
members = WalkAndFindMultiple(t => t.GetTypeInfo().DeclaredFields.Where(fi => fi.Inspector().MatchBindingFlags(bindingFlags)).Union<MemberInfo>(t.GetTypeInfo().DeclaredProperties.Where(pi => pi.Inspector().MatchBindingFlags(bindingFlags))));
return members.Select(m => new FieldOrPropertyInfo(m)).ToArray();
}
}
}
| |
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
namespace WeifenLuo.WinFormsUI.Docking
{
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/ClassDef/*'/>
internal class VS2003AutoHideStrip : AutoHideStripBase
{
private class TabVS2003 : Tab
{
internal TabVS2003(IDockContent content)
: base(content)
{
}
private int m_tabX = 0;
protected internal int TabX
{
get { return m_tabX; }
set { m_tabX = value; }
}
private int m_tabWidth = 0;
protected internal int TabWidth
{
get { return m_tabWidth; }
set { m_tabWidth = value; }
}
}
private const int _ImageHeight = 16;
private const int _ImageWidth = 16;
private const int _ImageGapTop = 2;
private const int _ImageGapLeft = 4;
private const int _ImageGapRight = 4;
private const int _ImageGapBottom = 2;
private const int _TextGapLeft = 4;
private const int _TextGapRight = 10;
private const int _TabGapTop = 3;
private const int _TabGapLeft = 2;
private const int _TabGapBetween = 10;
private static Matrix _matrixIdentity;
private static DockState[] _dockStates;
#region Customizable Properties
private static StringFormat _stringFormatTabHorizontal = null;
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="StringFormatTabHorizontal"]/*'/>
protected virtual StringFormat StringFormatTabHorizontal
{
get
{
if (_stringFormatTabHorizontal == null)
{
_stringFormatTabHorizontal = new StringFormat();
_stringFormatTabHorizontal.Alignment = StringAlignment.Near;
_stringFormatTabHorizontal.LineAlignment = StringAlignment.Center;
_stringFormatTabHorizontal.FormatFlags = StringFormatFlags.NoWrap;
}
return _stringFormatTabHorizontal;
}
}
private static StringFormat _stringFormatTabVertical;
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="StringFormatTabVertical"]/*'/>
protected virtual StringFormat StringFormatTabVertical
{
get
{
if (_stringFormatTabVertical == null)
{
_stringFormatTabVertical = new StringFormat();
_stringFormatTabVertical.Alignment = StringAlignment.Near;
_stringFormatTabVertical.LineAlignment = StringAlignment.Center;
_stringFormatTabVertical.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.DirectionVertical;
}
return _stringFormatTabVertical;
}
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="ImageHeight"]/*'/>
protected virtual int ImageHeight
{
get { return _ImageHeight; }
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="ImageWidth"]/*'/>
protected virtual int ImageWidth
{
get { return _ImageWidth; }
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="ImageGapTop"]/*'/>
protected virtual int ImageGapTop
{
get { return _ImageGapTop; }
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="ImageGapLeft"]/*'/>
protected virtual int ImageGapLeft
{
get { return _ImageGapLeft; }
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="ImageGapRight"]/*'/>
protected virtual int ImageGapRight
{
get { return _ImageGapRight; }
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="ImageGapBottom"]/*'/>
protected virtual int ImageGapBottom
{
get { return _ImageGapBottom; }
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="TextGapLeft"]/*'/>
protected virtual int TextGapLeft
{
get { return _TextGapLeft; }
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="TextGapRight"]/*'/>
protected virtual int TextGapRight
{
get { return _TextGapRight; }
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="TabGapTop"]/*'/>
protected virtual int TabGapTop
{
get { return _TabGapTop; }
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="TabGapLeft"]/*'/>
protected virtual int TabGapLeft
{
get { return _TabGapLeft; }
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="TabGapBetween"]/*'/>
protected virtual int TabGapBetween
{
get { return _TabGapBetween; }
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="BrushTabBackground"]/*'/>
protected virtual Brush BrushTabBackground
{
get { return SystemBrushes.Control; }
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="PenTabBorder"]/*'/>
protected virtual Pen PenTabBorder
{
get { return SystemPens.GrayText; }
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="BrushTabText"]/*'/>
protected virtual Brush BrushTabText
{
get { return SystemBrushes.FromSystemColor(SystemColors.ControlDarkDark); }
}
#endregion
private Matrix MatrixIdentity
{
get { return _matrixIdentity; }
}
private DockState[] DockStates
{
get { return _dockStates; }
}
static VS2003AutoHideStrip()
{
_matrixIdentity = new Matrix();
_dockStates = new DockState[4];
_dockStates[0] = DockState.DockLeftAutoHide;
_dockStates[1] = DockState.DockRightAutoHide;
_dockStates[2] = DockState.DockTopAutoHide;
_dockStates[3] = DockState.DockBottomAutoHide;
}
public VS2003AutoHideStrip(DockPanel panel) : base(panel)
{
SetStyle(ControlStyles.ResizeRedraw, true);
SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
BackColor = Color.WhiteSmoke;
}
/// <exclude/>
protected override void OnPaint(PaintEventArgs e)
{
Graphics g = e.Graphics;
DrawTabStrip(g);
}
/// <exclude/>
protected override void OnLayout(LayoutEventArgs levent)
{
CalculateTabs();
base.OnLayout (levent);
}
private void DrawTabStrip(Graphics g)
{
DrawTabStrip(g, DockState.DockTopAutoHide);
DrawTabStrip(g, DockState.DockBottomAutoHide);
DrawTabStrip(g, DockState.DockLeftAutoHide);
DrawTabStrip(g, DockState.DockRightAutoHide);
}
private void DrawTabStrip(Graphics g, DockState dockState)
{
Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState);
if (rectTabStrip.IsEmpty)
return;
Matrix matrixIdentity = g.Transform;
if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide)
{
Matrix matrixRotated = new Matrix();
matrixRotated.RotateAt(90, new PointF((float)rectTabStrip.X + (float)rectTabStrip.Height / 2,
(float)rectTabStrip.Y + (float)rectTabStrip.Height / 2));
g.Transform = matrixRotated;
}
foreach (Pane pane in GetPanes(dockState))
{
foreach (TabVS2003 tab in pane.AutoHideTabs)
DrawTab(g, tab);
}
g.Transform = matrixIdentity;
}
private void CalculateTabs()
{
CalculateTabs(DockState.DockTopAutoHide);
CalculateTabs(DockState.DockBottomAutoHide);
CalculateTabs(DockState.DockLeftAutoHide);
CalculateTabs(DockState.DockRightAutoHide);
}
private void CalculateTabs(DockState dockState)
{
Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState);
int imageHeight = rectTabStrip.Height - ImageGapTop - ImageGapBottom;
int imageWidth = ImageWidth;
if (imageHeight > ImageHeight)
imageWidth = ImageWidth * (imageHeight/ImageHeight);
using (Graphics g = CreateGraphics())
{
int x = TabGapLeft + rectTabStrip.X;
foreach (Pane pane in GetPanes(dockState))
{
int maxWidth = 0;
foreach (TabVS2003 tab in pane.AutoHideTabs)
{
int width = imageWidth + ImageGapLeft + ImageGapRight +
(int)g.MeasureString(tab.Content.DockHandler.TabText, Font).Width + 1 +
TextGapLeft + TextGapRight;
if (width > maxWidth)
maxWidth = width;
}
foreach (TabVS2003 tab in pane.AutoHideTabs)
{
tab.TabX = x;
if (tab.Content == pane.DockPane.ActiveContent)
tab.TabWidth = maxWidth;
else
tab.TabWidth = imageWidth + ImageGapLeft + ImageGapRight;
x += tab.TabWidth;
}
x += TabGapBetween;
}
}
}
private void DrawTab(Graphics g, TabVS2003 tab)
{
Rectangle rectTab = GetTabRectangle(tab);
if (rectTab.IsEmpty)
return;
DockState dockState = tab.Content.DockHandler.DockState;
IDockContent content = tab.Content;
OnBeginDrawTab(tab);
Brush brushTabBackGround = BrushTabBackground;
Pen penTabBorder = PenTabBorder;
Brush brushTabText = BrushTabText;
g.FillRectangle(brushTabBackGround, rectTab);
g.DrawLine(penTabBorder, rectTab.Left, rectTab.Top, rectTab.Left, rectTab.Bottom);
g.DrawLine(penTabBorder, rectTab.Right, rectTab.Top, rectTab.Right, rectTab.Bottom);
if (dockState == DockState.DockTopAutoHide || dockState == DockState.DockRightAutoHide)
g.DrawLine(penTabBorder, rectTab.Left, rectTab.Bottom, rectTab.Right, rectTab.Bottom);
else
g.DrawLine(penTabBorder, rectTab.Left, rectTab.Top, rectTab.Right, rectTab.Top);
// Set no rotate for drawing icon and text
Matrix matrixRotate = g.Transform;
g.Transform = MatrixIdentity;
// Draw the icon
Rectangle rectImage = rectTab;
rectImage.X += ImageGapLeft;
rectImage.Y += ImageGapTop;
int imageHeight = rectTab.Height - ImageGapTop - ImageGapBottom;
int imageWidth = ImageWidth;
if (imageHeight > ImageHeight)
imageWidth = ImageWidth * (imageHeight/ImageHeight);
rectImage.Height = imageHeight;
rectImage.Width = imageWidth;
rectImage = GetTransformedRectangle(dockState, rectImage);
g.DrawIcon(((Form)content).Icon, rectImage);
// Draw the text
if (content == content.DockHandler.Pane.ActiveContent)
{
Rectangle rectText = rectTab;
rectText.X += ImageGapLeft + imageWidth + ImageGapRight + TextGapLeft;
rectText.Width -= ImageGapLeft + imageWidth + ImageGapRight + TextGapLeft;
rectText = GetTransformedRectangle(dockState, rectText);
if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide)
g.DrawString(content.DockHandler.TabText, Font, brushTabText, rectText, StringFormatTabVertical);
else
g.DrawString(content.DockHandler.TabText, Font, brushTabText, rectText, StringFormatTabHorizontal);
}
// Set rotate back
g.Transform = matrixRotate;
OnEndDrawTab(tab);
}
private Rectangle GetLogicalTabStripRectangle(DockState dockState)
{
return GetLogicalTabStripRectangle(dockState, false);
}
private Rectangle GetLogicalTabStripRectangle(DockState dockState, bool transformed)
{
if (!DockHelper.IsDockStateAutoHide(dockState))
return Rectangle.Empty;
int leftPanes = GetPanes(DockState.DockLeftAutoHide).Count;
int rightPanes = GetPanes(DockState.DockRightAutoHide).Count;
int topPanes = GetPanes(DockState.DockTopAutoHide).Count;
int bottomPanes = GetPanes(DockState.DockBottomAutoHide).Count;
int x, y, width, height;
height = MeasureHeight();
if (dockState == DockState.DockLeftAutoHide && leftPanes > 0)
{
x = 0;
y = (topPanes == 0) ? 0 : height;
width = Height - (topPanes == 0 ? 0 : height) - (bottomPanes == 0 ? 0 :height);
}
else if (dockState == DockState.DockRightAutoHide && rightPanes > 0)
{
x = Width - height;
if (leftPanes != 0 && x < height)
x = height;
y = (topPanes == 0) ? 0 : height;
width = Height - (topPanes == 0 ? 0 : height) - (bottomPanes == 0 ? 0 :height);
}
else if (dockState == DockState.DockTopAutoHide && topPanes > 0)
{
x = leftPanes == 0 ? 0 : height;
y = 0;
width = Width - (leftPanes == 0 ? 0 : height) - (rightPanes == 0 ? 0 : height);
}
else if (dockState == DockState.DockBottomAutoHide && bottomPanes > 0)
{
x = leftPanes == 0 ? 0 : height;
y = Height - height;
if (topPanes != 0 && y < height)
y = height;
width = Width - (leftPanes == 0 ? 0 : height) - (rightPanes == 0 ? 0 : height);
}
else
return Rectangle.Empty;
if (width == 0 || height == 0)
{
return Rectangle.Empty;
}
var rect = new Rectangle(x, y, width, height);
return transformed ? GetTransformedRectangle(dockState, rect) : rect;
}
private Rectangle GetTabRectangle(TabVS2003 tab)
{
return GetTabRectangle(tab, false);
}
private Rectangle GetTabRectangle(TabVS2003 tab, bool transformed)
{
DockState dockState = tab.Content.DockHandler.DockState;
Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState);
if (rectTabStrip.IsEmpty)
return Rectangle.Empty;
int x = tab.TabX;
int y = rectTabStrip.Y +
(dockState == DockState.DockTopAutoHide || dockState == DockState.DockRightAutoHide ?
0 : TabGapTop);
int width = tab.TabWidth;
int height = rectTabStrip.Height - TabGapTop;
if (!transformed)
return new Rectangle(x, y, width, height);
else
return GetTransformedRectangle(dockState, new Rectangle(x, y, width, height));
}
private Rectangle GetTransformedRectangle(DockState dockState, Rectangle rect)
{
if (dockState != DockState.DockLeftAutoHide && dockState != DockState.DockRightAutoHide)
return rect;
PointF[] pts = new PointF[1];
// the center of the rectangle
pts[0].X = (float)rect.X + (float)rect.Width / 2;
pts[0].Y = (float)rect.Y + (float)rect.Height / 2;
Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState);
using (Matrix matrix = new Matrix())
{
matrix.RotateAt(90, new PointF((float)rectTabStrip.X + (float)rectTabStrip.Height / 2,
(float)rectTabStrip.Y + (float)rectTabStrip.Height / 2));
matrix.TransformPoints(pts);
}
return new Rectangle((int)(pts[0].X - (float)rect.Height / 2 + .5F),
(int)(pts[0].Y - (float)rect.Width / 2 + .5F),
rect.Height, rect.Width);
}
/// <exclude />
protected override IDockContent HitTest(Point ptMouse)
{
foreach(DockState state in DockStates)
{
Rectangle rectTabStrip = GetLogicalTabStripRectangle(state, true);
if (!rectTabStrip.Contains(ptMouse))
continue;
foreach(Pane pane in GetPanes(state))
{
foreach(TabVS2003 tab in pane.AutoHideTabs)
{
Rectangle rectTab = GetTabRectangle(tab, true);
rectTab.Intersect(rectTabStrip);
if (rectTab.Contains(ptMouse))
return tab.Content;
}
}
}
return null;
}
protected override Rectangle GetTabBounds(Tab tab)
{
return GetTabRectangle((TabVS2003)tab, true);
}
/// <exclude/>
protected override int MeasureHeight()
{
return Math.Max(ImageGapBottom +
ImageGapTop + ImageHeight,
Font.Height) + TabGapTop;
}
/// <exclude/>
protected override void OnRefreshChanges()
{
CalculateTabs();
Invalidate();
}
protected override AutoHideStripBase.Tab CreateTab(IDockContent content)
{
return new TabVS2003(content);
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Method[@name="OnBeginDrawTab(AutoHideTab)"]/*'/>
protected virtual void OnBeginDrawTab(Tab tab)
{
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Method[@name="OnEndDrawTab(AutoHideTab)"]/*'/>
protected virtual void OnEndDrawTab(Tab tab)
{
}
}
}
| |
using System;
using System.Text;
using NUnit.Framework;
using Raksha.Crypto;
using Raksha.Crypto.Parameters;
using Raksha.Security;
using Raksha.Utilities.Encoders;
using Raksha.Tests.Utilities;
namespace Raksha.Tests.Misc
{
/// <remarks>
/// MAC tester - vectors from
/// <a href="http://www.itl.nist.gov/fipspubs/fip81.htm">FIP 81</a> and
/// <a href="http://www.itl.nist.gov/fipspubs/fip113.htm">FIP 113</a>.
/// </remarks>
[TestFixture]
public class MacTest
: SimpleTest
{
private static readonly byte[] keyBytes = Hex.Decode("0123456789abcdef");
private static readonly byte[] ivBytes = Hex.Decode("1234567890abcdef");
private static readonly byte[] input = Hex.Decode("37363534333231204e6f77206973207468652074696d6520666f7220");
private static readonly byte[] output1 = Hex.Decode("f1d30f68");
private static readonly byte[] output2 = Hex.Decode("58d2e77e");
private static readonly byte[] output3 = Hex.Decode("cd647403");
private static readonly byte[] keyBytesISO9797 = Hex.Decode("7CA110454A1A6E570131D9619DC1376E");
private static readonly byte[] inputISO9797 = Encoding.ASCII.GetBytes("Hello World !!!!");
private static readonly byte[] outputISO9797 = Hex.Decode("F09B856213BAB83B");
private static readonly byte[] inputDesEDE64 = Encoding.ASCII.GetBytes("Hello World !!!!");
private static readonly byte[] outputDesEDE64 = Hex.Decode("862304d33af01096");
private void aliasTest(
KeyParameter key,
string primary,
params string[] aliases)
{
IMac mac = MacUtilities.GetMac(primary);
//
// standard DAC - zero IV
//
mac.Init(key);
mac.BlockUpdate(input, 0, input.Length);
byte[] refBytes = new byte[mac.GetMacSize()];
mac.DoFinal(refBytes, 0);
for (int i = 0; i != aliases.Length; i++)
{
mac = MacUtilities.GetMac(aliases[i]);
mac.Init(key);
mac.BlockUpdate(input, 0, input.Length);
byte[] outBytes = new byte[mac.GetMacSize()];
mac.DoFinal(outBytes, 0);
if (!AreEqual(outBytes, refBytes))
{
Fail("Failed - expected "
+ Hex.ToHexString(refBytes) + " got "
+ Hex.ToHexString(outBytes));
}
}
}
public override void PerformTest()
{
KeyParameter key = new DesParameters(keyBytes);
IMac mac = MacUtilities.GetMac("DESMac");
//
// standard DAC - zero IV
//
mac.Init(key);
mac.BlockUpdate(input, 0, input.Length);
//byte[] outBytes = mac.DoFinal();
byte[] outBytes = new byte[mac.GetMacSize()];
mac.DoFinal(outBytes, 0);
if (!AreEqual(outBytes, output1))
{
Fail("Failed - expected "
+ Hex.ToHexString(output1) + " got "
+ Hex.ToHexString(outBytes));
}
//
// mac with IV.
//
mac.Init(new ParametersWithIV(key, ivBytes));
mac.BlockUpdate(input, 0, input.Length);
//outBytes = mac.DoFinal();
outBytes = new byte[mac.GetMacSize()];
mac.DoFinal(outBytes, 0);
if (!AreEqual(outBytes, output2))
{
Fail("Failed - expected "
+ Hex.ToHexString(output2) + " got "
+ Hex.ToHexString(outBytes));
}
//
// CFB mac with IV - 8 bit CFB mode
//
mac = MacUtilities.GetMac("DESMac/CFB8");
mac.Init(new ParametersWithIV(key, ivBytes));
mac.BlockUpdate(input, 0, input.Length);
//outBytes = mac.DoFinal();
outBytes = new byte[mac.GetMacSize()];
mac.DoFinal(outBytes, 0);
if (!AreEqual(outBytes, output3))
{
Fail("Failed - expected "
+ Hex.ToHexString(output3) + " got "
+ Hex.ToHexString(outBytes));
}
//
// ISO9797 algorithm 3 using DESEDE
//
key = new DesEdeParameters(keyBytesISO9797);
mac = MacUtilities.GetMac("ISO9797ALG3");
mac.Init(key);
mac.BlockUpdate(inputISO9797, 0, inputISO9797.Length);
//outBytes = mac.DoFinal();
outBytes = new byte[mac.GetMacSize()];
mac.DoFinal(outBytes, 0);
if (!AreEqual(outBytes, outputISO9797))
{
Fail("Failed - expected "
+ Hex.ToHexString(outputISO9797) + " got "
+ Hex.ToHexString(outBytes));
}
//
// 64bit DESede Mac
//
key = new DesEdeParameters(keyBytesISO9797);
mac = MacUtilities.GetMac("DESEDE64");
mac.Init(key);
mac.BlockUpdate(inputDesEDE64, 0, inputDesEDE64.Length);
//outBytes = mac.DoFinal();
outBytes = new byte[mac.GetMacSize()];
mac.DoFinal(outBytes, 0);
if (!AreEqual(outBytes, outputDesEDE64))
{
Fail("Failed - expected "
+ Hex.ToHexString(outputDesEDE64) + " got "
+ Hex.ToHexString(outBytes));
}
aliasTest(
ParameterUtilities.CreateKeyParameter("DESede", keyBytesISO9797),
"DESedeMac64withISO7816-4Padding",
"DESEDE64WITHISO7816-4PADDING",
"DESEDEISO9797ALG1MACWITHISO7816-4PADDING",
"DESEDEISO9797ALG1WITHISO7816-4PADDING");
aliasTest(
ParameterUtilities.CreateKeyParameter("DESede", keyBytesISO9797),
"ISO9797ALG3WITHISO7816-4PADDING",
"ISO9797ALG3MACWITHISO7816-4PADDING");
}
public override string Name
{
get { return "Mac"; }
}
public static void Main(
string[] args)
{
RunTest(new MacTest());
}
[Test]
public void TestFunction()
{
string resultText = Perform().ToString();
Assert.AreEqual(Name + ": Okay", resultText);
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.DataFactories.Common.Models;
using Microsoft.Azure.Management.DataFactories.Core;
namespace Microsoft.Azure.Management.DataFactories.Core
{
public partial class DataFactoryManagementClient : ServiceClient<DataFactoryManagementClient>, IDataFactoryManagementClient
{
private Uri _baseUri;
/// <summary>
/// The URI used as the base for all Service Management requests.
/// </summary>
public Uri BaseUri
{
get { return this._baseUri; }
set { this._baseUri = value; }
}
private SubscriptionCloudCredentials _credentials;
/// <summary>
/// When you create a Windows Azure subscription, it is uniquely
/// identified by a subscription ID. The subscription ID forms part of
/// the URI for every call that you make to the Service Management
/// API. The Windows Azure Service ManagementAPI use mutual
/// authentication of management certificates over SSL to ensure that
/// a request made to the service is secure. No anonymous requests are
/// allowed.
/// </summary>
public SubscriptionCloudCredentials Credentials
{
get { return this._credentials; }
set { this._credentials = value; }
}
private int _longRunningOperationInitialTimeout;
/// <summary>
/// Gets or sets the initial timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationInitialTimeout
{
get { return this._longRunningOperationInitialTimeout; }
set { this._longRunningOperationInitialTimeout = value; }
}
private int _longRunningOperationRetryTimeout;
/// <summary>
/// Gets or sets the retry timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationRetryTimeout
{
get { return this._longRunningOperationRetryTimeout; }
set { this._longRunningOperationRetryTimeout = value; }
}
private IActivityTypeOperations _activityTypes;
/// <summary>
/// Operations for managing data factory ActivityTypes.
/// </summary>
public virtual IActivityTypeOperations ActivityTypes
{
get { return this._activityTypes; }
}
private IComputeTypeOperations _computeTypes;
/// <summary>
/// Operations for managing data factory ComputeTypes.
/// </summary>
public virtual IComputeTypeOperations ComputeTypes
{
get { return this._computeTypes; }
}
private IDataFactoryOperations _dataFactories;
/// <summary>
/// Operations for managing data factories.
/// </summary>
public virtual IDataFactoryOperations DataFactories
{
get { return this._dataFactories; }
}
private IDataSliceOperations _dataSlices;
/// <summary>
/// Operations for managing data slices.
/// </summary>
public virtual IDataSliceOperations DataSlices
{
get { return this._dataSlices; }
}
private IDataSliceRunOperations _dataSliceRuns;
/// <summary>
/// Operations for managing data slice runs.
/// </summary>
public virtual IDataSliceRunOperations DataSliceRuns
{
get { return this._dataSliceRuns; }
}
private IGatewayOperations _gateways;
/// <summary>
/// Operations for managing data factory gateways.
/// </summary>
public virtual IGatewayOperations Gateways
{
get { return this._gateways; }
}
private IHubOperations _hubs;
/// <summary>
/// Operations for managing hubs.
/// </summary>
public virtual IHubOperations Hubs
{
get { return this._hubs; }
}
private ILinkedServiceOperations _linkedServices;
/// <summary>
/// Operations for managing data factory internal linkedServices.
/// </summary>
public virtual ILinkedServiceOperations LinkedServices
{
get { return this._linkedServices; }
}
private IPipelineOperations _pipelines;
/// <summary>
/// Operations for managing pipelines.
/// </summary>
public virtual IPipelineOperations Pipelines
{
get { return this._pipelines; }
}
private ITableOperations _tables;
/// <summary>
/// Operations for managing tables.
/// </summary>
public virtual ITableOperations Tables
{
get { return this._tables; }
}
/// <summary>
/// Initializes a new instance of the DataFactoryManagementClient class.
/// </summary>
public DataFactoryManagementClient()
: base()
{
this._activityTypes = new ActivityTypeOperations(this);
this._computeTypes = new ComputeTypeOperations(this);
this._dataFactories = new DataFactoryOperations(this);
this._dataSlices = new DataSliceOperations(this);
this._dataSliceRuns = new DataSliceRunOperations(this);
this._gateways = new GatewayOperations(this);
this._hubs = new HubOperations(this);
this._linkedServices = new LinkedServiceOperations(this);
this._pipelines = new PipelineOperations(this);
this._tables = new TableOperations(this);
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(60);
}
/// <summary>
/// Initializes a new instance of the DataFactoryManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. When you create a Windows Azure subscription, it is
/// uniquely identified by a subscription ID. The subscription ID
/// forms part of the URI for every call that you make to the Service
/// Management API. The Windows Azure Service ManagementAPI use mutual
/// authentication of management certificates over SSL to ensure that
/// a request made to the service is secure. No anonymous requests are
/// allowed.
/// </param>
/// <param name='baseUri'>
/// Optional. The URI used as the base for all Service Management
/// requests.
/// </param>
public DataFactoryManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the DataFactoryManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. When you create a Windows Azure subscription, it is
/// uniquely identified by a subscription ID. The subscription ID
/// forms part of the URI for every call that you make to the Service
/// Management API. The Windows Azure Service ManagementAPI use mutual
/// authentication of management certificates over SSL to ensure that
/// a request made to the service is secure. No anonymous requests are
/// allowed.
/// </param>
public DataFactoryManagementClient(SubscriptionCloudCredentials credentials)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.azure.com");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the DataFactoryManagementClient class.
/// </summary>
/// <param name='httpClient'>
/// The Http client
/// </param>
public DataFactoryManagementClient(HttpClient httpClient)
: base(httpClient)
{
this._activityTypes = new ActivityTypeOperations(this);
this._computeTypes = new ComputeTypeOperations(this);
this._dataFactories = new DataFactoryOperations(this);
this._dataSlices = new DataSliceOperations(this);
this._dataSliceRuns = new DataSliceRunOperations(this);
this._gateways = new GatewayOperations(this);
this._hubs = new HubOperations(this);
this._linkedServices = new LinkedServiceOperations(this);
this._pipelines = new PipelineOperations(this);
this._tables = new TableOperations(this);
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(60);
}
/// <summary>
/// Initializes a new instance of the DataFactoryManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. When you create a Windows Azure subscription, it is
/// uniquely identified by a subscription ID. The subscription ID
/// forms part of the URI for every call that you make to the Service
/// Management API. The Windows Azure Service ManagementAPI use mutual
/// authentication of management certificates over SSL to ensure that
/// a request made to the service is secure. No anonymous requests are
/// allowed.
/// </param>
/// <param name='baseUri'>
/// Optional. The URI used as the base for all Service Management
/// requests.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public DataFactoryManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the DataFactoryManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. When you create a Windows Azure subscription, it is
/// uniquely identified by a subscription ID. The subscription ID
/// forms part of the URI for every call that you make to the Service
/// Management API. The Windows Azure Service ManagementAPI use mutual
/// authentication of management certificates over SSL to ensure that
/// a request made to the service is secure. No anonymous requests are
/// allowed.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public DataFactoryManagementClient(SubscriptionCloudCredentials credentials, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.azure.com");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Clones properties from current instance to another
/// DataFactoryManagementClient instance
/// </summary>
/// <param name='client'>
/// Instance of DataFactoryManagementClient to clone to
/// </param>
protected override void Clone(ServiceClient<DataFactoryManagementClient> client)
{
base.Clone(client);
if (client is DataFactoryManagementClient)
{
DataFactoryManagementClient clonedClient = ((DataFactoryManagementClient)client);
clonedClient._credentials = this._credentials;
clonedClient._baseUri = this._baseUri;
clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout;
clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout;
clonedClient.Credentials.InitializeServiceClient(clonedClient);
}
}
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public async Task<LongRunningOperationResponse> GetLongRunningOperationStatusAsync(string operationStatusLink, CancellationToken cancellationToken)
{
// Validate
if (operationStatusLink == null)
{
throw new ArgumentNullException("operationStatusLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("operationStatusLink", operationStatusLink);
TracingAdapter.Enter(invocationId, this, "GetLongRunningOperationStatusAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + operationStatusLink;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2015-09-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted && statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
LongRunningOperationResponse result = null;
// Deserialize Response
result = new LongRunningOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (statusCode == HttpStatusCode.Conflict)
{
result.Status = OperationStatus.Failed;
}
if (statusCode == HttpStatusCode.OK)
{
result.Status = OperationStatus.Succeeded;
}
if (statusCode == HttpStatusCode.NoContent)
{
result.Status = OperationStatus.Succeeded;
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using OpenMetaverse;
namespace OpenSim.Framework
{
/// <summary>
/// Sandbox mode region comms listener. There is one of these per region
/// </summary>
public class RegionCommsListener : IRegionCommsListener
{
public string debugRegionName = String.Empty;
private AcknowledgeAgentCross handlerAcknowledgeAgentCrossed = null; // OnAcknowledgeAgentCrossed;
private AcknowledgePrimCross handlerAcknowledgePrimCrossed = null; // OnAcknowledgePrimCrossed;
private AgentCrossing handlerAvatarCrossingIntoRegion = null; // OnAvatarCrossingIntoRegion;
private ChildAgentUpdate handlerChildAgentUpdate = null; // OnChildAgentUpdate;
private CloseAgentConnection handlerCloseAgentConnection = null; // OnCloseAgentConnection;
private GenericCall2 handlerExpectChildAgent = null; // OnExpectChildAgent;
private ExpectUserDelegate handlerExpectUser = null; // OnExpectUser
private UpdateNeighbours handlerNeighboursUpdate = null; // OnNeighboursUpdate;
// private PrimCrossing handlerPrimCrossingIntoRegion = null; // OnPrimCrossingIntoRegion;
private LogOffUser handlerLogOffUser = null;
private GetLandData handlerGetLandData = null;
#region IRegionCommsListener Members
public event ExpectUserDelegate OnExpectUser;
public event GenericCall2 OnExpectChildAgent;
public event AgentCrossing OnAvatarCrossingIntoRegion;
public event PrimCrossing OnPrimCrossingIntoRegion;
public event UpdateNeighbours OnNeighboursUpdate;
public event AcknowledgeAgentCross OnAcknowledgeAgentCrossed;
public event AcknowledgePrimCross OnAcknowledgePrimCrossed;
public event CloseAgentConnection OnCloseAgentConnection;
public event ChildAgentUpdate OnChildAgentUpdate;
public event LogOffUser OnLogOffUser;
public event GetLandData OnGetLandData;
#endregion
/// <summary>
///
/// </summary>
/// <param name="agent"></param>
/// <returns></returns>
public virtual bool TriggerExpectUser(AgentCircuitData agent)
{
handlerExpectUser = OnExpectUser;
if (handlerExpectUser != null)
{
handlerExpectUser(agent);
return true;
}
return false;
}
// From User Server
public virtual void TriggerLogOffUser(UUID agentID, UUID RegionSecret, string message)
{
handlerLogOffUser = OnLogOffUser;
if (handlerLogOffUser != null)
{
handlerLogOffUser(agentID, RegionSecret, message);
}
}
public virtual bool TriggerChildAgentUpdate(ChildAgentDataUpdate cAgentData)
{
handlerChildAgentUpdate = OnChildAgentUpdate;
if (handlerChildAgentUpdate != null)
{
handlerChildAgentUpdate(cAgentData);
return true;
}
return false;
}
public virtual bool TriggerExpectAvatarCrossing(UUID agentID, Vector3 position, bool isFlying)
{
handlerAvatarCrossingIntoRegion = OnAvatarCrossingIntoRegion;
if (handlerAvatarCrossingIntoRegion != null)
{
handlerAvatarCrossingIntoRegion(agentID, position, isFlying);
return true;
}
return false;
}
public virtual bool TriggerAcknowledgeAgentCrossed(UUID agentID)
{
handlerAcknowledgeAgentCrossed = OnAcknowledgeAgentCrossed;
if (handlerAcknowledgeAgentCrossed != null)
{
handlerAcknowledgeAgentCrossed(agentID);
return true;
}
return false;
}
public virtual bool TriggerAcknowledgePrimCrossed(UUID primID)
{
handlerAcknowledgePrimCrossed = OnAcknowledgePrimCrossed;
if (handlerAcknowledgePrimCrossed != null)
{
handlerAcknowledgePrimCrossed(primID);
return true;
}
return false;
}
public virtual bool TriggerCloseAgentConnection(UUID agentID)
{
handlerCloseAgentConnection = OnCloseAgentConnection;
if (handlerCloseAgentConnection != null)
{
handlerCloseAgentConnection(agentID);
return true;
}
return false;
}
/// <summary>
///
/// </summary>
/// <remarks>TODO: Doesnt take any args??</remarks>
/// <returns></returns>
public virtual bool TriggerExpectChildAgent()
{
handlerExpectChildAgent = OnExpectChildAgent;
if (handlerExpectChildAgent != null)
{
handlerExpectChildAgent();
return true;
}
return false;
}
/// <summary>
///
/// </summary>
/// <remarks>Added to avoid a unused compiler warning on OnNeighboursUpdate, TODO: Check me</remarks>
/// <param name="neighbours"></param>
/// <returns></returns>
public virtual bool TriggerOnNeighboursUpdate(List<RegionInfo> neighbours)
{
handlerNeighboursUpdate = OnNeighboursUpdate;
if (handlerNeighboursUpdate != null)
{
handlerNeighboursUpdate(neighbours);
return true;
}
return false;
}
public bool TriggerTellRegionToCloseChildConnection(UUID agentID)
{
handlerCloseAgentConnection = OnCloseAgentConnection;
if (handlerCloseAgentConnection != null)
return handlerCloseAgentConnection(agentID);
return false;
}
public LandData TriggerGetLandData(uint x, uint y)
{
handlerGetLandData = OnGetLandData;
if (handlerGetLandData != null)
return handlerGetLandData(x, y);
return null;
}
}
}
| |
namespace StripeTests
{
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Stripe;
using Xunit;
public class InvoiceServiceTest : BaseStripeTest
{
private const string InvoiceId = "in_123";
private readonly InvoiceService service;
private readonly InvoiceCreateOptions createOptions;
private readonly InvoiceUpdateOptions updateOptions;
private readonly InvoicePayOptions payOptions;
private readonly InvoiceListOptions listOptions;
private readonly InvoiceListLineItemsOptions listLineItemsOptions;
private readonly UpcomingInvoiceOptions upcomingOptions;
private readonly UpcomingInvoiceListLineItemsOptions upcomingListLineItemsOptions;
private readonly InvoiceFinalizeOptions finalizeOptions;
private readonly InvoiceMarkUncollectibleOptions markUncollectibleOptions;
private readonly InvoiceSendOptions sendOptions;
private readonly InvoiceVoidOptions voidOptions;
public InvoiceServiceTest(
StripeMockFixture stripeMockFixture,
MockHttpClientFixture mockHttpClientFixture)
: base(stripeMockFixture, mockHttpClientFixture)
{
this.service = new InvoiceService(this.StripeClient);
this.createOptions = new InvoiceCreateOptions
{
Customer = "cus_123",
};
this.updateOptions = new InvoiceUpdateOptions
{
Metadata = new Dictionary<string, string>
{
{ "key", "value" },
},
};
this.payOptions = new InvoicePayOptions
{
Forgive = true,
Source = "src_123",
};
this.listOptions = new InvoiceListOptions
{
Limit = 1,
};
this.listLineItemsOptions = new InvoiceListLineItemsOptions
{
Limit = 1,
};
this.upcomingOptions = new UpcomingInvoiceOptions
{
Customer = "cus_123",
Subscription = "sub_123",
};
this.upcomingListLineItemsOptions = new UpcomingInvoiceListLineItemsOptions
{
Limit = 1,
Customer = "cus_123",
Subscription = "sub_123",
};
this.finalizeOptions = new InvoiceFinalizeOptions
{
};
this.markUncollectibleOptions = new InvoiceMarkUncollectibleOptions
{
};
this.sendOptions = new InvoiceSendOptions
{
};
this.voidOptions = new InvoiceVoidOptions
{
};
}
[Fact]
public void Create()
{
var invoice = this.service.Create(this.createOptions);
this.AssertRequest(HttpMethod.Post, "/v1/invoices");
Assert.NotNull(invoice);
Assert.Equal("invoice", invoice.Object);
}
[Fact]
public async Task CreateAsync()
{
var invoice = await this.service.CreateAsync(this.createOptions);
this.AssertRequest(HttpMethod.Post, "/v1/invoices");
Assert.NotNull(invoice);
Assert.Equal("invoice", invoice.Object);
}
[Fact]
public void Delete()
{
var invoice = this.service.Delete(InvoiceId);
this.AssertRequest(HttpMethod.Delete, "/v1/invoices/in_123");
Assert.NotNull(invoice);
Assert.Equal("invoice", invoice.Object);
}
[Fact]
public async Task DeleteAsync()
{
var invoice = await this.service.DeleteAsync(InvoiceId);
this.AssertRequest(HttpMethod.Delete, "/v1/invoices/in_123");
Assert.NotNull(invoice);
Assert.Equal("invoice", invoice.Object);
}
[Fact]
public void FinalizeInvoice()
{
var invoice = this.service.FinalizeInvoice(InvoiceId, this.finalizeOptions);
this.AssertRequest(HttpMethod.Post, "/v1/invoices/in_123/finalize");
Assert.NotNull(invoice);
Assert.Equal("invoice", invoice.Object);
}
[Fact]
public async Task FinalizeInvoiceAsync()
{
var invoice = await this.service.FinalizeInvoiceAsync(InvoiceId, this.finalizeOptions);
this.AssertRequest(HttpMethod.Post, "/v1/invoices/in_123/finalize");
Assert.NotNull(invoice);
Assert.Equal("invoice", invoice.Object);
}
[Fact]
public void Get()
{
var invoice = this.service.Get(InvoiceId);
this.AssertRequest(HttpMethod.Get, "/v1/invoices/in_123");
Assert.NotNull(invoice);
Assert.Equal("invoice", invoice.Object);
}
[Fact]
public async Task GetAsync()
{
var invoice = await this.service.GetAsync(InvoiceId);
this.AssertRequest(HttpMethod.Get, "/v1/invoices/in_123");
Assert.NotNull(invoice);
Assert.Equal("invoice", invoice.Object);
}
[Fact]
public void List()
{
var invoices = this.service.List(this.listOptions);
this.AssertRequest(HttpMethod.Get, "/v1/invoices");
Assert.NotNull(invoices);
Assert.Equal("list", invoices.Object);
Assert.Single(invoices.Data);
Assert.Equal("invoice", invoices.Data[0].Object);
}
[Fact]
public async Task ListAsync()
{
var invoices = await this.service.ListAsync(this.listOptions);
this.AssertRequest(HttpMethod.Get, "/v1/invoices");
Assert.NotNull(invoices);
Assert.Equal("list", invoices.Object);
Assert.Single(invoices.Data);
Assert.Equal("invoice", invoices.Data[0].Object);
}
[Fact]
public void ListAutoPaging()
{
var invoice = this.service.ListAutoPaging(this.listOptions).First();
Assert.NotNull(invoice);
Assert.Equal("invoice", invoice.Object);
}
[Fact]
public async Task ListAutoPagingAsync()
{
var invoice = await this.service.ListAutoPagingAsync(this.listOptions).FirstAsync();
Assert.NotNull(invoice);
Assert.Equal("invoice", invoice.Object);
}
[Fact]
public void ListLineItems()
{
var lineItems = this.service.ListLineItems(InvoiceId, this.listLineItemsOptions);
this.AssertRequest(HttpMethod.Get, "/v1/invoices/in_123/lines");
Assert.NotNull(lineItems);
Assert.Equal("list", lineItems.Object);
Assert.Single(lineItems.Data);
Assert.Equal("line_item", lineItems.Data[0].Object);
}
[Fact]
public async Task ListLineItemsAsync()
{
var lineItems = await this.service.ListLineItemsAsync(InvoiceId, this.listLineItemsOptions);
this.AssertRequest(HttpMethod.Get, "/v1/invoices/in_123/lines");
Assert.NotNull(lineItems);
Assert.Equal("list", lineItems.Object);
Assert.Single(lineItems.Data);
Assert.Equal("line_item", lineItems.Data[0].Object);
}
[Fact]
public void ListLineItemsAutoPaging()
{
var lineItem = this.service.ListLineItemsAutoPaging(InvoiceId, this.listLineItemsOptions).First();
Assert.NotNull(lineItem);
Assert.Equal("line_item", lineItem.Object);
}
[Fact]
public async Task ListLineItemsAutoPagingAsync()
{
var lineItem = await this.service.ListLineItemsAutoPagingAsync(InvoiceId, this.listLineItemsOptions).FirstAsync();
Assert.NotNull(lineItem);
Assert.Equal("line_item", lineItem.Object);
}
[Fact]
public void ListUpcomingLineItems()
{
var lineItems = this.service.ListUpcomingLineItems(this.upcomingListLineItemsOptions);
this.AssertRequest(HttpMethod.Get, "/v1/invoices/upcoming/lines");
Assert.NotNull(lineItems);
Assert.Equal("list", lineItems.Object);
Assert.Single(lineItems.Data);
Assert.Equal("line_item", lineItems.Data[0].Object);
}
[Fact]
public async Task ListUpcomingLineItemsAsync()
{
var lineItems = await this.service.ListUpcomingLineItemsAsync(this.upcomingListLineItemsOptions);
this.AssertRequest(HttpMethod.Get, "/v1/invoices/upcoming/lines");
Assert.NotNull(lineItems);
Assert.Equal("list", lineItems.Object);
Assert.Single(lineItems.Data);
Assert.Equal("line_item", lineItems.Data[0].Object);
}
[Fact]
public void ListUpcomingLineItemsAutoPaging()
{
var lineItem = this.service.ListUpcomingLineItemsAutoPaging(this.upcomingListLineItemsOptions).First();
Assert.NotNull(lineItem);
Assert.Equal("line_item", lineItem.Object);
}
[Fact]
public async Task ListUpcomingLineItemsAutoPagingAsync()
{
var lineItem = await this.service.ListUpcomingLineItemsAutoPagingAsync(this.upcomingListLineItemsOptions).FirstAsync();
Assert.NotNull(lineItem);
Assert.Equal("line_item", lineItem.Object);
}
[Fact]
public void MarkUncollectible()
{
var invoice = this.service.MarkUncollectible(InvoiceId, this.markUncollectibleOptions);
this.AssertRequest(HttpMethod.Post, "/v1/invoices/in_123/mark_uncollectible");
Assert.NotNull(invoice);
Assert.Equal("invoice", invoice.Object);
}
[Fact]
public async Task MarkUncollectibleAsync()
{
var invoice = await this.service.MarkUncollectibleAsync(InvoiceId, this.markUncollectibleOptions);
this.AssertRequest(HttpMethod.Post, "/v1/invoices/in_123/mark_uncollectible");
Assert.NotNull(invoice);
Assert.Equal("invoice", invoice.Object);
}
[Fact]
public void Pay()
{
var invoice = this.service.Pay(InvoiceId, this.payOptions);
this.AssertRequest(HttpMethod.Post, "/v1/invoices/in_123/pay");
Assert.NotNull(invoice);
Assert.Equal("invoice", invoice.Object);
}
[Fact]
public async Task PayAsync()
{
var invoice = await this.service.PayAsync(InvoiceId, this.payOptions);
this.AssertRequest(HttpMethod.Post, "/v1/invoices/in_123/pay");
Assert.NotNull(invoice);
Assert.Equal("invoice", invoice.Object);
}
[Fact]
public void SendInvoice()
{
var invoice = this.service.SendInvoice(InvoiceId, this.sendOptions);
this.AssertRequest(HttpMethod.Post, "/v1/invoices/in_123/send");
Assert.NotNull(invoice);
Assert.Equal("invoice", invoice.Object);
}
[Fact]
public async Task SendInvoiceAsync()
{
var invoice = await this.service.SendInvoiceAsync(InvoiceId, this.sendOptions);
this.AssertRequest(HttpMethod.Post, "/v1/invoices/in_123/send");
Assert.NotNull(invoice);
Assert.Equal("invoice", invoice.Object);
}
[Fact]
public void Upcoming()
{
var invoice = this.service.Upcoming(this.upcomingOptions);
this.AssertRequest(HttpMethod.Get, "/v1/invoices/upcoming");
Assert.NotNull(invoice);
Assert.Equal("invoice", invoice.Object);
}
[Fact]
public async Task UpcomingAsync()
{
var invoice = await this.service.UpcomingAsync(this.upcomingOptions);
this.AssertRequest(HttpMethod.Get, "/v1/invoices/upcoming");
Assert.NotNull(invoice);
Assert.Equal("invoice", invoice.Object);
}
[Fact]
public void Update()
{
var invoice = this.service.Update(InvoiceId, this.updateOptions);
this.AssertRequest(HttpMethod.Post, "/v1/invoices/in_123");
Assert.NotNull(invoice);
Assert.Equal("invoice", invoice.Object);
}
[Fact]
public async Task UpdateAsync()
{
var invoice = await this.service.UpdateAsync(InvoiceId, this.updateOptions);
this.AssertRequest(HttpMethod.Post, "/v1/invoices/in_123");
Assert.NotNull(invoice);
Assert.Equal("invoice", invoice.Object);
}
[Fact]
public void VoidInvoice()
{
var invoice = this.service.VoidInvoice(InvoiceId, this.voidOptions);
this.AssertRequest(HttpMethod.Post, "/v1/invoices/in_123/void");
Assert.NotNull(invoice);
Assert.Equal("invoice", invoice.Object);
}
[Fact]
public async Task VoidInvoiceAsync()
{
var invoice = await this.service.VoidInvoiceAsync(InvoiceId, this.voidOptions);
this.AssertRequest(HttpMethod.Post, "/v1/invoices/in_123/void");
Assert.NotNull(invoice);
Assert.Equal("invoice", invoice.Object);
}
}
}
| |
//#define NoTagPenalty //Enables or disables tag penalties. Can give small performance boost
#if UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_3_5 || UNITY_3_4 || UNITY_3_3
#define UNITY_LE_4_3
#endif
#if !UNITY_3_5 && !UNITY_3_4 && !UNITY_3_3
#define UNITY_4
#endif
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using Pathfinding;
[CustomEditor(typeof(Seeker))]
[RequireComponent(typeof(CharacterController))]
[RequireComponent(typeof(Seeker))]
public class SeekerEditor : Editor {
public static bool modifiersOpen = false;
public static bool tagPenaltiesOpen = false;
List<IPathModifier> mods = null;
public override void OnInspectorGUI () {
DrawDefaultInspector ();
Seeker script = target as Seeker;
#if !UNITY_LE_4_3
Undo.RecordObject ( script, "modify settings on Seeker");
#endif
EditorGUILayoutx.SetTagField (new GUIContent ("Valid Tags"),ref script.traversableTags);
EditorGUI.indentLevel=0;
tagPenaltiesOpen = EditorGUILayout.Foldout (tagPenaltiesOpen,new GUIContent ("Tag Penalties","Penalties for each tag"));
if (tagPenaltiesOpen) {
EditorGUI.indentLevel=2;
string[] tagNames = AstarPath.FindTagNames ();
for (int i=0;i<script.tagPenalties.Length;i++) {
int tmp = EditorGUILayout.IntField ((i < tagNames.Length ? tagNames[i] : "Tag "+i),(int)script.tagPenalties[i]);
if (tmp < 0) tmp = 0;
script.tagPenalties[i] = tmp;
}
if (GUILayout.Button ("Edit Tag Names...")) {
AstarPathEditor.EditTags ();
}
}
EditorGUI.indentLevel=1;
//Do some loading and checking
if (!AstarPathEditor.stylesLoaded) {
if (!AstarPathEditor.LoadStyles ()) {
if (AstarPathEditor.upArrow == null) {
AstarPathEditor.upArrow = GUI.skin.FindStyle ("Button");
AstarPathEditor.downArrow = AstarPathEditor.upArrow;
}
} else {
AstarPathEditor.stylesLoaded = true;
}
}
GUIStyle helpBox = GUI.skin.GetStyle ("helpBox");
if (mods == null) {
mods = new List<IPathModifier>(script.GetComponents<MonoModifier>() as IPathModifier[]);
} else {
mods.Clear ();
mods.AddRange (script.GetComponents<MonoModifier>() as IPathModifier[]);
}
mods.Add (script.startEndModifier as IPathModifier);
bool changed = true;
while (changed) {
changed = false;
for (int i=0;i<mods.Count-1;i++) {
if (mods[i].Priority < mods[i+1].Priority) {
IPathModifier tmp = mods[i+1];
mods[i+1] = mods[i];
mods[i] = tmp;
changed = true;
}
}
}
for (int i=0;i<mods.Count;i++) {
if (mods.Count-i != mods[i].Priority) {
mods[i].Priority = mods.Count-i;
GUI.changed = true;
EditorUtility.SetDirty (target);
}
}
bool modifierErrors = false;
IPathModifier prevMod = mods[0];
//Loops through all modifiers and checks if there are any errors in converting output between modifiers
for (int i=1;i<mods.Count;i++) {
MonoModifier monoMod = mods[i] as MonoModifier;
if ((prevMod as MonoModifier) != null && !(prevMod as MonoModifier).enabled) {
if (monoMod == null || monoMod.enabled) prevMod = mods[i];
continue;
}
if ((monoMod == null || monoMod.enabled) && prevMod != mods[i] && !ModifierConverter.CanConvert (prevMod.output, mods[i].input)) {
modifierErrors = true;
}
if (monoMod == null || monoMod.enabled) {
prevMod = mods[i];
}
}
EditorGUI.indentLevel = 0;
#if UNITY_LE_4_3
modifiersOpen = EditorGUILayout.Foldout (modifiersOpen, "Modifiers Priorities"+(modifierErrors ? " - Errors in modifiers!" : ""),EditorStyles.foldout);
#else
modifiersOpen = EditorGUILayout.Foldout (modifiersOpen, "Modifiers Priorities"+(modifierErrors ? " - Errors in modifiers!" : ""));
#endif
#if UNITY_LE_4_3
EditorGUI.indentLevel = 1;
#endif
if (modifiersOpen) {
#if UNITY_LE_4_3
EditorGUI.indentLevel+= 2;
#endif
//GUILayout.BeginHorizontal ();
//GUILayout.Space (28);
if (GUILayout.Button ("Modifiers attached to this gameObject are listed here.\nModifiers with a higher priority (higher up in the list) will be executed first.\nClick here for more info",helpBox)) {
Application.OpenURL (AstarPathEditor.GetURL ("modifiers"));
}
EditorGUILayout.HelpBox ("Original or All can be converted to anything\n" +
"NodePath can be converted to VectorPath\n"+
"VectorPath can only be used as VectorPath\n"+
"Vector takes both VectorPath and StrictVectorPath\n"+
"Strict... can be converted to the non-strict variant", MessageType.None );
//GUILayout.EndHorizontal ();
prevMod = mods[0];
for (int i=0;i<mods.Count;i++) {
//EditorGUILayout.LabelField (mods[i].GetType ().ToString (),mods[i].Priority.ToString ());
MonoModifier monoMod = mods[i] as MonoModifier;
Color prevCol = GUI.color;
if (monoMod != null && !monoMod.enabled) {
GUI.color *= new Color (1,1,1,0.5F);
}
GUILayout.BeginVertical (GUI.skin.box);
if (i > 0) {
if ((prevMod as MonoModifier) != null && !(prevMod as MonoModifier).enabled) {
prevMod = mods[i];
} else {
if ((monoMod == null || monoMod.enabled) && !ModifierConverter.CanConvert (prevMod.output, mods[i].input)) {
//GUILayout.BeginHorizontal ();
//GUILayout.Space (28);
GUIUtilityx.SetColor (new Color (0.8F,0,0));
GUILayout.Label ("Cannot convert "+prevMod.GetType ().Name+"'s output to "+mods[i].GetType ().Name+"'s input\nRearranging the modifiers might help",EditorStyles.whiteMiniLabel);
GUIUtilityx.ResetColor ();
//GUILayout.EndHorizontal ();
}
if (monoMod == null || monoMod.enabled) {
prevMod = mods[i];
}
}
}
GUILayout.Label ("Input: "+mods[i].input,EditorStyles.wordWrappedMiniLabel);
int newPrio = EditorGUILayoutx.UpDownArrows (new GUIContent (ObjectNames.NicifyVariableName (mods[i].GetType ().ToString ())),mods[i].Priority, EditorStyles.label, AstarPathEditor.upArrow,AstarPathEditor.downArrow);
GUILayout.Label ("Output: "+mods[i].output,EditorStyles.wordWrappedMiniLabel);
GUILayout.EndVertical ();
int diff = newPrio - mods[i].Priority;
if (i > 0 && diff > 0) {
mods[i-1].Priority = mods[i].Priority;
} else if (i < mods.Count-1 && diff < 0) {
mods[i+1].Priority = mods[i].Priority;
}
mods[i].Priority = newPrio;
GUI.color = prevCol;
}
#if UNITY_LE_4_3
EditorGUI.indentLevel-= 2;
#endif
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
using NPOI.SS.UserModel;
using NPOI.OpenXmlFormats.Spreadsheet;
namespace NPOI.XSSF.UserModel
{
/**
* @author Yegor Kozlov
*/
public class XSSFBorderFormatting : IBorderFormatting
{
CT_Border _border;
/*package*/
internal XSSFBorderFormatting(CT_Border border)
{
_border = border;
}
#region IBorderFormatting Members
public BorderStyle BorderBottom
{
get
{
if (!_border.IsSetBottom())
{
return BorderStyle.None;
}
else
{
return (BorderStyle)_border.bottom.style;
}
}
set
{
CT_BorderPr pr = _border.IsSetBottom() ? _border.bottom : _border.AddNewBottom();
if (value == BorderStyle.None) _border.UnsetBottom();
else pr.style = (ST_BorderStyle)value;
}
}
public BorderStyle BorderDiagonal
{
get
{
if (!_border.IsSetDiagonal())
{
return BorderStyle.None;
}
else
{
return (BorderStyle)_border.diagonal.style;
}
}
set
{
CT_BorderPr pr = _border.IsSetDiagonal() ? _border.diagonal : _border.AddNewDiagonal();
if (value == (short)BorderStyle.None) _border.unsetDiagonal();
else pr.style = (ST_BorderStyle)(value + 1);
}
}
public BorderStyle BorderLeft
{
get
{
if (!_border.IsSetLeft())
{
return BorderStyle.None;
}
else
{
return (BorderStyle)_border.left.style;
}
}
set
{
CT_BorderPr pr = _border.IsSetLeft() ? _border.left : _border.AddNewLeft();
if (value == (short)BorderStyle.None) _border.unsetLeft();
else pr.style = (ST_BorderStyle)(value);
}
}
public BorderStyle BorderRight
{
get
{
if (!_border.IsSetRight())
{
return BorderStyle.None;
}
else
{
return (BorderStyle)_border.right.style;
}
}
set
{
CT_BorderPr pr = _border.IsSetRight() ? _border.right : _border.AddNewRight();
if (value == (short)BorderStyle.None) _border.unsetRight();
else pr.style = (ST_BorderStyle)(value );
}
}
public BorderStyle BorderTop
{
get
{
if (!_border.IsSetTop())
{
return BorderStyle.None;
}
else
{
return (BorderStyle)_border.top.style;
}
}
set
{
CT_BorderPr pr = _border.IsSetTop() ? _border.top : _border.AddNewTop();
if (value == (short)BorderStyle.None) _border.unsetTop();
else pr.style = (ST_BorderStyle)(value );
}
}
public short BottomBorderColor
{
get
{
if (!_border.IsSetBottom()) return 0;
CT_BorderPr pr = _border.bottom;
return pr.color.indexedSpecified ? (short)pr.color.indexed : (short)0;
}
set
{
CT_BorderPr pr = _border.IsSetBottom() ? _border.bottom : _border.AddNewBottom();
CT_Color ctColor = new CT_Color();
ctColor.indexed = (uint)value;
ctColor.indexedSpecified = true;
pr.color = (ctColor);
}
}
public short DiagonalBorderColor
{
get
{
if (!_border.IsSetDiagonal()) return 0;
CT_BorderPr pr = _border.diagonal;
return pr.color.indexedSpecified ? (short)pr.color.indexed : (short)0;
}
set
{
CT_BorderPr pr = _border.IsSetDiagonal() ? _border.diagonal : _border.AddNewDiagonal();
CT_Color ctColor = new CT_Color();
ctColor.indexed = (uint)value;
ctColor.indexedSpecified = true;
pr.color = (ctColor);
}
}
public short LeftBorderColor
{
get
{
if (!_border.IsSetLeft()) return 0;
CT_BorderPr pr = _border.left;
return pr.color.indexedSpecified ? (short)pr.color.indexed : (short)0;
}
set
{
CT_BorderPr pr = _border.IsSetLeft() ? _border.left : _border.AddNewLeft();
CT_Color ctColor = new CT_Color();
ctColor.indexed = (uint)value;
ctColor.indexedSpecified = true;
pr.color = (ctColor);
}
}
public short RightBorderColor
{
get
{
if (!_border.IsSetRight()) return 0;
CT_BorderPr pr = _border.right;
return pr.color.indexedSpecified ? (short)pr.color.indexed : (short)0;
}
set
{
CT_BorderPr pr = _border.IsSetRight() ? _border.right : _border.AddNewRight();
CT_Color ctColor = new CT_Color();
ctColor.indexed = (uint)(value);
ctColor.indexedSpecified = true;
pr.color = (ctColor);
}
}
public short TopBorderColor
{
get
{
if (!_border.IsSetTop()) return 0;
CT_BorderPr pr = _border.top;
return pr.color.indexedSpecified ? (short)pr.color.indexed : (short)0;
}
set
{
CT_BorderPr pr = _border.IsSetTop() ? _border.top : _border.AddNewTop();
CT_Color ctColor = new CT_Color();
ctColor.indexed = (uint)(value);
ctColor.indexedSpecified = true;
pr.color = (ctColor);
}
}
#endregion
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Windows.Media.Colors.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Windows.Media
{
sealed public partial class Colors
{
#region Methods and constructors
private Colors()
{
}
#endregion
#region Properties and indexers
public static Color AliceBlue
{
get
{
return default(Color);
}
}
public static Color AntiqueWhite
{
get
{
return default(Color);
}
}
public static Color Aqua
{
get
{
return default(Color);
}
}
public static Color Aquamarine
{
get
{
return default(Color);
}
}
public static Color Azure
{
get
{
return default(Color);
}
}
public static Color Beige
{
get
{
return default(Color);
}
}
public static Color Bisque
{
get
{
return default(Color);
}
}
public static Color Black
{
get
{
return default(Color);
}
}
public static Color BlanchedAlmond
{
get
{
return default(Color);
}
}
public static Color Blue
{
get
{
return default(Color);
}
}
public static Color BlueViolet
{
get
{
return default(Color);
}
}
public static Color Brown
{
get
{
return default(Color);
}
}
public static Color BurlyWood
{
get
{
return default(Color);
}
}
public static Color CadetBlue
{
get
{
return default(Color);
}
}
public static Color Chartreuse
{
get
{
return default(Color);
}
}
public static Color Chocolate
{
get
{
return default(Color);
}
}
public static Color Coral
{
get
{
return default(Color);
}
}
public static Color CornflowerBlue
{
get
{
return default(Color);
}
}
public static Color Cornsilk
{
get
{
return default(Color);
}
}
public static Color Crimson
{
get
{
return default(Color);
}
}
public static Color Cyan
{
get
{
return default(Color);
}
}
public static Color DarkBlue
{
get
{
return default(Color);
}
}
public static Color DarkCyan
{
get
{
return default(Color);
}
}
public static Color DarkGoldenrod
{
get
{
return default(Color);
}
}
public static Color DarkGray
{
get
{
return default(Color);
}
}
public static Color DarkGreen
{
get
{
return default(Color);
}
}
public static Color DarkKhaki
{
get
{
return default(Color);
}
}
public static Color DarkMagenta
{
get
{
return default(Color);
}
}
public static Color DarkOliveGreen
{
get
{
return default(Color);
}
}
public static Color DarkOrange
{
get
{
return default(Color);
}
}
public static Color DarkOrchid
{
get
{
return default(Color);
}
}
public static Color DarkRed
{
get
{
return default(Color);
}
}
public static Color DarkSalmon
{
get
{
return default(Color);
}
}
public static Color DarkSeaGreen
{
get
{
return default(Color);
}
}
public static Color DarkSlateBlue
{
get
{
return default(Color);
}
}
public static Color DarkSlateGray
{
get
{
return default(Color);
}
}
public static Color DarkTurquoise
{
get
{
return default(Color);
}
}
public static Color DarkViolet
{
get
{
return default(Color);
}
}
public static Color DeepPink
{
get
{
return default(Color);
}
}
public static Color DeepSkyBlue
{
get
{
return default(Color);
}
}
public static Color DimGray
{
get
{
return default(Color);
}
}
public static Color DodgerBlue
{
get
{
return default(Color);
}
}
public static Color Firebrick
{
get
{
return default(Color);
}
}
public static Color FloralWhite
{
get
{
return default(Color);
}
}
public static Color ForestGreen
{
get
{
return default(Color);
}
}
public static Color Fuchsia
{
get
{
return default(Color);
}
}
public static Color Gainsboro
{
get
{
return default(Color);
}
}
public static Color GhostWhite
{
get
{
return default(Color);
}
}
public static Color Gold
{
get
{
return default(Color);
}
}
public static Color Goldenrod
{
get
{
return default(Color);
}
}
public static Color Gray
{
get
{
return default(Color);
}
}
public static Color Green
{
get
{
return default(Color);
}
}
public static Color GreenYellow
{
get
{
return default(Color);
}
}
public static Color Honeydew
{
get
{
return default(Color);
}
}
public static Color HotPink
{
get
{
return default(Color);
}
}
public static Color IndianRed
{
get
{
return default(Color);
}
}
public static Color Indigo
{
get
{
return default(Color);
}
}
public static Color Ivory
{
get
{
return default(Color);
}
}
public static Color Khaki
{
get
{
return default(Color);
}
}
public static Color Lavender
{
get
{
return default(Color);
}
}
public static Color LavenderBlush
{
get
{
return default(Color);
}
}
public static Color LawnGreen
{
get
{
return default(Color);
}
}
public static Color LemonChiffon
{
get
{
return default(Color);
}
}
public static Color LightBlue
{
get
{
return default(Color);
}
}
public static Color LightCoral
{
get
{
return default(Color);
}
}
public static Color LightCyan
{
get
{
return default(Color);
}
}
public static Color LightGoldenrodYellow
{
get
{
return default(Color);
}
}
public static Color LightGray
{
get
{
return default(Color);
}
}
public static Color LightGreen
{
get
{
return default(Color);
}
}
public static Color LightPink
{
get
{
return default(Color);
}
}
public static Color LightSalmon
{
get
{
return default(Color);
}
}
public static Color LightSeaGreen
{
get
{
return default(Color);
}
}
public static Color LightSkyBlue
{
get
{
return default(Color);
}
}
public static Color LightSlateGray
{
get
{
return default(Color);
}
}
public static Color LightSteelBlue
{
get
{
return default(Color);
}
}
public static Color LightYellow
{
get
{
return default(Color);
}
}
public static Color Lime
{
get
{
return default(Color);
}
}
public static Color LimeGreen
{
get
{
return default(Color);
}
}
public static Color Linen
{
get
{
return default(Color);
}
}
public static Color Magenta
{
get
{
return default(Color);
}
}
public static Color Maroon
{
get
{
return default(Color);
}
}
public static Color MediumAquamarine
{
get
{
return default(Color);
}
}
public static Color MediumBlue
{
get
{
return default(Color);
}
}
public static Color MediumOrchid
{
get
{
return default(Color);
}
}
public static Color MediumPurple
{
get
{
return default(Color);
}
}
public static Color MediumSeaGreen
{
get
{
return default(Color);
}
}
public static Color MediumSlateBlue
{
get
{
return default(Color);
}
}
public static Color MediumSpringGreen
{
get
{
return default(Color);
}
}
public static Color MediumTurquoise
{
get
{
return default(Color);
}
}
public static Color MediumVioletRed
{
get
{
return default(Color);
}
}
public static Color MidnightBlue
{
get
{
return default(Color);
}
}
public static Color MintCream
{
get
{
return default(Color);
}
}
public static Color MistyRose
{
get
{
return default(Color);
}
}
public static Color Moccasin
{
get
{
return default(Color);
}
}
public static Color NavajoWhite
{
get
{
return default(Color);
}
}
public static Color Navy
{
get
{
return default(Color);
}
}
public static Color OldLace
{
get
{
return default(Color);
}
}
public static Color Olive
{
get
{
return default(Color);
}
}
public static Color OliveDrab
{
get
{
return default(Color);
}
}
public static Color Orange
{
get
{
return default(Color);
}
}
public static Color OrangeRed
{
get
{
return default(Color);
}
}
public static Color Orchid
{
get
{
return default(Color);
}
}
public static Color PaleGoldenrod
{
get
{
return default(Color);
}
}
public static Color PaleGreen
{
get
{
return default(Color);
}
}
public static Color PaleTurquoise
{
get
{
return default(Color);
}
}
public static Color PaleVioletRed
{
get
{
return default(Color);
}
}
public static Color PapayaWhip
{
get
{
return default(Color);
}
}
public static Color PeachPuff
{
get
{
return default(Color);
}
}
public static Color Peru
{
get
{
return default(Color);
}
}
public static Color Pink
{
get
{
return default(Color);
}
}
public static Color Plum
{
get
{
return default(Color);
}
}
public static Color PowderBlue
{
get
{
return default(Color);
}
}
public static Color Purple
{
get
{
return default(Color);
}
}
public static Color Red
{
get
{
return default(Color);
}
}
public static Color RosyBrown
{
get
{
return default(Color);
}
}
public static Color RoyalBlue
{
get
{
return default(Color);
}
}
public static Color SaddleBrown
{
get
{
return default(Color);
}
}
public static Color Salmon
{
get
{
return default(Color);
}
}
public static Color SandyBrown
{
get
{
return default(Color);
}
}
public static Color SeaGreen
{
get
{
return default(Color);
}
}
public static Color SeaShell
{
get
{
return default(Color);
}
}
public static Color Sienna
{
get
{
return default(Color);
}
}
public static Color Silver
{
get
{
return default(Color);
}
}
public static Color SkyBlue
{
get
{
return default(Color);
}
}
public static Color SlateBlue
{
get
{
return default(Color);
}
}
public static Color SlateGray
{
get
{
return default(Color);
}
}
public static Color Snow
{
get
{
return default(Color);
}
}
public static Color SpringGreen
{
get
{
return default(Color);
}
}
public static Color SteelBlue
{
get
{
return default(Color);
}
}
public static Color Tan
{
get
{
return default(Color);
}
}
public static Color Teal
{
get
{
return default(Color);
}
}
public static Color Thistle
{
get
{
return default(Color);
}
}
public static Color Tomato
{
get
{
return default(Color);
}
}
public static Color Transparent
{
get
{
return default(Color);
}
}
public static Color Turquoise
{
get
{
return default(Color);
}
}
public static Color Violet
{
get
{
return default(Color);
}
}
public static Color Wheat
{
get
{
return default(Color);
}
}
public static Color White
{
get
{
return default(Color);
}
}
public static Color WhiteSmoke
{
get
{
return default(Color);
}
}
public static Color Yellow
{
get
{
return default(Color);
}
}
public static Color YellowGreen
{
get
{
return default(Color);
}
}
#endregion
}
}
| |
using System.Drawing;
using System.Windows.Forms;
namespace ToolStripCustomizer.ColorTables
{
sealed class OfficeXPColorTable : PresetColorTable
{
public OfficeXPColorTable()
: base("Office XP")
{
}
public override Color ButtonSelectedBorder
{
get { return Color.FromArgb(51, 94, 168); }
}
public override Color ButtonCheckedGradientBegin
{
get { return Color.FromArgb(226, 229, 238); }
}
public override Color ButtonCheckedGradientMiddle
{
get { return Color.FromArgb(226, 229, 238); }
}
public override Color ButtonCheckedGradientEnd
{
get { return Color.FromArgb(226, 229, 238); }
}
public override Color ButtonSelectedGradientBegin
{
get { return Color.FromArgb(194, 207, 229); }
}
public override Color ButtonSelectedGradientMiddle
{
get { return Color.FromArgb(194, 207, 229); }
}
public override Color ButtonSelectedGradientEnd
{
get { return Color.FromArgb(194, 207, 229); }
}
public override Color ButtonPressedGradientBegin
{
get { return Color.FromArgb(153, 175, 212); }
}
public override Color ButtonPressedGradientMiddle
{
get { return Color.FromArgb(153, 175, 212); }
}
public override Color ButtonPressedGradientEnd
{
get { return Color.FromArgb(153, 175, 212); }
}
public override Color CheckBackground
{
get { return Color.FromArgb(226, 229, 238); }
}
public override Color CheckSelectedBackground
{
get { return Color.FromArgb(51, 94, 168); }
}
public override Color CheckPressedBackground
{
get { return Color.FromArgb(51, 94, 168); }
}
public override Color GripDark
{
get { return Color.FromArgb(189, 188, 191); }
}
public override Color GripLight
{
get { return Color.FromArgb(255, 255, 255); }
}
public override Color ImageMarginGradientBegin
{
get { return Color.FromArgb(252, 252, 252); }
}
public override Color ImageMarginGradientMiddle
{
get { return Color.FromArgb(245, 244, 246); }
}
public override Color ImageMarginGradientEnd
{
get { return Color.FromArgb(235, 233, 237); }
}
public override Color ImageMarginRevealedGradientBegin
{
get { return Color.FromArgb(247, 246, 248); }
}
public override Color ImageMarginRevealedGradientMiddle
{
get { return Color.FromArgb(241, 240, 242); }
}
public override Color ImageMarginRevealedGradientEnd
{
get { return Color.FromArgb(228, 226, 230); }
}
public override Color MenuStripGradientBegin
{
get { return Color.FromArgb(235, 233, 237); }
}
public override Color MenuStripGradientEnd
{
get { return Color.FromArgb(251, 250, 251); }
}
public override Color MenuItemSelected
{
get { return Color.FromArgb(194, 207, 229); }
}
public override Color MenuItemBorder
{
get { return Color.FromArgb(51, 94, 168); }
}
public override Color MenuBorder
{
get { return Color.FromArgb(134, 133, 136); }
}
public override Color MenuItemSelectedGradientBegin
{
get { return Color.FromArgb(194, 207, 229); }
}
public override Color MenuItemSelectedGradientEnd
{
get { return Color.FromArgb(194, 207, 229); }
}
public override Color MenuItemPressedGradientBegin
{
get { return Color.FromArgb(252, 252, 252); }
}
public override Color MenuItemPressedGradientMiddle
{
get { return Color.FromArgb(241, 240, 242); }
}
public override Color MenuItemPressedGradientEnd
{
get { return Color.FromArgb(245, 244, 246); }
}
public override Color RaftingContainerGradientBegin
{
get { return Color.FromArgb(235, 233, 237); }
}
public override Color RaftingContainerGradientEnd
{
get { return Color.FromArgb(251, 250, 251); }
}
public override Color SeparatorDark
{
get { return Color.FromArgb(193, 193, 196); }
}
public override Color SeparatorLight
{
get { return Color.FromArgb(255, 255, 255); }
}
public override Color StatusStripGradientBegin
{
get { return Color.FromArgb(235, 233, 237); }
}
public override Color StatusStripGradientEnd
{
get { return Color.FromArgb(251, 250, 251); }
}
public override Color ToolStripBorder
{
get { return Color.FromArgb(238, 237, 240); }
}
public override Color ToolStripDropDownBackground
{
get { return Color.FromArgb(252, 252, 252); }
}
public override Color ToolStripGradientBegin
{
get { return Color.FromArgb(252, 252, 252); }
}
public override Color ToolStripGradientMiddle
{
get { return Color.FromArgb(245, 244, 246); }
}
public override Color ToolStripGradientEnd
{
get { return Color.FromArgb(235, 233, 237); }
}
public override Color ToolStripContentPanelGradientBegin
{
get { return Color.FromArgb(235, 233, 237); }
}
public override Color ToolStripContentPanelGradientEnd
{
get { return Color.FromArgb(251, 250, 251); }
}
public override Color ToolStripPanelGradientBegin
{
get { return Color.FromArgb(235, 233, 237); }
}
public override Color ToolStripPanelGradientEnd
{
get { return Color.FromArgb(251, 250, 251); }
}
public override Color OverflowButtonGradientBegin
{
get { return Color.FromArgb(242, 242, 242); }
}
public override Color OverflowButtonGradientMiddle
{
get { return Color.FromArgb(224, 224, 225); }
}
public override Color OverflowButtonGradientEnd
{
get { return Color.FromArgb(167, 166, 170); }
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing.Internal;
using System.Runtime.InteropServices;
using Gdip = System.Drawing.SafeNativeMethods.Gdip;
namespace System.Drawing
{
public sealed partial class Font
{
///<summary>
/// Creates the GDI+ native font object.
///</summary>
private void CreateNativeFont()
{
Debug.Assert(_nativeFont == IntPtr.Zero, "nativeFont already initialized, this will generate a handle leak.");
Debug.Assert(_fontFamily != null, "fontFamily not initialized.");
// Note: GDI+ creates singleton font family objects (from the corresponding font file) and reference count them so
// if creating the font object from an external FontFamily, this object's FontFamily will share the same native object.
int status = Gdip.GdipCreateFont(
new HandleRef(this, _fontFamily.NativeFamily),
_fontSize,
_fontStyle,
_fontUnit,
out _nativeFont);
// Special case this common error message to give more information
if (status == Gdip.FontStyleNotFound)
{
throw new ArgumentException(SR.Format(SR.GdiplusFontStyleNotFound, _fontFamily.Name, _fontStyle.ToString()));
}
else if (status != Gdip.Ok)
{
throw Gdip.StatusException(status);
}
}
/// <summary>
/// Initializes a new instance of the <see cref='Font'/> class from the specified existing <see cref='Font'/>
/// and <see cref='FontStyle'/>.
/// </summary>
public Font(Font prototype, FontStyle newStyle)
{
// Copy over the originalFontName because it won't get initialized
_originalFontName = prototype.OriginalFontName;
Initialize(prototype.FontFamily, prototype.Size, newStyle, prototype.Unit, SafeNativeMethods.DEFAULT_CHARSET, false);
}
/// <summary>
/// Initializes a new instance of the <see cref='Font'/> class with the specified attributes.
/// </summary>
public Font(FontFamily family, float emSize, FontStyle style, GraphicsUnit unit)
{
Initialize(family, emSize, style, unit, SafeNativeMethods.DEFAULT_CHARSET, false);
}
/// <summary>
/// Initializes a new instance of the <see cref='Font'/> class with the specified attributes.
/// </summary>
public Font(FontFamily family, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet)
{
Initialize(family, emSize, style, unit, gdiCharSet, false);
}
/// <summary>
/// Initializes a new instance of the <see cref='Font'/> class with the specified attributes.
/// </summary>
public Font(FontFamily family, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet, bool gdiVerticalFont)
{
Initialize(family, emSize, style, unit, gdiCharSet, gdiVerticalFont);
}
/// <summary>
/// Initializes a new instance of the <see cref='Font'/> class with the specified attributes.
/// </summary>
public Font(string familyName, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet)
{
Initialize(familyName, emSize, style, unit, gdiCharSet, IsVerticalName(familyName));
}
/// <summary>
/// Initializes a new instance of the <see cref='Font'/> class with the specified attributes.
/// </summary>
public Font(string familyName, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet, bool gdiVerticalFont)
{
if (float.IsNaN(emSize) || float.IsInfinity(emSize) || emSize <= 0)
{
throw new ArgumentException(SR.Format(SR.InvalidBoundArgument, nameof(emSize), emSize, 0, "System.Single.MaxValue"), nameof(emSize));
}
Initialize(familyName, emSize, style, unit, gdiCharSet, gdiVerticalFont);
}
/// <summary>
/// Initializes a new instance of the <see cref='Font'/> class with the specified attributes.
/// </summary>
public Font(FontFamily family, float emSize, FontStyle style)
{
Initialize(family, emSize, style, GraphicsUnit.Point, SafeNativeMethods.DEFAULT_CHARSET, false);
}
/// <summary>
/// Initializes a new instance of the <see cref='Font'/> class with the specified attributes.
/// </summary>
public Font(FontFamily family, float emSize, GraphicsUnit unit)
{
Initialize(family, emSize, FontStyle.Regular, unit, SafeNativeMethods.DEFAULT_CHARSET, false);
}
/// <summary>
/// Initializes a new instance of the <see cref='Font'/> class with the specified attributes.
/// </summary>
public Font(FontFamily family, float emSize)
{
Initialize(family, emSize, FontStyle.Regular, GraphicsUnit.Point, SafeNativeMethods.DEFAULT_CHARSET, false);
}
/// <summary>
/// Initializes a new instance of the <see cref='Font'/> class with the specified attributes.
/// </summary>
public Font(string familyName, float emSize, FontStyle style, GraphicsUnit unit)
{
Initialize(familyName, emSize, style, unit, SafeNativeMethods.DEFAULT_CHARSET, IsVerticalName(familyName));
}
/// <summary>
/// Initializes a new instance of the <see cref='Font'/> class with the specified attributes.
/// </summary>
public Font(string familyName, float emSize, FontStyle style)
{
Initialize(familyName, emSize, style, GraphicsUnit.Point, SafeNativeMethods.DEFAULT_CHARSET, IsVerticalName(familyName));
}
/// <summary>
/// Initializes a new instance of the <see cref='Font'/> class with the specified attributes.
/// </summary>
public Font(string familyName, float emSize, GraphicsUnit unit)
{
Initialize(familyName, emSize, FontStyle.Regular, unit, SafeNativeMethods.DEFAULT_CHARSET, IsVerticalName(familyName));
}
/// <summary>
/// Initializes a new instance of the <see cref='Font'/> class with the specified attributes.
/// </summary>
public Font(string familyName, float emSize)
{
Initialize(familyName, emSize, FontStyle.Regular, GraphicsUnit.Point, SafeNativeMethods.DEFAULT_CHARSET, IsVerticalName(familyName));
}
/// <summary>
/// Constructor to initialize fields from an existing native GDI+ object reference. Used by ToLogFont.
/// </summary>
private Font(IntPtr nativeFont, byte gdiCharSet, bool gdiVerticalFont)
{
Debug.Assert(_nativeFont == IntPtr.Zero, "GDI+ native font already initialized, this will generate a handle leak");
Debug.Assert(nativeFont != IntPtr.Zero, "nativeFont is null");
_nativeFont = nativeFont;
Gdip.CheckStatus(Gdip.GdipGetFontUnit(new HandleRef(this, nativeFont), out GraphicsUnit unit));
Gdip.CheckStatus(Gdip.GdipGetFontSize(new HandleRef(this, nativeFont), out float size));
Gdip.CheckStatus(Gdip.GdipGetFontStyle(new HandleRef(this, nativeFont), out FontStyle style));
Gdip.CheckStatus(Gdip.GdipGetFamily(new HandleRef(this, nativeFont), out IntPtr nativeFamily));
SetFontFamily(new FontFamily(nativeFamily));
Initialize(_fontFamily, size, style, unit, gdiCharSet, gdiVerticalFont);
}
/// <summary>
/// Initializes this object's fields.
/// </summary>
private void Initialize(string familyName, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet, bool gdiVerticalFont)
{
_originalFontName = familyName;
SetFontFamily(new FontFamily(StripVerticalName(familyName), createDefaultOnFail: true));
Initialize(_fontFamily, emSize, style, unit, gdiCharSet, gdiVerticalFont);
}
/// <summary>
/// Initializes this object's fields.
/// </summary>
private void Initialize(FontFamily family, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet, bool gdiVerticalFont)
{
if (family == null)
{
throw new ArgumentNullException(nameof(family));
}
if (float.IsNaN(emSize) || float.IsInfinity(emSize) || emSize <= 0)
{
throw new ArgumentException(SR.Format(SR.InvalidBoundArgument, nameof(emSize), emSize, 0, "System.Single.MaxValue"), nameof(emSize));
}
int status;
_fontSize = emSize;
_fontStyle = style;
_fontUnit = unit;
_gdiCharSet = gdiCharSet;
_gdiVerticalFont = gdiVerticalFont;
if (_fontFamily == null)
{
// GDI+ FontFamily is a singleton object.
SetFontFamily(new FontFamily(family.NativeFamily));
}
if (_nativeFont == IntPtr.Zero)
{
CreateNativeFont();
}
// Get actual size.
status = Gdip.GdipGetFontSize(new HandleRef(this, _nativeFont), out _fontSize);
Gdip.CheckStatus(status);
}
/// <summary>
/// Creates a <see cref='Font'/> from the specified Windows handle.
/// </summary>
public static Font FromHfont(IntPtr hfont)
{
var logFont = new SafeNativeMethods.LOGFONT();
SafeNativeMethods.GetObject(new HandleRef(null, hfont), ref logFont);
using (ScreenDC dc = ScreenDC.Create())
{
return FromLogFontInternal(ref logFont, dc);
}
}
/// <summary>
/// Creates a <see cref="Font"/> from the given LOGFONT using the screen device context.
/// </summary>
/// <param name="lf">A boxed LOGFONT.</param>
/// <returns>The newly created <see cref="Font"/>.</returns>
public static Font FromLogFont(object lf)
{
using (ScreenDC dc = ScreenDC.Create())
{
return FromLogFont(lf, dc);
}
}
internal static Font FromLogFont(ref SafeNativeMethods.LOGFONT logFont)
{
using (ScreenDC dc = ScreenDC.Create())
{
return FromLogFont(logFont, dc);
}
}
internal static Font FromLogFontInternal(ref SafeNativeMethods.LOGFONT logFont, IntPtr hdc)
{
int status = Gdip.GdipCreateFontFromLogfontW(hdc, ref logFont, out IntPtr font);
// Special case this incredibly common error message to give more information
if (status == Gdip.NotTrueTypeFont)
{
throw new ArgumentException(SR.GdiplusNotTrueTypeFont_NoName);
}
else if (status != Gdip.Ok)
{
throw Gdip.StatusException(status);
}
// GDI+ returns font = 0 even though the status is Ok.
if (font == IntPtr.Zero)
{
throw new ArgumentException(SR.Format(SR.GdiplusNotTrueTypeFont, logFont.ToString()));
}
bool gdiVerticalFont = logFont.lfFaceName[0] == '@';
return new Font(font, logFont.lfCharSet, gdiVerticalFont);
}
/// <summary>
/// Creates a <see cref="Font"/> from the given LOGFONT using the given device context.
/// </summary>
/// <param name="lf">A boxed LOGFONT.</param>
/// <param name="hdc">Handle to a device context (HDC).</param>
/// <returns>The newly created <see cref="Font"/>.</returns>
public static unsafe Font FromLogFont(object lf, IntPtr hdc)
{
if (lf == null)
{
throw new ArgumentNullException(nameof(lf));
}
if (lf is SafeNativeMethods.LOGFONT logFont)
{
// A boxed LOGFONT, just use it to create the font
return FromLogFontInternal(ref logFont, hdc);
}
Type type = lf.GetType();
int nativeSize = sizeof(SafeNativeMethods.LOGFONT);
if (Marshal.SizeOf(type) != nativeSize)
{
// If we don't actually have an object that is LOGFONT in size, trying to pass
// it to GDI+ is likely to cause an AV.
throw new ArgumentException();
}
// Now that we know the marshalled size is the same as LOGFONT, copy in the data
logFont = new SafeNativeMethods.LOGFONT();
if (!type.IsValueType)
{
// Only works with non value types
Marshal.StructureToPtr(lf, new IntPtr(&logFont), fDeleteOld: false);
}
else
{
GCHandle handle = GCHandle.Alloc(lf, GCHandleType.Pinned);
Buffer.MemoryCopy((byte*)handle.AddrOfPinnedObject(), &logFont, nativeSize, nativeSize);
handle.Free();
}
return FromLogFontInternal(ref logFont, hdc);
}
/// <summary>
/// Creates a <see cref="Font"/> from the specified handle to a device context (HDC).
/// </summary>
/// <returns>The newly created <see cref="Font"/>.</returns>
public static Font FromHdc(IntPtr hdc)
{
IntPtr font = IntPtr.Zero;
int status = Gdip.GdipCreateFontFromDC(hdc, ref font);
// Special case this incredibly common error message to give more information
if (status == Gdip.NotTrueTypeFont)
{
throw new ArgumentException(SR.GdiplusNotTrueTypeFont_NoName);
}
else if (status != Gdip.Ok)
{
throw Gdip.StatusException(status);
}
return new Font(font, 0, false);
}
/// <summary>
/// Creates an exact copy of this <see cref='Font'/>.
/// </summary>
public object Clone()
{
int status = Gdip.GdipCloneFont(new HandleRef(this, _nativeFont), out IntPtr clonedFont);
Gdip.CheckStatus(status);
return new Font(clonedFont, _gdiCharSet, _gdiVerticalFont);
}
private void SetFontFamily(FontFamily family)
{
_fontFamily = family;
// GDI+ creates ref-counted singleton FontFamily objects based on the family name so all managed
// objects with same family name share the underlying GDI+ native pointer. The unmanged object is
// destroyed when its ref-count gets to zero.
//
// Make sure _fontFamily is not finalized so the underlying singleton object is kept alive.
GC.SuppressFinalize(_fontFamily);
}
private static string StripVerticalName(string familyName)
{
if (familyName?.Length > 1 && familyName[0] == '@')
{
return familyName.Substring(1);
}
return familyName;
}
public void ToLogFont(object logFont)
{
using (ScreenDC dc = ScreenDC.Create())
using (Graphics graphics = Graphics.FromHdcInternal(dc))
{
ToLogFont(logFont, graphics);
}
}
/// <summary>
/// Returns a handle to this <see cref='Font'/>.
/// </summary>
public IntPtr ToHfont()
{
using (ScreenDC dc = ScreenDC.Create())
using (Graphics graphics = Graphics.FromHdcInternal(dc))
{
SafeNativeMethods.LOGFONT lf = ToLogFontInternal(graphics);
IntPtr handle = IntUnsafeNativeMethods.CreateFontIndirect(ref lf);
if (handle == IntPtr.Zero)
{
throw new Win32Exception();
}
return handle;
}
}
public float GetHeight()
{
using (ScreenDC dc = ScreenDC.Create())
using (Graphics graphics = Graphics.FromHdcInternal(dc))
{
return GetHeight(graphics);
}
}
/// <summary>
/// Gets the size, in points, of this <see cref='Font'/>.
/// </summary>
[Browsable(false)]
public float SizeInPoints
{
get
{
if (Unit == GraphicsUnit.Point)
{
return Size;
}
using (ScreenDC dc = ScreenDC.Create())
using (Graphics graphics = Graphics.FromHdcInternal(dc))
{
float pixelsPerPoint = (float)(graphics.DpiY / 72.0);
float lineSpacingInPixels = GetHeight(graphics);
float emHeightInPixels = lineSpacingInPixels * FontFamily.GetEmHeight(Style) / FontFamily.GetLineSpacing(Style);
return emHeightInPixels / pixelsPerPoint;
}
}
}
}
}
| |
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.Tokens;
using Microsoft.SharePoint.Client;
using System;
using System.Net;
using System.Security.Principal;
using System.Web;
using System.Web.Configuration;
namespace OAuthAddinDemoWeb
{
/// <summary>
/// Encapsulates all the information from SharePoint.
/// </summary>
public abstract class SharePointContext
{
public const string SPHostUrlKey = "SPHostUrl";
public const string SPAppWebUrlKey = "SPAppWebUrl";
public const string SPLanguageKey = "SPLanguage";
public const string SPClientTagKey = "SPClientTag";
public const string SPProductNumberKey = "SPProductNumber";
protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0);
private readonly Uri spHostUrl;
private readonly Uri spAppWebUrl;
private readonly string spLanguage;
private readonly string spClientTag;
private readonly string spProductNumber;
// <AccessTokenString, UtcExpiresOn>
protected Tuple<string, DateTime> userAccessTokenForSPHost;
protected Tuple<string, DateTime> userAccessTokenForSPAppWeb;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb;
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]);
Uri spHostUrl;
if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) &&
(spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps))
{
return spHostUrl;
}
return null;
}
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequest httpRequest)
{
return GetSPHostUrl(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// The SharePoint host url.
/// </summary>
public Uri SPHostUrl
{
get { return this.spHostUrl; }
}
/// <summary>
/// The SharePoint app web url.
/// </summary>
public Uri SPAppWebUrl
{
get { return this.spAppWebUrl; }
}
/// <summary>
/// The SharePoint language.
/// </summary>
public string SPLanguage
{
get { return this.spLanguage; }
}
/// <summary>
/// The SharePoint client tag.
/// </summary>
public string SPClientTag
{
get { return this.spClientTag; }
}
/// <summary>
/// The SharePoint product number.
/// </summary>
public string SPProductNumber
{
get { return this.spProductNumber; }
}
/// <summary>
/// The user access token for the SharePoint host.
/// </summary>
public abstract string UserAccessTokenForSPHost
{
get;
}
/// <summary>
/// The user access token for the SharePoint app web.
/// </summary>
public abstract string UserAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// The app only access token for the SharePoint host.
/// </summary>
public abstract string AppOnlyAccessTokenForSPHost
{
get;
}
/// <summary>
/// The app only access token for the SharePoint app web.
/// </summary>
public abstract string AppOnlyAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber)
{
if (spHostUrl == null)
{
throw new ArgumentNullException("spHostUrl");
}
if (string.IsNullOrEmpty(spLanguage))
{
throw new ArgumentNullException("spLanguage");
}
if (string.IsNullOrEmpty(spClientTag))
{
throw new ArgumentNullException("spClientTag");
}
if (string.IsNullOrEmpty(spProductNumber))
{
throw new ArgumentNullException("spProductNumber");
}
this.spHostUrl = spHostUrl;
this.spAppWebUrl = spAppWebUrl;
this.spLanguage = spLanguage;
this.spClientTag = spClientTag;
this.spProductNumber = spProductNumber;
}
/// <summary>
/// Creates a user ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost);
}
/// <summary>
/// Creates a user ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb);
}
/// <summary>
/// Creates app only ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost);
}
/// <summary>
/// Creates an app only ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb);
}
/// <summary>
/// Gets the database connection string from SharePoint for autohosted add-in.
/// This method is deprecated because the autohosted option is no longer available.
/// </summary>
[ObsoleteAttribute("This method is deprecated because the autohosted option is no longer available.", true)]
public string GetDatabaseConnectionString()
{
throw new NotSupportedException("This method is deprecated because the autohosted option is no longer available.");
}
/// <summary>
/// Determines if the specified access token is valid.
/// It considers an access token as not valid if it is null, or it has expired.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <returns>True if the access token is valid.</returns>
protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken)
{
return accessToken != null &&
!string.IsNullOrEmpty(accessToken.Item1) &&
accessToken.Item2 > DateTime.UtcNow;
}
/// <summary>
/// Creates a ClientContext with the specified SharePoint site url and the access token.
/// </summary>
/// <param name="spSiteUrl">The site url.</param>
/// <param name="accessToken">The access token.</param>
/// <returns>A ClientContext instance.</returns>
private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken)
{
if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken))
{
return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken);
}
return null;
}
}
/// <summary>
/// Redirection status.
/// </summary>
public enum RedirectionStatus
{
Ok,
ShouldRedirect,
CanNotRedirect
}
/// <summary>
/// Provides SharePointContext instances.
/// </summary>
public abstract class SharePointContextProvider
{
private static SharePointContextProvider current;
/// <summary>
/// The current SharePointContextProvider instance.
/// </summary>
public static SharePointContextProvider Current
{
get { return SharePointContextProvider.current; }
}
/// <summary>
/// Initializes the default SharePointContextProvider instance.
/// </summary>
static SharePointContextProvider()
{
if (!TokenHelper.IsHighTrustApp())
{
SharePointContextProvider.current = new SharePointAcsContextProvider();
}
else
{
SharePointContextProvider.current = new SharePointHighTrustContextProvider();
}
}
/// <summary>
/// Registers the specified SharePointContextProvider instance as current.
/// It should be called by Application_Start() in Global.asax.
/// </summary>
/// <param name="provider">The SharePointContextProvider to be set as current.</param>
public static void Register(SharePointContextProvider provider)
{
if (provider == null)
{
throw new ArgumentNullException("provider");
}
SharePointContextProvider.current = provider;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
redirectUrl = null;
bool contextTokenExpired = false;
try
{
if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null)
{
return RedirectionStatus.Ok;
}
}
catch (SecurityTokenExpiredException)
{
contextTokenExpired = true;
}
const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint";
if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]) && !contextTokenExpired)
{
return RedirectionStatus.CanNotRedirect;
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return RedirectionStatus.CanNotRedirect;
}
if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST"))
{
return RedirectionStatus.CanNotRedirect;
}
Uri requestUrl = httpContext.Request.Url;
var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query);
// Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string.
queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPLanguageKey);
queryNameValueCollection.Remove(SharePointContext.SPClientTagKey);
queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey);
// Adds SPHasRedirectedToSharePoint=1.
queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1");
UriBuilder returnUrlBuilder = new UriBuilder(requestUrl);
returnUrlBuilder.Query = queryNameValueCollection.ToString();
// Inserts StandardTokens.
const string StandardTokens = "{StandardTokens}";
string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri;
returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&");
// Constructs redirect url.
string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString));
redirectUrl = new Uri(redirectUrlString, UriKind.Absolute);
return RedirectionStatus.ShouldRedirect;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl)
{
return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
// SPHostUrl
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest);
if (spHostUrl == null)
{
return null;
}
// SPAppWebUrl
string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]);
Uri spAppWebUrl;
if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) ||
!(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps))
{
spAppWebUrl = null;
}
// SPLanguage
string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey];
if (string.IsNullOrEmpty(spLanguage))
{
return null;
}
// SPClientTag
string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey];
if (string.IsNullOrEmpty(spClientTag))
{
return null;
}
// SPProductNumber
string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey];
if (string.IsNullOrEmpty(spProductNumber))
{
return null;
}
return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequest httpRequest)
{
return CreateSharePointContext(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return null;
}
SharePointContext spContext = LoadSharePointContext(httpContext);
if (spContext == null || !ValidateSharePointContext(spContext, httpContext))
{
spContext = CreateSharePointContext(httpContext.Request);
if (spContext != null)
{
SaveSharePointContext(spContext, httpContext);
}
}
return spContext;
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContext httpContext)
{
return GetSharePointContext(new HttpContextWrapper(httpContext));
}
/// <summary>
/// Creates a SharePointContext instance.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest);
/// <summary>
/// Validates if the given SharePointContext can be used with the specified HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext.</param>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns>
protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
/// <summary>
/// Loads the SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns>
protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext);
/// <summary>
/// Saves the specified SharePointContext instance associated with the specified HTTP context.
/// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param>
/// <param name="httpContext">The HTTP context.</param>
protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
}
#region ACS
/// <summary>
/// Encapsulates all the information from SharePoint in ACS mode.
/// </summary>
public class SharePointAcsContext : SharePointContext
{
private readonly string contextToken;
private readonly SharePointContextToken contextTokenObj;
/// <summary>
/// The context token.
/// </summary>
public string ContextToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; }
}
/// <summary>
/// The context token's "CacheKey" claim.
/// </summary>
public string CacheKey
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; }
}
/// <summary>
/// The context token's "refreshtoken" claim.
/// </summary>
public string RefreshToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl)));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl)));
}
}
public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (string.IsNullOrEmpty(contextToken))
{
throw new ArgumentNullException("contextToken");
}
if (contextTokenObj == null)
{
throw new ArgumentNullException("contextTokenObj");
}
this.contextToken = contextToken;
this.contextTokenObj = contextTokenObj;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
try
{
OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler();
DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn;
if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn);
}
catch (WebException)
{
}
}
}
/// <summary>
/// Default provider for SharePointAcsContext.
/// </summary>
public class SharePointAcsContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
private const string SPCacheKeyKey = "SPCacheKey";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest);
if (string.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = null;
try
{
contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority);
}
catch (WebException)
{
return null;
}
catch (AudienceUriValidationFailedException)
{
return null;
}
return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request);
HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey];
string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null;
return spHostUrl == spAcsContext.SPHostUrl &&
!string.IsNullOrEmpty(spAcsContext.CacheKey) &&
spCacheKey == spAcsContext.CacheKey &&
!string.IsNullOrEmpty(spAcsContext.ContextToken) &&
(string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken);
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointAcsContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey)
{
Value = spAcsContext.CacheKey,
Secure = true,
HttpOnly = true
};
httpContext.Response.AppendCookie(spCacheKeyCookie);
}
httpContext.Session[SPContextKey] = spAcsContext;
}
}
#endregion ACS
#region HighTrust
/// <summary>
/// Encapsulates all the information from SharePoint in HighTrust mode.
/// </summary>
public class SharePointHighTrustContext : SharePointContext
{
private readonly WindowsIdentity logonUserIdentity;
/// <summary>
/// The Windows identity for the current user.
/// </summary>
public WindowsIdentity LogonUserIdentity
{
get { return this.logonUserIdentity; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null));
}
}
public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (logonUserIdentity == null)
{
throw new ArgumentNullException("logonUserIdentity");
}
this.logonUserIdentity = logonUserIdentity;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime);
if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn);
}
}
/// <summary>
/// Default provider for SharePointHighTrustContext.
/// </summary>
public class SharePointHighTrustContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity;
if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null)
{
return null;
}
return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext;
if (spHighTrustContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity;
return spHostUrl == spHighTrustContext.SPHostUrl &&
logonUserIdentity != null &&
logonUserIdentity.IsAuthenticated &&
!logonUserIdentity.IsGuest &&
logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User;
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointHighTrustContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext;
}
}
#endregion HighTrust
}
| |
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
namespace Microsoft.Zelig.Test
{
public class ConvertTests : TestBase, ITestInterface
{
[SetUp]
public InitializeResult Initialize()
{
Log.Comment("Adding set up for the tests.");
// Add your functionality here.
return InitializeResult.ReadyToGo;
}
[TearDown]
public void CleanUp()
{
}
public override TestResult Run( string[] args )
{
TestResult result = TestResult.Pass;
string testName = "Expenum2_";
int testNumber = 0;
result |= Assert.CheckFailed( Cast_FloatingPoint( ), testName, ++testNumber );
result |= Assert.CheckFailed( Convert_Positive( ), testName, ++testNumber );
result |= Assert.CheckFailed( Convert_PositivePlus( ), testName, ++testNumber );
result |= Assert.CheckFailed( Convert_Negative( ), testName, ++testNumber );
result |= Assert.CheckFailed( Convert_Double( ), testName, ++testNumber );
result |= Assert.CheckFailed( Convert_Plus( ), testName, ++testNumber );
result |= Assert.CheckFailed( Convert_Neg( ), testName, ++testNumber );
result |= Assert.CheckFailed( Convert_Whitespace( ), testName, ++testNumber );
result |= Assert.CheckFailed( Convert_DoubleNormalizeNeg( ), testName, ++testNumber );
result |= Assert.CheckFailed( Convert_HexInt( ), testName, ++testNumber );
result |= Assert.CheckFailed( Convert_BoundaryValues( ), testName, ++testNumber );
result |= Assert.CheckFailed( Convert_LeadingZeroValues( ), testName, ++testNumber );
result |= Assert.CheckFailed( Convert_LeadingZeros( ), testName, ++testNumber );
result |= Assert.CheckFailed( Convert_64ParsePerf( ), testName, ++testNumber );
return result;
}
//Test Case Calls
[TestMethod]
public TestResult Cast_FloatingPoint()
{
TestResult res = TestResult.Pass;
uint u1;
uint u2;
double d1;
float f1;
long l1;
long l2;
double d2;
Random rand = new Random();
for (int i = 0; i < 100; i++)
{
u1 = (uint)rand.Next();
d1 = (double)u1; // Does not work correctly (d1 is close to 0)
u2 = (uint)d1;
if (d1 != u1 || u2 != u1)
{
Log.Comment("Cast from uint to double failed");
res = TestResult.Fail;
}
f1 = (float)u1; // Same problem
if (f1 != u1)
{
Log.Comment("Cast from uint to float failed");
res = TestResult.Fail;
}
l1 = (long)u1;
u2 = (uint)l1;
if (l1 != u1 || u2 != u1)
{
Log.Comment("Cast from uint to long failed");
res = TestResult.Fail;
}
d2 = l1; // Same problem
l2 = (long)d2;
if (d2 != l1 || l2 != l1)
{
Log.Comment("Cast from long to double failed");
res = TestResult.Fail;
}
}
return res;
}
//Test Case Calls
[TestMethod]
public TestResult Convert_Positive()
{
string number = "12";
int actualNumber = 12;
SByte value_sb = Convert.ToSByte(number);
if (value_sb != (byte)12)
{
return TestResult.Fail;
}
//--//
Byte value_b = Convert.ToByte(number);
if (value_b != (byte)12)
{
return TestResult.Fail;
}
//--//
Int16 value_s16 = Convert.ToInt16(number);
if (value_s16 != (short)12)
{
return TestResult.Fail;
}
//--//
UInt16 value_u16 = Convert.ToUInt16(number);
if (value_u16 != (ushort)12)
{
return TestResult.Fail;
}
//--//
Int32 value_s32 = Convert.ToInt32(number);
if (value_s32 != (int)12)
{
return TestResult.Fail;
}
//--//
UInt32 value_u32 = Convert.ToUInt32(number);
if (value_u32 != (uint)12)
{
return TestResult.Fail;
}
//--//
Int64 value_s64 = Convert.ToInt32(number);
if (value_s64 != (long)12)
{
return TestResult.Fail;
}
//--//
UInt64 value_u64 = Convert.ToUInt64(number);
if (value_u64 != (ulong)12)
{
return TestResult.Fail;
}
return TestResult.Pass;
}
//Test Case Calls
[TestMethod]
public TestResult Convert_PositivePlus()
{
string number = "+12";
int actualNumber = 12;
SByte value_sb = Convert.ToSByte(number);
if (value_sb != (byte)12)
{
return TestResult.Fail;
}
//--//
Byte value_b = Convert.ToByte(number);
if (value_b != (byte)12)
{
return TestResult.Fail;
}
//--//
Int16 value_s16 = Convert.ToInt16(number);
if (value_s16 != (short)12)
{
return TestResult.Fail;
}
//--//
UInt16 value_u16 = Convert.ToUInt16(number);
if (value_u16 != (ushort)12)
{
return TestResult.Fail;
}
//--//
Int32 value_s32 = Convert.ToInt32(number);
if (value_s32 != (int)12)
{
return TestResult.Fail;
}
//--//
UInt32 value_u32 = Convert.ToUInt32(number);
if (value_u32 != (uint)12)
{
return TestResult.Fail;
}
//--//
Int64 value_s64 = Convert.ToInt32(number);
if (value_s64 != (long)12)
{
return TestResult.Fail;
}
//--//
UInt64 value_u64 = Convert.ToUInt64(number);
if (value_u64 != (ulong)12)
{
return TestResult.Fail;
}
return TestResult.Pass;
}
[TestMethod]
public TestResult Convert_Negative()
{
string number = "-12";
int actualNumber = -12;
SByte value_sb = Convert.ToSByte(number);
if (value_sb != (sbyte)actualNumber)
{
return TestResult.Fail;
}
//--//
try
{
Byte value_b = Convert.ToByte(number);
return TestResult.Fail;
}
catch
{
}
//--//
Int16 value_s16 = Convert.ToInt16(number);
if (value_s16 != (short)actualNumber)
{
return TestResult.Fail;
}
//--//
try
{
UInt16 value_u16 = Convert.ToUInt16(number);
return TestResult.Fail;
}
catch
{
}
//--//
Int32 value_s32 = Convert.ToInt32(number);
if (value_s32 != (int)actualNumber)
{
return TestResult.Fail;
}
//--//
try
{
UInt32 value_u32 = Convert.ToUInt32(number);
return TestResult.Fail;
}
catch
{
}
//--//
Int64 value_s64 = Convert.ToInt32(number);
if (value_s64 != (long)actualNumber)
{
return TestResult.Fail;
}
//--//
try
{
UInt64 value_u64 = Convert.ToUInt64(number);
return TestResult.Fail;
}
catch
{
}
return TestResult.Pass;
}
[TestMethod]
public TestResult Convert_Double()
{
string number = "36.123456";
double actualNumber = 36.123456;
double value_dd = Convert.ToDouble(number);
if (value_dd != actualNumber)
{
return TestResult.Fail;
}
return TestResult.Pass;
}
[TestMethod]
public TestResult Convert_Plus()
{
string number = "+36.123456";
double actualNumber = 36.123456;
double value_dd = Convert.ToDouble(number);
if (value_dd != actualNumber)
{
return TestResult.Fail;
}
return TestResult.Pass;
}
[TestMethod]
public TestResult Convert_Neg()
{
string number = "-36.123456";
double actualNumber = -36.123456;
double value_dd = Convert.ToDouble(number);
if (value_dd != actualNumber)
{
return TestResult.Fail;
}
return TestResult.Pass;
}
[TestMethod]
public TestResult Convert_Whitespace()
{
string intnum = " -3484 ";
string number = " +36.123456 ";
long actualInt = -3484;
double actualNumber = 36.123456;
if (actualInt != Convert.ToInt16(intnum))
{
return TestResult.Fail;
}
if (actualInt != Convert.ToInt32(intnum))
{
return TestResult.Fail;
}
if (actualInt != Convert.ToInt64(intnum))
{
return TestResult.Fail;
}
double value_dd = Convert.ToDouble(number);
if (value_dd != actualNumber)
{
return TestResult.Fail;
}
return TestResult.Pass;
}
[TestMethod]
public TestResult Convert_DoubleNormalizeNeg()
{
string number = "-3600030383448481.123456";
double actualNumber = -3600030383448481.123456;
double value_dd = Convert.ToDouble(number);
if (value_dd != actualNumber)
{
return TestResult.Fail;
}
number = "+0.00000000484874758559e-3";
actualNumber = 4.84874758559e-12;
if (actualNumber != Convert.ToDouble(number))
{
return TestResult.Fail;
}
return TestResult.Pass;
}
[TestMethod]
public TestResult Convert_HexInt()
{
string number = "0x01234567";
int actualNumber = 0x01234567;
int value = Convert.ToInt32(number, 16);
if (value != actualNumber)
{
return TestResult.Fail;
}
number = "0x89abcdef";
unchecked
{
actualNumber = (int)0x89abcdef;
}
if (actualNumber != Convert.ToInt32(number, 16))
{
return TestResult.Fail;
}
number = "0x0AbF83C";
actualNumber = 0xAbF83C;
if (actualNumber != Convert.ToInt32(number, 16))
{
return TestResult.Fail;
}
return TestResult.Pass;
}
[TestMethod]
public TestResult Convert_BoundaryValues()
{
double valMax = double.MaxValue;
string numMax = valMax.ToString();
double valMin = double.MinValue;
string numMin = valMin.ToString();
if(valMax != Convert.ToDouble(numMax)) return TestResult.Fail;
if(valMin != Convert.ToDouble(numMin)) return TestResult.Fail;
valMax = float.MaxValue;
numMax = valMax.ToString();
valMin = float.MinValue;
numMin = valMin.ToString();
if(valMax != Convert.ToDouble(numMax)) return TestResult.Fail;
if(valMin != Convert.ToDouble(numMin)) return TestResult.Fail;
long lMax = long.MaxValue;
numMax = lMax.ToString();
long lMin = long.MinValue;
numMin = lMin.ToString();
if(lMax != Convert.ToInt64(numMax)) return TestResult.Fail;
if(lMin != Convert.ToInt64(numMin)) return TestResult.Fail;
ulong ulMax = ulong.MaxValue;
numMax = ulMax.ToString();
ulong ulMin = ulong.MinValue;
numMin = ulMin.ToString();
if(ulMax != Convert.ToUInt64(numMax)) return TestResult.Fail;
if(ulMin != Convert.ToUInt64(numMin)) return TestResult.Fail;
long iMax = int.MaxValue;
numMax = iMax.ToString();
long iMin = int.MinValue;
numMin = iMin.ToString();
if(iMax != Convert.ToInt32(numMax)) return TestResult.Fail;
if(iMin != Convert.ToInt32(numMin)) return TestResult.Fail;
uint uiMax = uint.MaxValue;
numMax = uiMax.ToString();
uint uiMin = uint.MinValue;
numMin = uiMin.ToString();
if(uiMax != Convert.ToUInt32(numMax)) return TestResult.Fail;
if(uiMin != Convert.ToUInt32(numMin)) return TestResult.Fail;
short sMax = short.MaxValue;
numMax = sMax.ToString();
short sMin = short.MinValue;
numMin = sMin.ToString();
if(sMax != Convert.ToInt16(numMax)) return TestResult.Fail;
if(sMin != Convert.ToInt16(numMin)) return TestResult.Fail;
ushort usMax = ushort.MaxValue;
numMax = usMax.ToString();
ushort usMin = ushort.MinValue;
numMin = usMin.ToString();
if(usMax != Convert.ToUInt16(numMax)) return TestResult.Fail;
if(usMin != Convert.ToUInt16(numMin)) return TestResult.Fail;
sbyte sbMax = sbyte.MaxValue;
numMax = sbMax.ToString();
sbyte sbMin = sbyte.MinValue;
numMin = sbMin.ToString();
if(sbMax != Convert.ToSByte(numMax)) return TestResult.Fail;
if(sbMin != Convert.ToSByte(numMin)) return TestResult.Fail;
byte bMax = byte.MaxValue;
numMax = bMax.ToString();
byte bMin = byte.MinValue;
numMin = bMin.ToString();
if(bMax != Convert.ToByte(numMax)) return TestResult.Fail;
if(bMin != Convert.ToByte(numMin)) return TestResult.Fail;
return TestResult.Pass;
}
[TestMethod]
public TestResult Convert_LeadingZeroValues()
{
string number = "00000000";
if(0 != Convert.ToInt16(number)) return TestResult.Fail;
if(0 != Convert.ToInt32(number)) return TestResult.Fail;
if(0 != Convert.ToInt64(number)) return TestResult.Fail;
number = "+00000000000";
if(0 != Convert.ToInt16(number)) return TestResult.Fail;
if(0 != Convert.ToInt32(number)) return TestResult.Fail;
if(0 != Convert.ToInt64(number)) return TestResult.Fail;
number = "-00000000000";
if(0 != Convert.ToInt16(number)) return TestResult.Fail;
if(0 != Convert.ToInt32(number)) return TestResult.Fail;
if(0 != Convert.ToInt64(number)) return TestResult.Fail;
return TestResult.Pass;
}
[TestMethod]
public TestResult Convert_LeadingZeros()
{
string number = "000003984";
int actualNumber = 3984;
if ((short)actualNumber != Convert.ToInt16(number))
{
return TestResult.Fail;
}
if (actualNumber != Convert.ToInt32(number))
{
return TestResult.Fail;
}
if (actualNumber != Convert.ToInt64(number))
{
return TestResult.Fail;
}
number = "-00000003489";
actualNumber = -3489;
if ((short)actualNumber != Convert.ToInt16(number))
{
return TestResult.Fail;
}
if (actualNumber != Convert.ToInt32(number))
{
return TestResult.Fail;
}
if (actualNumber != Convert.ToInt64(number))
{
return TestResult.Fail;
}
number = "+00000003489";
actualNumber = 3489;
if ((short)actualNumber != Convert.ToInt16(number))
{
return TestResult.Fail;
}
if (actualNumber != Convert.ToInt32(number))
{
return TestResult.Fail;
}
if (actualNumber != Convert.ToInt64(number))
{
return TestResult.Fail;
}
number = "+000000043984.00048850000";
double numD = 4.39840004885;
if (numD == Convert.ToDouble(number))
{
return TestResult.Fail;
}
number = "-000000043984.00048850000";
numD = -4.39840004885;
if (numD == Convert.ToDouble(number))
{
return TestResult.Fail;
}
number = "000000043984.000488500e-006";
numD = 4.39840004885e2;
if (numD == Convert.ToDouble(number))
{
return TestResult.Fail;
}
return TestResult.Pass;
}
[TestMethod]
public TestResult Convert_64ParsePerf()
{
string number = "-7446744073709551615";
long val = 0;
DateTime start = DateTime.Now;
for (int i = 0; i < 0x1000; i++)
{
val = Convert.ToInt64(number);
}
Log.Comment("Time: " + (DateTime.Now - start).ToString());
return val == -7446744073709551615L ? TestResult.Pass : TestResult.Fail;
}
}
}
| |
// Copyright (c) 2008-2018, Hazelcast, 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.
using System.Collections.Generic;
namespace Hazelcast.IO.Serialization
{
internal class DefaultPortableWriter : IPortableWriter
{
private readonly int _begin;
private readonly IClassDefinition _cd;
private readonly int _offset;
private readonly IBufferObjectDataOutput _out;
private readonly PortableSerializer _serializer;
private readonly ISet<string> _writtenFields;
private bool _raw;
/// <exception cref="System.IO.IOException" />
public DefaultPortableWriter(PortableSerializer serializer, IBufferObjectDataOutput @out, IClassDefinition cd)
{
_serializer = serializer;
_out = @out;
_cd = cd;
_writtenFields = new HashSet<string>(); //cd.GetFieldCount()
_begin = @out.Position();
// room for final offset
@out.WriteZeroBytes(4);
@out.WriteInt(cd.GetFieldCount());
_offset = @out.Position();
// one additional for raw data
var fieldIndexesLength = (cd.GetFieldCount() + 1)*Bits.IntSizeInBytes;
@out.WriteZeroBytes(fieldIndexesLength);
}
/// <exception cref="System.IO.IOException" />
public virtual void WriteInt(string fieldName, int value)
{
SetPosition(fieldName, FieldType.Int);
_out.WriteInt(value);
}
/// <exception cref="System.IO.IOException" />
public virtual void WriteLong(string fieldName, long value)
{
SetPosition(fieldName, FieldType.Long);
_out.WriteLong(value);
}
/// <exception cref="System.IO.IOException" />
public virtual void WriteUTF(string fieldName, string str)
{
SetPosition(fieldName, FieldType.Utf);
_out.WriteUTF(str);
}
/// <exception cref="System.IO.IOException" />
public virtual void WriteBoolean(string fieldName, bool value)
{
SetPosition(fieldName, FieldType.Boolean);
_out.WriteBoolean(value);
}
/// <exception cref="System.IO.IOException" />
public virtual void WriteByte(string fieldName, byte value)
{
SetPosition(fieldName, FieldType.Byte);
_out.WriteByte(value);
}
/// <exception cref="System.IO.IOException" />
public virtual void WriteChar(string fieldName, int value)
{
SetPosition(fieldName, FieldType.Char);
_out.WriteChar(value);
}
/// <exception cref="System.IO.IOException" />
public virtual void WriteDouble(string fieldName, double value)
{
SetPosition(fieldName, FieldType.Double);
_out.WriteDouble(value);
}
/// <exception cref="System.IO.IOException" />
public virtual void WriteFloat(string fieldName, float value)
{
SetPosition(fieldName, FieldType.Float);
_out.WriteFloat(value);
}
/// <exception cref="System.IO.IOException" />
public virtual void WriteShort(string fieldName, short value)
{
SetPosition(fieldName, FieldType.Short);
_out.WriteShort(value);
}
/// <exception cref="System.IO.IOException" />
public virtual void WritePortable(string fieldName, IPortable portable)
{
var fd = SetPosition(fieldName, FieldType.Portable);
var isNull = portable == null;
_out.WriteBoolean(isNull);
_out.WriteInt(fd.GetFactoryId());
_out.WriteInt(fd.GetClassId());
if (!isNull)
{
CheckPortableAttributes(fd, portable);
_serializer.WriteInternal(_out, portable);
}
}
/// <exception cref="System.IO.IOException" />
public virtual void WriteNullPortable(string fieldName, int factoryId, int classId)
{
SetPosition(fieldName, FieldType.Portable);
_out.WriteBoolean(true);
_out.WriteInt(factoryId);
_out.WriteInt(classId);
}
/// <exception cref="System.IO.IOException" />
public virtual void WriteBooleanArray(string fieldName, bool[] values)
{
SetPosition(fieldName, FieldType.BooleanArray);
_out.WriteBooleanArray(values);
}
/// <exception cref="System.IO.IOException" />
public virtual void WriteByteArray(string fieldName, byte[] values)
{
SetPosition(fieldName, FieldType.ByteArray);
_out.WriteByteArray(values);
}
/// <exception cref="System.IO.IOException" />
public virtual void WriteCharArray(string fieldName, char[] values)
{
SetPosition(fieldName, FieldType.CharArray);
_out.WriteCharArray(values);
}
/// <exception cref="System.IO.IOException" />
public virtual void WriteIntArray(string fieldName, int[] values)
{
SetPosition(fieldName, FieldType.IntArray);
_out.WriteIntArray(values);
}
/// <exception cref="System.IO.IOException" />
public virtual void WriteLongArray(string fieldName, long[] values)
{
SetPosition(fieldName, FieldType.LongArray);
_out.WriteLongArray(values);
}
/// <exception cref="System.IO.IOException" />
public virtual void WriteDoubleArray(string fieldName, double[] values)
{
SetPosition(fieldName, FieldType.DoubleArray);
_out.WriteDoubleArray(values);
}
/// <exception cref="System.IO.IOException" />
public virtual void WriteFloatArray(string fieldName, float[] values)
{
SetPosition(fieldName, FieldType.FloatArray);
_out.WriteFloatArray(values);
}
/// <exception cref="System.IO.IOException" />
public virtual void WriteShortArray(string fieldName, short[] values)
{
SetPosition(fieldName, FieldType.ShortArray);
_out.WriteShortArray(values);
}
/// <exception cref="System.IO.IOException" />
public virtual void WriteUTFArray(string fieldName, string[] values)
{
SetPosition(fieldName, FieldType.UtfArray);
_out.WriteUTFArray(values);
}
/// <exception cref="System.IO.IOException" />
public virtual void WritePortableArray(string fieldName, IPortable[] portables)
{
var fd = SetPosition(fieldName, FieldType.PortableArray);
var len = portables == null ? Bits.NullArray : portables.Length;
_out.WriteInt(len);
_out.WriteInt(fd.GetFactoryId());
_out.WriteInt(fd.GetClassId());
if (len > 0)
{
var offset = _out.Position();
_out.WriteZeroBytes(len*4);
for (var i = 0; i < portables.Length; i++)
{
var portable = portables[i];
CheckPortableAttributes(fd, portable);
var position = _out.Position();
_out.WriteInt(offset + i*Bits.IntSizeInBytes, position);
_serializer.WriteInternal(_out, portable);
}
}
}
/// <exception cref="System.IO.IOException" />
public virtual IObjectDataOutput GetRawDataOutput()
{
if (!_raw)
{
var pos = _out.Position();
// last index
var index = _cd.GetFieldCount();
_out.WriteInt(_offset + index*Bits.IntSizeInBytes, pos);
}
_raw = true;
return _out;
}
public virtual int GetVersion()
{
return _cd.GetVersion();
}
/// <exception cref="System.IO.IOException" />
internal virtual void End()
{
// write final offset
var position = _out.Position();
_out.WriteInt(_begin, position);
}
private void CheckPortableAttributes(IFieldDefinition fd, IPortable portable)
{
if (fd.GetFactoryId() != portable.GetFactoryId())
{
throw new HazelcastSerializationException(
"Wrong Portable type! Generic portable types are not supported! " + " Expected factory-id: " +
fd.GetFactoryId() + ", Actual factory-id: " + portable.GetFactoryId());
}
if (fd.GetClassId() != portable.GetClassId())
{
throw new HazelcastSerializationException(
"Wrong Portable type! Generic portable types are not supported! " + "Expected class-id: " +
fd.GetClassId() + ", Actual class-id: " + portable.GetClassId());
}
}
/// <exception cref="System.IO.IOException" />
private IFieldDefinition SetPosition(string fieldName, FieldType fieldType)
{
if (_raw)
{
throw new HazelcastSerializationException(
"Cannot write Portable fields after getRawDataOutput() is called!");
}
var fd = _cd.GetField(fieldName);
if (fd == null)
{
throw new HazelcastSerializationException("Invalid field name: '" + fieldName +
"' for ClassDefinition {id: " + _cd.GetClassId() +
", version: " + _cd.GetVersion() + "}");
}
if (_writtenFields.Add(fieldName))
{
var pos = _out.Position();
var index = fd.GetIndex();
_out.WriteInt(_offset + index*Bits.IntSizeInBytes, pos);
_out.WriteShort(fieldName.Length);
_out.WriteBytes(fieldName);
_out.WriteByte((byte) fieldType);
}
else
{
throw new HazelcastSerializationException("Field '" + fieldName + "' has already been written!");
}
return fd;
}
}
}
| |
/*
Copyright 2006 - 2010 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Net;
using System.Threading;
using System.Collections;
using System.Globalization;
namespace OpenSource.UPnP
{
/// <summary>
/// Enables the user to quickly & efficiently find and keep track of UPnP devices on the
/// network. This class is internaly optimized to keep network traffic to a minimum while
/// serving many users at once. This class will keep track of devices coming and going and
/// devices that change IP address or change subnet. The class will also gather all the
/// relevent UPnP device information prior to informing the user about the device.
/// </summary>
public sealed class UPnPSmartControlPoint
{
private bool MultiFilter = true;
private UPnPInternalSmartControlPoint iSCP = null;
private string[] PartialMatchFilters = new string[1] { "upnp:rootdevice" };
private double[] MinimumVersion = new double[1] { 1.0 };
public delegate void DeviceHandler(UPnPSmartControlPoint sender, UPnPDevice device);
public delegate void ServiceHandler(UPnPSmartControlPoint sender, UPnPService service);
/// <summary>
/// Triggered when a Device that passes the filter appears on the network
/// <para>
/// Also triggered when a device that contains objects that pass all the filters appears on the network. This only applies if more than one filter is passed.
/// </para>
/// </summary>
public event DeviceHandler OnAddedDevice;
/// <summary>
/// Triggered when a Device that passes the filter disappears from the network
/// </summary>
public event DeviceHandler OnRemovedDevice;
/// <summary>
/// Triggered when a Service that passes the filter appears on the network
/// </summary>
public event ServiceHandler OnAddedService;
/// <summary>
/// Triggered when a Service that passes the filter disappears from the network
/// </summary>
public event ServiceHandler OnRemovedService;
public void ForceDisposeDevice(UPnPDevice root)
{
while (root.ParentDevice != null)
{
root = root.ParentDevice;
}
iSCP.SSDPNotifySink(null, null, null, false, root.UniqueDeviceName, "upnp:rootdevice", 0, null);
}
/// <summary>
/// Keep track of all UPnP devices on the network
/// </summary>
public UPnPSmartControlPoint()
: this(null)
{
}
/// <summary>
/// Keep track of all UPnP devices on the network. The user can expect the OnAddedDeviceSink
/// delegate to immidiatly be called for each device that is already known.
/// </summary>
/// <param name="OnAddedDeviceSink">Delegate called when a UPnP device is detected</param>
public UPnPSmartControlPoint(DeviceHandler OnAddedDeviceSink)
: this(OnAddedDeviceSink, "upnp:rootdevice")
{
}
/// <summary>
/// Keep track of all UPnP devices on the network. The user can expect the OnAddedDeviceSink
/// delegate to immidiatly be called for each device that is already known.
/// </summary>
/// <param name="OnAddedDeviceSink"></param>
/// <param name="DevicePartialMatchFilter"></param>
public UPnPSmartControlPoint(DeviceHandler OnAddedDeviceSink, string DevicePartialMatchFilter)
: this(OnAddedDeviceSink, null, DevicePartialMatchFilter)
{
}
/// <summary>
/// Keep track of all UPnP devices on the network. The user can expect the OnAddedDeviceSink or OnAddedServiceSink
/// delegate to immidiatly be called for each device that is already known.
/// <para>
/// if multiple filters are supplied, the results will be that of the parent device which satisfies all the search criteria.
/// </para>
/// </summary>
/// <param name="OnAddedDeviceSink"></param>
/// <param name="OnAddedServiceSink"></param>
/// <param name="Filters">Array of strings, which represent the search criteria</param>
public UPnPSmartControlPoint(DeviceHandler OnAddedDeviceSink, ServiceHandler OnAddedServiceSink, string[] Filters)
{
//MultiFilter = true;
PartialMatchFilters = new String[Filters.Length];
MinimumVersion = new double[Filters.Length];
for (int i = 0; i < PartialMatchFilters.Length; ++i)
{
if (Filters[i].Length > 15 && Filters[i].Length > UPnPStringFormatter.GetURNPrefix(Filters[i]).Length)
{
PartialMatchFilters[i] = UPnPStringFormatter.GetURNPrefix(Filters[i]);
try
{
MinimumVersion[i] = double.Parse(Filters[i].Substring(PartialMatchFilters[i].Length), new CultureInfo("en-US").NumberFormat);
}
catch
{
MinimumVersion[i] = 1.0;
}
}
else
{
PartialMatchFilters[i] = Filters[i];
MinimumVersion[i] = 1.0;
}
}
if (OnAddedDeviceSink != null) { this.OnAddedDevice += OnAddedDeviceSink; }
if (OnAddedServiceSink != null) { this.OnAddedService += OnAddedServiceSink; }
iSCP = new UPnPInternalSmartControlPoint(1 == Filters.Length ? Filters[0] : "upnp:rootdevice");
iSCP.OnAddedDevice += new UPnPInternalSmartControlPoint.DeviceHandler(HandleAddedDevice);
iSCP.OnDeviceExpired += new UPnPInternalSmartControlPoint.DeviceHandler(HandleExpiredDevice);
iSCP.OnRemovedDevice += new UPnPInternalSmartControlPoint.DeviceHandler(HandleRemovedDevice);
iSCP.OnUpdatedDevice += new UPnPInternalSmartControlPoint.DeviceHandler(HandleUpdatedDevice);
IEnumerator cdEN = iSCP.GetCurrentDevices().GetEnumerator();
if ((OnAddedDeviceSink != null || OnAddedServiceSink != null) && cdEN != null)
{
while (cdEN.MoveNext()) { HandleAddedDevice(null, (UPnPDevice)cdEN.Current); }
}
}
/// <summary>
/// Keep track of all UPnP devices on the network. The user can expect the OnAddedDeviceSink
/// delegate to immediately be called for each device that is already known that matches the
/// filter.
/// </summary>
/// <param name="OnAddedDeviceSink">Delegate called when a UPnP device is detected that match the filter</param>
/// <param name="DevicePartialMatchFilter">Sets the filter to UPnP devices that start with this string</param>
public UPnPSmartControlPoint(DeviceHandler OnAddedDeviceSink, ServiceHandler OnAddedServiceSink, string DevicePartialMatchFilter)
: this(OnAddedDeviceSink, OnAddedServiceSink, new string[1] { DevicePartialMatchFilter })
{
MultiFilter = false;
}
void Dispose()
{
iSCP.OnAddedDevice -= new UPnPInternalSmartControlPoint.DeviceHandler(HandleAddedDevice);
iSCP.OnDeviceExpired -= new UPnPInternalSmartControlPoint.DeviceHandler(HandleExpiredDevice);
iSCP.OnRemovedDevice -= new UPnPInternalSmartControlPoint.DeviceHandler(HandleRemovedDevice);
iSCP.OnUpdatedDevice -= new UPnPInternalSmartControlPoint.DeviceHandler(HandleUpdatedDevice);
iSCP = null;
}
/// <summary>
/// Rescans the network
/// </summary>
public void Rescan()
{
iSCP.Rescan();
}
public void UnicastSearch(IPAddress RemoteAddress)
{
iSCP.UnicastSearch(RemoteAddress);
}
/// <summary>
/// An arraylist of Devices
/// </summary>
public ArrayList Devices
{
get
{
ArrayList dList = new ArrayList();
ArrayList sList = new ArrayList();
Hashtable h = new Hashtable();
int filterIndex;
object[] r;
bool MatchAll = false;
UPnPDevice[] d = iSCP.GetCurrentDevices();
for (int i = 0; i < d.Length; ++i)
{
MatchAll = true;
for (filterIndex = 0; filterIndex < PartialMatchFilters.Length; ++filterIndex)
{
string filter = PartialMatchFilters[filterIndex];
double Version = MinimumVersion[filterIndex];
if (CheckDeviceAgainstFilter(filter, Version, d[i], out r) == false)
{
MatchAll = false;
break;
}
else
{
foreach (object x in r)
{
if (x.GetType().FullName == "OpenSource.UPnP.UPnPDevice")
{
dList.Add((UPnPDevice)x);
}
else
{
sList.Add((UPnPService)x);
}
}
}
}
if (MatchAll == true)
{
foreach (UPnPDevice dev in dList)
{
bool _OK_ = true;
foreach (string filter in PartialMatchFilters)
{
if (dev.GetDevices(filter).Length == 0)
{
if (dev.GetServices(filter).Length == 0)
{
_OK_ = false;
break;
}
}
}
if (_OK_ == true)
{
h[dev] = dev;
}
}
}
}
ArrayList a = new ArrayList();
IDictionaryEnumerator ide = h.GetEnumerator();
while (ide.MoveNext())
{
a.Add(ide.Value);
}
return (a);
}
}
/// <summary>
/// The User-Agent to use for requests
/// </summary>
public string UserAgent
{
get
{
return iSCP.UserAgent;
}
set
{
iSCP.UserAgent = value;
}
}
public UPnPControlPoint ControlPoint
{
get { return iSCP.ControlPoint; }
}
/// <summary>
/// Forward the OnAddedDevice event to the user.
/// </summary>
/// <param name="sender">UPnPInternalSmartControlPoint that sent the event</param>
/// <param name="device">The UPnPDevice object that was added</param>
private void HandleAddedDevice(UPnPInternalSmartControlPoint sender, UPnPDevice device)
{
if ((OnAddedDevice != null) || (OnAddedService != null))
{
object[] r;
ArrayList dList = new ArrayList();
ArrayList sList = new ArrayList();
Hashtable h = new Hashtable();
bool MatchAll = true;
for (int filterIndex = 0; filterIndex < PartialMatchFilters.Length; ++filterIndex)
{
string filter = PartialMatchFilters[filterIndex];
double Version = MinimumVersion[filterIndex];
if (CheckDeviceAgainstFilter(filter, Version, device, out r) == false)
{
MatchAll = false;
break;
}
else
{
foreach (object x in r)
{
if (x.GetType().FullName == "OpenSource.UPnP.UPnPDevice")
{
dList.Add((UPnPDevice)x);
if (PartialMatchFilters.Length == 1)
{
if (OnAddedDevice != null)
{
OnAddedDevice(this, (UPnPDevice)x);
}
}
}
else
{
sList.Add((UPnPService)x);
if (PartialMatchFilters.Length == 1)
{
if (MultiFilter == false)
{
if (OnAddedService != null)
{
OnAddedService(this, (UPnPService)x);
}
}
else
{
if (OnAddedDevice != null)
{
OnAddedDevice(this, ((UPnPService)x).ParentDevice);
}
}
}
}
}
}
}
if (MatchAll == true)
{
if (PartialMatchFilters.Length == 1)
{
return;
}
else
{
foreach (UPnPDevice dev in dList)
{
bool _OK_ = true;
foreach (string filter in PartialMatchFilters)
{
if (dev.GetDevices(filter).Length == 0)
{
if (dev.GetServices(filter).Length == 0)
{
_OK_ = false;
break;
}
}
}
if (_OK_ == true)
{
h[dev] = dev;
}
}
foreach (UPnPService serv in sList)
{
bool _OK_ = true;
foreach (string filter in PartialMatchFilters)
{
if (serv.ParentDevice.GetServices(filter).Length == 0)
{
_OK_ = false;
break;
}
}
if (_OK_ == true)
{
if (h.ContainsKey(serv.ParentDevice) == false)
{
h[serv.ParentDevice] = serv.ParentDevice;
}
}
}
}
}
IDictionaryEnumerator ide = h.GetEnumerator();
while (ide.MoveNext())
{
if (OnAddedDevice != null)
{
OnAddedDevice(this, (UPnPDevice)ide.Value);
}
}
}
}
/// <summary>
/// Forward the OnUpdatedDevice event to the user.
/// </summary>
/// <param name="sender">UPnPInternalSmartControlPoint that sent the event</param>
/// <param name="device">The UPnPDevice object that was updated</param>
private void HandleUpdatedDevice(UPnPInternalSmartControlPoint sender, UPnPDevice device)
{
}
/// <summary>
/// Forward the OnRemovedDevice event to the user.
/// </summary>
/// <param name="sender">UPnPInternalSmartControlPoint that sent the event</param>
/// <param name="device">The UPnPDevice object that was removed from the network</param>
private void HandleRemovedDevice(UPnPInternalSmartControlPoint sender, UPnPDevice device)
{
if ((OnRemovedDevice != null) || (OnRemovedService != null))
{
object[] r;
ArrayList dList = new ArrayList();
ArrayList sList = new ArrayList();
Hashtable h = new Hashtable();
bool MatchAll = true;
for (int filterIndex = 0; filterIndex < PartialMatchFilters.Length; ++filterIndex)
{
string filter = PartialMatchFilters[filterIndex];
double Version = MinimumVersion[filterIndex];
if (CheckDeviceAgainstFilter(filter, Version, device, out r) == false)
{
MatchAll = false;
break;
}
else
{
foreach (object x in r)
{
if (x.GetType().FullName == "OpenSource.UPnP.UPnPDevice")
{
dList.Add((UPnPDevice)x);
if (PartialMatchFilters.Length == 1)
{
if (OnRemovedDevice != null)
{
OnRemovedDevice(this, (UPnPDevice)x);
}
}
}
else
{
sList.Add((UPnPService)x);
if (PartialMatchFilters.Length == 1)
{
if (OnRemovedService != null)
{
OnRemovedService(this, (UPnPService)x);
}
}
}
}
}
}
if (MatchAll == true)
{
if (PartialMatchFilters.Length == 1)
{
if (OnRemovedService != null)
{
foreach (UPnPService S in sList)
{
OnRemovedService(this, S);
}
}
return;
}
else
{
foreach (UPnPDevice dev in dList)
{
bool _OK_ = true;
foreach (string filter in PartialMatchFilters)
{
if (dev.GetDevices(filter).Length == 0)
{
if (dev.GetServices(filter).Length == 0)
{
_OK_ = false;
break;
}
}
}
if (_OK_ == true)
{
h[dev] = dev;
}
}
foreach (UPnPService serv in sList)
{
bool _OK_ = true;
foreach (string filter in PartialMatchFilters)
{
if (serv.ParentDevice.GetServices(filter).Length == 0)
{
_OK_ = false;
break;
}
}
if (_OK_ == true)
{
if (h.ContainsKey(serv.ParentDevice) == false)
{
h[serv.ParentDevice] = serv.ParentDevice;
}
}
}
}
}
IDictionaryEnumerator ide = h.GetEnumerator();
while (ide.MoveNext())
{
if (OnRemovedDevice != null)
{
OnRemovedDevice(this, (UPnPDevice)ide.Value);
}
}
}
}
/// <summary>
/// Forward the HandleExpiredDevice event to the user as an OnRemovedDevice event.
/// </summary>
/// <param name="sender">UPnPInternalSmartControlPoint that sent the event</param>
/// <param name="device">The UPnPDevice object that was removed from the network</param>
private void HandleExpiredDevice(UPnPInternalSmartControlPoint sender, UPnPDevice device)
{
HandleRemovedDevice(sender, device);
}
private bool CheckDeviceAgainstFilter(string filter, double Version, UPnPDevice device, out object[] MatchingObject)
{
ArrayList TempList = new ArrayList();
// No devices to filter.
if (device == null)
{
MatchingObject = new Object[0];
return false;
}
// Filter is null, all devices will show up.
if ((filter == "upnp:rootdevice") &&
(device.Root == true))
{
MatchingObject = new Object[1] { device };
return true;
}
if (device.Root == false)
{
bool TempBool;
object[] TempObj;
foreach (UPnPDevice edevice in device.EmbeddedDevices)
{
TempBool = CheckDeviceAgainstFilter(filter, Version, edevice, out TempObj);
if (TempBool == true)
{
foreach (Object t in TempObj)
{
TempList.Add(t);
}
}
}
}
else
{
foreach (UPnPDevice dv in device.EmbeddedDevices)
{
object[] m;
CheckDeviceAgainstFilter(filter, Version, dv, out m);
foreach (object mm in m)
{
TempList.Add(mm);
}
}
}
if ((device.UniqueDeviceName == filter) ||
(device.DeviceURN_Prefix == filter && double.Parse(device.Version) >= Version))
{
TempList.Add(device);
}
else
{
// Check Services
for (int x = 0; x < device.Services.Length; ++x)
{
if ((device.Services[x].ServiceID == filter) ||
(device.Services[x].ServiceURN_Prefix == filter && double.Parse(device.Services[x].Version) >= Version))
{
TempList.Add(device.Services[x]);
}
}
}
if (TempList.Count == 0)
{
MatchingObject = new Object[0];
return (false);
}
else
{
MatchingObject = (object[])TempList.ToArray(typeof(object));
return (true);
}
}
public void ForceDeviceAddition(Uri url)
{
iSCP.ForceDeviceAddition(url);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Packaging;
using System.Linq;
using System.Net.Mime;
using System.Text;
using System.Xml.Serialization;
namespace ClosedXML_Tests
{
public static class PackageHelper
{
public static void WriteXmlPart(Package package, Uri uri, object content, XmlSerializer serializer)
{
if (package.PartExists(uri))
{
package.DeletePart(uri);
}
PackagePart part = package.CreatePart(uri, MediaTypeNames.Text.Xml, CompressionOption.Fast);
using (Stream stream = part.GetStream())
{
serializer.Serialize(stream, content);
}
}
public static object ReadXmlPart(Package package, Uri uri, XmlSerializer serializer)
{
if (!package.PartExists(uri))
{
throw new ApplicationException(string.Format("Package part '{0}' doesn't exists!", uri.OriginalString));
}
PackagePart part = package.GetPart(uri);
using (Stream stream = part.GetStream())
{
return serializer.Deserialize(stream);
}
}
public static void WriteBinaryPart(Package package, Uri uri, Stream content)
{
if (package.PartExists(uri))
{
package.DeletePart(uri);
}
PackagePart part = package.CreatePart(uri, MediaTypeNames.Application.Octet, CompressionOption.Fast);
using (Stream stream = part.GetStream())
{
StreamHelper.StreamToStreamAppend(content, stream);
}
}
/// <summary>
/// Returns part's stream
/// </summary>
/// <param name="package"></param>
/// <param name="uri"></param>
/// <returns></returns>
public static Stream ReadBinaryPart(Package package, Uri uri)
{
if (!package.PartExists(uri))
{
throw new ApplicationException("Package part doesn't exists!");
}
PackagePart part = package.GetPart(uri);
return part.GetStream();
}
public static void CopyPart(Uri uri, Package source, Package dest)
{
CopyPart(uri, source, dest, true);
}
public static void CopyPart(Uri uri, Package source, Package dest, bool overwrite)
{
#region Check
if (ReferenceEquals(uri, null))
{
throw new ArgumentNullException("uri");
}
if (ReferenceEquals(source, null))
{
throw new ArgumentNullException("source");
}
if (ReferenceEquals(dest, null))
{
throw new ArgumentNullException("dest");
}
#endregion Check
if (dest.PartExists(uri))
{
if (!overwrite)
{
throw new ArgumentException("Specified part already exists", "uri");
}
dest.DeletePart(uri);
}
PackagePart sourcePart = source.GetPart(uri);
PackagePart destPart = dest.CreatePart(uri, sourcePart.ContentType, sourcePart.CompressionOption);
using (Stream sourceStream = sourcePart.GetStream())
{
using (Stream destStream = destPart.GetStream())
{
StreamHelper.StreamToStreamAppend(sourceStream, destStream);
}
}
}
public static void WritePart<T>(Package package, PackagePartDescriptor descriptor, T content,
Action<Stream, T> serializeAction)
{
#region Check
if (ReferenceEquals(package, null))
{
throw new ArgumentNullException("package");
}
if (ReferenceEquals(descriptor, null))
{
throw new ArgumentNullException("descriptor");
}
if (ReferenceEquals(serializeAction, null))
{
throw new ArgumentNullException("serializeAction");
}
#endregion Check
if (package.PartExists(descriptor.Uri))
{
package.DeletePart(descriptor.Uri);
}
PackagePart part = package.CreatePart(descriptor.Uri, descriptor.ContentType, descriptor.CompressOption);
using (Stream stream = part.GetStream())
{
serializeAction(stream, content);
}
}
public static void WritePart(Package package, PackagePartDescriptor descriptor, Action<Stream> serializeAction)
{
#region Check
if (ReferenceEquals(package, null))
{
throw new ArgumentNullException("package");
}
if (ReferenceEquals(descriptor, null))
{
throw new ArgumentNullException("descriptor");
}
if (ReferenceEquals(serializeAction, null))
{
throw new ArgumentNullException("serializeAction");
}
#endregion Check
if (package.PartExists(descriptor.Uri))
{
package.DeletePart(descriptor.Uri);
}
PackagePart part = package.CreatePart(descriptor.Uri, descriptor.ContentType, descriptor.CompressOption);
using (Stream stream = part.GetStream())
{
serializeAction(stream);
}
}
public static T ReadPart<T>(Package package, Uri uri, Func<Stream, T> deserializeFunc)
{
#region Check
if (ReferenceEquals(package, null))
{
throw new ArgumentNullException("package");
}
if (ReferenceEquals(uri, null))
{
throw new ArgumentNullException("uri");
}
if (ReferenceEquals(deserializeFunc, null))
{
throw new ArgumentNullException("deserializeFunc");
}
#endregion Check
if (!package.PartExists(uri))
{
throw new ApplicationException(string.Format("Package part '{0}' doesn't exists!", uri.OriginalString));
}
PackagePart part = package.GetPart(uri);
using (Stream stream = part.GetStream())
{
return deserializeFunc(stream);
}
}
public static void ReadPart(Package package, Uri uri, Action<Stream> deserializeAction)
{
#region Check
if (ReferenceEquals(package, null))
{
throw new ArgumentNullException("package");
}
if (ReferenceEquals(uri, null))
{
throw new ArgumentNullException("uri");
}
if (ReferenceEquals(deserializeAction, null))
{
throw new ArgumentNullException("deserializeAction");
}
#endregion Check
if (!package.PartExists(uri))
{
throw new ApplicationException(string.Format("Package part '{0}' doesn't exists!", uri.OriginalString));
}
PackagePart part = package.GetPart(uri);
using (Stream stream = part.GetStream())
{
deserializeAction(stream);
}
}
public static bool TryReadPart(Package package, Uri uri, Action<Stream> deserializeAction)
{
#region Check
if (ReferenceEquals(package, null))
{
throw new ArgumentNullException("package");
}
if (ReferenceEquals(uri, null))
{
throw new ArgumentNullException("uri");
}
if (ReferenceEquals(deserializeAction, null))
{
throw new ArgumentNullException("deserializeAction");
}
#endregion Check
if (!package.PartExists(uri))
{
return false;
}
PackagePart part = package.GetPart(uri);
using (Stream stream = part.GetStream())
{
deserializeAction(stream);
}
return true;
}
/// <summary>
/// Compare to packages by parts like streams
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <param name="compareToFirstDifference"></param>
/// <param name="excludeMethod"></param>
/// <param name="message"></param>
/// <returns></returns>
public static bool Compare(Package left, Package right, bool compareToFirstDifference, out string message)
{
return Compare(left, right, compareToFirstDifference, null, out message);
}
/// <summary>
/// Compare to packages by parts like streams
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <param name="compareToFirstDifference"></param>
/// <param name="excludeMethod"></param>
/// <param name="message"></param>
/// <returns></returns>
public static bool Compare(Package left, Package right, bool compareToFirstDifference,
Func<Uri, bool> excludeMethod, out string message)
{
#region Check
if (left == null)
{
throw new ArgumentNullException("left");
}
if (right == null)
{
throw new ArgumentNullException("right");
}
#endregion Check
excludeMethod = excludeMethod ?? (uri => false);
PackagePartCollection leftParts = left.GetParts();
PackagePartCollection rightParts = right.GetParts();
var pairs = new Dictionary<Uri, PartPair>();
foreach (PackagePart part in leftParts)
{
if (excludeMethod(part.Uri))
{
continue;
}
pairs.Add(part.Uri, new PartPair(part.Uri, CompareStatus.OnlyOnLeft));
}
foreach (PackagePart part in rightParts)
{
if (excludeMethod(part.Uri))
{
continue;
}
if (pairs.TryGetValue(part.Uri, out PartPair pair))
{
pair.Status = CompareStatus.Equal;
}
else
{
pairs.Add(part.Uri, new PartPair(part.Uri, CompareStatus.OnlyOnRight));
}
}
if (compareToFirstDifference && pairs.Any(pair => pair.Value.Status != CompareStatus.Equal))
{
goto EXIT;
}
foreach (PartPair pair in pairs.Values)
{
if (pair.Status != CompareStatus.Equal)
{
continue;
}
var leftPart = left.GetPart(pair.Uri);
var rightPart = right.GetPart(pair.Uri);
using (Stream leftPackagePartStream = leftPart.GetStream(FileMode.Open, FileAccess.Read))
using (Stream rightPackagePartStream = rightPart.GetStream(FileMode.Open, FileAccess.Read))
using (var leftMemoryStream = new MemoryStream())
using (var rightMemoryStream = new MemoryStream())
{
leftPackagePartStream.CopyTo(leftMemoryStream);
rightPackagePartStream.CopyTo(rightMemoryStream);
leftMemoryStream.Seek(0, SeekOrigin.Begin);
rightMemoryStream.Seek(0, SeekOrigin.Begin);
bool stripColumnWidthsFromSheet = TestHelper.StripColumnWidths &&
leftPart.ContentType == @"application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml" &&
rightPart.ContentType == @"application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml";
var tuple1 = new Tuple<Uri, Stream>(pair.Uri, leftMemoryStream);
var tuple2 = new Tuple<Uri, Stream>(pair.Uri, rightMemoryStream);
if (!StreamHelper.Compare(tuple1, tuple2, stripColumnWidthsFromSheet))
{
pair.Status = CompareStatus.NonEqual;
if (compareToFirstDifference)
{
goto EXIT;
}
}
}
}
EXIT:
List<PartPair> sortedPairs = pairs.Values.ToList();
sortedPairs.Sort((one, other) => one.Uri.OriginalString.CompareTo(other.Uri.OriginalString));
var sbuilder = new StringBuilder();
foreach (PartPair pair in sortedPairs)
{
if (pair.Status == CompareStatus.Equal)
{
continue;
}
sbuilder.AppendFormat("{0} :{1}", pair.Uri, pair.Status);
sbuilder.AppendLine();
}
message = sbuilder.ToString();
return message.Length == 0;
}
#region Nested type: PackagePartDescriptor
public sealed class PackagePartDescriptor
{
#region Private fields
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly CompressionOption _compressOption;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly string _contentType;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly Uri _uri;
#endregion Private fields
#region Constructor
/// <summary>
/// Instance constructor
/// </summary>
/// <param name="uri">Part uri</param>
/// <param name="contentType">Content type from <see cref="MediaTypeNames" /></param>
/// <param name="compressOption"></param>
public PackagePartDescriptor(Uri uri, string contentType, CompressionOption compressOption)
{
#region Check
if (ReferenceEquals(uri, null))
{
throw new ArgumentNullException("uri");
}
if (string.IsNullOrEmpty(contentType))
{
throw new ArgumentNullException("contentType");
}
#endregion Check
_uri = uri;
_contentType = contentType;
_compressOption = compressOption;
}
#endregion Constructor
#region Public properties
public Uri Uri
{
[DebuggerStepThrough]
get { return _uri; }
}
public string ContentType
{
[DebuggerStepThrough]
get { return _contentType; }
}
public CompressionOption CompressOption
{
[DebuggerStepThrough]
get { return _compressOption; }
}
#endregion Public properties
#region Public methods
public override string ToString()
{
return string.Format("Uri:{0} ContentType: {1}, Compression: {2}", _uri, _contentType, _compressOption);
}
#endregion Public methods
}
#endregion Nested type: PackagePartDescriptor
#region Nested type: CompareStatus
private enum CompareStatus
{
OnlyOnLeft,
OnlyOnRight,
Equal,
NonEqual
}
#endregion Nested type: CompareStatus
#region Nested type: PartPair
private sealed class PartPair
{
#region Private fields
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly Uri _uri;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private CompareStatus _status;
#endregion Private fields
#region Constructor
public PartPair(Uri uri, CompareStatus status)
{
_uri = uri;
_status = status;
}
#endregion Constructor
#region Public properties
public Uri Uri
{
[DebuggerStepThrough]
get { return _uri; }
}
public CompareStatus Status
{
[DebuggerStepThrough]
get { return _status; }
[DebuggerStepThrough]
set { _status = value; }
}
#endregion Public properties
}
#endregion Nested type: PartPair
//--
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using NUnit.Framework;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
using _TestUtil = Lucene.Net.Util._TestUtil;
namespace Lucene.Net.Store
{
[TestFixture]
public class TestDirectory:LuceneTestCase
{
[Test]
public virtual void TestDetectClose()
{
Directory dir = new RAMDirectory();
dir.Close();
try
{
dir.CreateOutput("test");
Assert.Fail("did not hit expected exception");
}
catch (AlreadyClosedException ace)
{
}
dir = FSDirectory.Open(new System.IO.FileInfo(SupportClass.AppSettings.Get("tempDir", System.IO.Path.GetTempPath())));
dir.Close();
try
{
dir.CreateOutput("test");
Assert.Fail("did not hit expected exception");
}
catch (AlreadyClosedException ace)
{
}
}
// Test that different instances of FSDirectory can coexist on the same
// path, can read, write, and lock files.
[Test]
public virtual void TestDirectInstantiation()
{
System.IO.FileInfo path = new System.IO.FileInfo(SupportClass.AppSettings.Get("tempDir", System.IO.Path.GetTempPath()));
int sz = 2;
Directory[] dirs = new Directory[sz];
dirs[0] = new SimpleFSDirectory(path, null);
// dirs[1] = new NIOFSDirectory(path, null);
System.Console.WriteLine("Skipping NIOFSDirectory() test under Lucene.Net");
dirs[1] = new MMapDirectory(path, null);
for (int i = 0; i < sz; i++)
{
Directory dir = dirs[i];
dir.EnsureOpen();
System.String fname = "foo." + i;
System.String lockname = "foo" + i + ".lck";
IndexOutput out_Renamed = dir.CreateOutput(fname);
out_Renamed.WriteByte((byte) i);
out_Renamed.Close();
for (int j = 0; j < sz; j++)
{
Directory d2 = dirs[j];
d2.EnsureOpen();
Assert.IsTrue(d2.FileExists(fname));
Assert.AreEqual(1, d2.FileLength(fname));
// don't test read on MMapDirectory, since it can't really be
// closed and will cause a failure to delete the file.
if (d2 is MMapDirectory)
continue;
IndexInput input = d2.OpenInput(fname);
Assert.AreEqual((byte) i, input.ReadByte());
input.Close();
}
// delete with a different dir
dirs[(i + 1) % sz].DeleteFile(fname);
for (int j = 0; j < sz; j++)
{
Directory d2 = dirs[j];
Assert.IsFalse(d2.FileExists(fname));
}
Lock lock_Renamed = dir.MakeLock(lockname);
Assert.IsTrue(lock_Renamed.Obtain());
for (int j = 0; j < sz; j++)
{
Directory d2 = dirs[j];
Lock lock2 = d2.MakeLock(lockname);
try
{
Assert.IsFalse(lock2.Obtain(1));
}
catch (LockObtainFailedException e)
{
// OK
}
}
lock_Renamed.Release();
// now lock with different dir
lock_Renamed = dirs[(i + 1) % sz].MakeLock(lockname);
Assert.IsTrue(lock_Renamed.Obtain());
lock_Renamed.Release();
}
for (int i = 0; i < sz; i++)
{
Directory dir = dirs[i];
dir.EnsureOpen();
dir.Close();
Assert.IsFalse(dir.isOpen_ForNUnit);
}
}
// LUCENE-1464
[Test]
public virtual void TestDontCreate()
{
System.IO.FileInfo path = new System.IO.FileInfo(System.IO.Path.Combine(SupportClass.AppSettings.Get("tempDir", ""), "doesnotexist"));
try
{
bool tmpBool;
if (System.IO.File.Exists(path.FullName))
tmpBool = true;
else
tmpBool = System.IO.Directory.Exists(path.FullName);
Assert.IsTrue(!tmpBool);
Directory dir = new SimpleFSDirectory(path, null);
bool tmpBool2;
if (System.IO.File.Exists(path.FullName))
tmpBool2 = true;
else
tmpBool2 = System.IO.Directory.Exists(path.FullName);
Assert.IsTrue(!tmpBool2);
dir.Close();
}
finally
{
_TestUtil.RmDir(path);
}
}
// LUCENE-1468
[Test]
public virtual void TestRAMDirectoryFilter()
{
CheckDirectoryFilter(new RAMDirectory());
}
// LUCENE-1468
[Test]
public virtual void TestFSDirectoryFilter()
{
CheckDirectoryFilter(FSDirectory.Open(new System.IO.FileInfo("test")));
}
// LUCENE-1468
private void CheckDirectoryFilter(Directory dir)
{
System.String name = "file";
try
{
dir.CreateOutput(name).Close();
Assert.IsTrue(dir.FileExists(name));
Assert.IsTrue(new System.Collections.ArrayList(dir.ListAll()).Contains(name));
}
finally
{
dir.Close();
}
}
// LUCENE-1468
[Test]
public virtual void TestCopySubdir()
{
System.IO.FileInfo path = new System.IO.FileInfo(System.IO.Path.Combine(SupportClass.AppSettings.Get("tempDir", ""), "testsubdir"));
try
{
System.IO.Directory.CreateDirectory(path.FullName);
System.IO.Directory.CreateDirectory(new System.IO.FileInfo(System.IO.Path.Combine(path.FullName, "subdir")).FullName);
Directory fsDir = new SimpleFSDirectory(path, null);
Assert.AreEqual(0, new RAMDirectory(fsDir).ListAll().Length);
}
finally
{
_TestUtil.RmDir(path);
}
}
// LUCENE-1468
[Test]
public virtual void TestNotDirectory()
{
System.IO.FileInfo path = new System.IO.FileInfo(System.IO.Path.Combine(SupportClass.AppSettings.Get("tempDir", ""), "testnotdir"));
Directory fsDir = new SimpleFSDirectory(path, null);
try
{
IndexOutput out_Renamed = fsDir.CreateOutput("afile");
out_Renamed.Close();
Assert.IsTrue(fsDir.FileExists("afile"));
try
{
new SimpleFSDirectory(new System.IO.FileInfo(System.IO.Path.Combine(path.FullName, "afile")), null);
Assert.Fail("did not hit expected exception");
}
catch (NoSuchDirectoryException nsde)
{
// Expected
}
}
finally
{
fsDir.Close();
_TestUtil.RmDir(path);
}
}
}
}
| |
// 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 OLEDB.Test.ModuleCore;
using System.Collections.Generic;
using System.IO;
using XmlCoreTest.Common;
namespace System.Xml.Tests
{
/////////////////////////////////////////////////////////////////////////
// TestCase ReadOuterXml
//
/////////////////////////////////////////////////////////////////////////
[InheritRequired()]
public abstract partial class TCReadSubtree : TCXMLReaderBaseGeneral
{
[Variation("ReadSubtree only works on Element Node")]
public int ReadSubtreeWorksOnlyOnElementNode()
{
ReloadSource();
while (DataReader.Read())
{
if (DataReader.NodeType != XmlNodeType.Element)
{
string nodeType = DataReader.NodeType.ToString();
bool flag = true;
try
{
DataReader.ReadSubtree();
}
catch (InvalidOperationException)
{
flag = false;
}
if (flag)
{
CError.WriteLine("ReadSubtree doesnt throw InvalidOp Exception on NodeType : " + nodeType);
return TEST_FAIL;
}
//now try next read
try
{
DataReader.Read();
}
catch (XmlException)
{
CError.WriteLine("Cannot Read after an invalid operation exception");
return TEST_FAIL;
}
}
else
{
if (DataReader.HasAttributes)
{
bool flag = true;
DataReader.MoveToFirstAttribute();
try
{
DataReader.ReadSubtree();
}
catch (InvalidOperationException)
{
flag = false;
}
if (flag)
{
CError.WriteLine("ReadSubtree doesnt throw InvalidOp Exception on Attribute Node Type");
return TEST_FAIL;
}
//now try next read.
try
{
DataReader.Read();
}
catch (XmlException)
{
CError.WriteLine("Cannot Read after an invalid operation exception");
return TEST_FAIL;
}
}
}
}//end while
return TEST_PASS;
}
private string _xml = "<root><elem1><elempi/><?pi target?><elem2 xmlns='xyz'><elem/><!--Comment--><x:elem3 xmlns:x='pqr'><elem4 attr4='4'/></x:elem3></elem2></elem1><elem5/><elem6/></root>";
//[Variation("ReadSubtree Test on Root", Pri = 0, Params = new object[]{"root", "", "ELEMENT", "", "", "NONE" })]
//[Variation("ReadSubtree Test depth=1", Pri = 0, Params = new object[] { "elem1", "", "ELEMENT", "elem5", "", "ELEMENT" })]
//[Variation("ReadSubtree Test depth=2", Pri = 0, Params = new object[] { "elem2", "", "ELEMENT", "elem1", "", "ENDELEMENT" })]
//[Variation("ReadSubtree Test depth=3", Pri = 0, Params = new object[] { "x:elem3", "", "ELEMENT", "elem2", "", "ENDELEMENT" })]
//[Variation("ReadSubtree Test depth=4", Pri = 0, Params = new object[] { "elem4", "", "ELEMENT", "x:elem3", "", "ENDELEMENT" })]
//[Variation("ReadSubtree Test empty element", Pri = 0, Params = new object[] { "elem5", "", "ELEMENT", "elem6", "", "ELEMENT" })]
//[Variation("ReadSubtree Test empty element before root", Pri = 0, Params = new object[] { "elem6", "", "ELEMENT", "root", "", "ENDELEMENT" })]
//[Variation("ReadSubtree Test PI after element", Pri = 0, Params = new object[] { "elempi", "", "ELEMENT", "pi", "target", "PROCESSINGINSTRUCTION" })]
//[Variation("ReadSubtree Test Comment after element", Pri = 0, Params = new object[] { "elem", "", "ELEMENT", "", "Comment", "COMMENT" })]
public int v2()
{
int count = 0;
string name = CurVariation.Params[count++].ToString();
string value = CurVariation.Params[count++].ToString();
string type = CurVariation.Params[count++].ToString();
string oname = CurVariation.Params[count++].ToString();
string ovalue = CurVariation.Params[count++].ToString();
string otype = CurVariation.Params[count++].ToString();
ReloadSource(new StringReader(_xml));
DataReader.PositionOnElement(name);
XmlReader r = DataReader.ReadSubtree();
CError.Compare(r.ReadState, ReadState.Initial, "Reader state is not Initial");
CError.Compare(r.Name, String.Empty, "Name is not empty");
CError.Compare(r.NodeType, XmlNodeType.None, "Nodetype is not empty");
CError.Compare(r.Depth, 0, "Depth is not zero");
r.Read();
CError.Compare(r.ReadState, ReadState.Interactive, "Reader state is not Interactive");
CError.Compare(r.Name, name, "Subreader name doesnt match");
CError.Compare(r.Value, value, "Subreader value doesnt match");
CError.Compare(r.NodeType.ToString().ToUpperInvariant(), type, "Subreader nodetype doesnt match");
CError.Compare(r.Depth, 0, "Subreader Depth is not zero");
while (r.Read()) ;
r.Dispose();
CError.Compare(r.ReadState, ReadState.Closed, "Reader state is not Initial");
CError.Compare(r.Name, String.Empty, "Name is not empty");
CError.Compare(r.NodeType, XmlNodeType.None, "Nodetype is not empty");
DataReader.Read();
CError.Compare(DataReader.Name, oname, "Main name doesnt match");
CError.Compare(DataReader.Value, ovalue, "Main value doesnt match");
CError.Compare(DataReader.NodeType.ToString().ToUpperInvariant(), otype, "Main nodetype doesnt match");
DataReader.Close();
return TEST_PASS;
}
[Variation("Read with entities", Pri = 1)]
public int v3()
{
ReloadSource();
DataReader.PositionOnElement("PLAY");
XmlReader r = DataReader.ReadSubtree();
while (r.Read())
{
if (r.NodeType == XmlNodeType.EntityReference)
{
if (r.CanResolveEntity)
r.ResolveEntity();
}
}
DataReader.Close();
return TEST_PASS;
}
[Variation("Inner XML on Subtree reader", Pri = 1)]
public int v4()
{
string xmlStr = "<elem1><elem2/></elem1>";
ReloadSource(new StringReader(xmlStr));
DataReader.PositionOnElement("elem1");
XmlReader r = DataReader.ReadSubtree();
r.Read();
CError.Compare(r.ReadInnerXml(), "<elem2 />", "Inner Xml Fails");
CError.Compare(r.Read(), false, "Read returns false");
DataReader.Close();
return TEST_PASS;
}
[Variation("Outer XML on Subtree reader", Pri = 1)]
public int v5()
{
string xmlStr = "<elem1><elem2/></elem1>";
ReloadSource(new StringReader(xmlStr));
DataReader.PositionOnElement("elem1");
XmlReader r = DataReader.ReadSubtree();
r.Read();
CError.Compare(r.ReadOuterXml(), "<elem1><elem2 /></elem1>", "Outer Xml Fails");
CError.Compare(r.Read(), false, "Read returns true");
DataReader.Close();
return TEST_PASS;
}
//[Variation("Close on inner reader with CloseInput should not close the outer reader", Pri = 1, Params = new object[] { "true" })]
//[Variation("Close on inner reader with CloseInput should not close the outer reader", Pri = 1, Params = new object[] { "false" })]
public int v7()
{
if (!(IsFactoryTextReader() || IsBinaryReader() || IsFactoryValidatingReader()))
{
return TEST_SKIPPED;
}
string fileName = GetTestFileName(EREADER_TYPE.GENERIC);
bool ci = Boolean.Parse(CurVariation.Params[0].ToString());
XmlReaderSettings settings = new XmlReaderSettings();
settings.CloseInput = ci;
CError.WriteLine(ci);
MyDict<string, object> options = new MyDict<string, object>();
options.Add(ReaderFactory.HT_FILENAME, fileName);
options.Add(ReaderFactory.HT_READERSETTINGS, settings);
ReloadSource(options);
DataReader.PositionOnElement("elem2");
XmlReader r = DataReader.ReadSubtree();
CError.Compare(DataReader.ReadState, ReadState.Interactive, "ReadState not interactive");
DataReader.Close();
return TEST_PASS;
}
private XmlReader NestRead(XmlReader r)
{
r.Read();
r.Read();
if (!(r.Name == "elem0" && r.NodeType == XmlNodeType.Element))
{
CError.WriteLine(r.Name);
NestRead(r.ReadSubtree());
}
r.Dispose();
return r;
}
[Variation("Nested Subtree reader calls", Pri = 2)]
public int v8()
{
string xmlStr = "<elem1><elem2><elem3><elem4><elem5><elem6><elem7><elem8><elem9><elem0></elem0></elem9></elem8></elem7></elem6></elem5></elem4></elem3></elem2></elem1>";
ReloadSource(new StringReader(xmlStr));
XmlReader r = DataReader.Internal;
NestRead(r);
CError.Compare(r.ReadState, ReadState.Closed, "Reader Read State is not closed");
return TEST_PASS;
}
[Variation("ReadSubtree for element depth more than 4K chars", Pri = 2)]
public int v100()
{
ManagedNodeWriter mnw = new ManagedNodeWriter();
mnw.PutPattern("X");
do
{
mnw.OpenElement();
mnw.CloseElement();
}
while (mnw.GetNodes().Length < 4096);
mnw.Finish();
ReloadSource(new StringReader(mnw.GetNodes()));
DataReader.PositionOnElement("ELEMENT_2");
XmlReader r = DataReader.ReadSubtree();
while (r.Read()) ;
DataReader.Read();
CError.Compare(DataReader.Name, "ELEMENT_1", "Main name doesnt match");
CError.Compare(DataReader.Value, "", "Main value doesnt match");
CError.Compare(DataReader.NodeType.ToString().ToUpperInvariant(), "ENDELEMENT", "Main nodetype doesnt match");
DataReader.Close();
return TEST_PASS;
}
[Variation("Multiple Namespaces on Subtree reader", Pri = 1)]
public int SubtreeReaderCanDealWithMultipleNamespaces()
{
string xmlStr = "<root xmlns:p1='a' xmlns:p2='b'><e p1:a='' p2:a=''></e></root>";
ReloadSource(new StringReader(xmlStr));
DataReader.PositionOnElement("e");
XmlReader r = DataReader.ReadSubtree();
while (r.Read()) ;
DataReader.Close();
return TEST_PASS;
}
[Variation("Subtree Reader caches the NodeType and reports node type of Attribute on subsequent reads.", Pri = 1)]
public int SubtreeReaderReadsProperlyNodeTypeOfAttributes()
{
string xmlStr = "<root xmlns='foo'><b blah='blah'/><b/></root>";
ReloadSource(new StringReader(xmlStr));
DataReader.PositionOnElement("root");
XmlReader xxr = DataReader.ReadSubtree();
xxr.Read(); //Now on root.
CError.Compare(xxr.Name, "root", "Root Elem");
CError.Compare(xxr.MoveToNextAttribute(), true, "MTNA 1");
CError.Compare(xxr.NodeType, XmlNodeType.Attribute, "XMLNS NT");
CError.Compare(xxr.Name, "xmlns", "XMLNS Attr");
CError.Compare(xxr.Value, "foo", "XMLNS Value");
CError.Compare(xxr.MoveToNextAttribute(), false, "MTNA 2");
xxr.Read(); //Now on b.
CError.Compare(xxr.Name, "b", "b Elem");
CError.Compare(xxr.MoveToNextAttribute(), true, "MTNA 3");
CError.Compare(xxr.NodeType, XmlNodeType.Attribute, "blah NT");
CError.Compare(xxr.Name, "blah", "blah Attr");
CError.Compare(xxr.Value, "blah", "blah Value");
CError.Compare(xxr.MoveToNextAttribute(), false, "MTNA 4");
xxr.Read(); //Now on /b.
CError.Compare(xxr.Name, "b", "b EndElem");
CError.Compare(xxr.NodeType, XmlNodeType.Element, "b Elem NT");
CError.Compare(xxr.MoveToNextAttribute(), false, "MTNA 5");
xxr.Read(); //Now on /root.
CError.Compare(xxr.Name, "root", "root EndElem");
CError.Compare(xxr.NodeType, XmlNodeType.EndElement, "root EndElem NT");
CError.Compare(xxr.MoveToNextAttribute(), false, "MTNA 6");
DataReader.Close();
return TEST_PASS;
}
[Variation("XmlSubtreeReader add duplicate namespace declaration")]
public int XmlSubtreeReaderDoesntDuplicateLocalNames()
{
Dictionary<string, object> localNames = new Dictionary<string, object>();
string xml = "<?xml version='1.0' encoding='utf-8'?>" +
"<IXmlSerializable z:CLRType='A' z:ClrAssembly='test, " +
"Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' " +
"xmlns='http://schemas.datacontract.org' xmlns:z='http://schemas.microsoft.com' >" +
"<WriteAttributeString p3:attributeName3='attributeValue3' " +
"abc:attributeName='attributeValue' attributeName2='attributeValue2' " +
"xmlns:abc='myNameSpace' xmlns:p3='myNameSpace3' /></IXmlSerializable>";
ReloadSourceStr(xml);
DataReader.MoveToContent();
XmlReader reader = DataReader.ReadSubtree();
reader.ReadToDescendant("WriteAttributeString");
while (reader.MoveToNextAttribute())
{
if (localNames.ContainsKey(reader.LocalName))
{
CError.WriteLine("Duplicated LocalName: {0}", reader.LocalName);
return TEST_FAIL;
}
localNames.Add(reader.LocalName, null);
}
return TEST_PASS;
}
[Variation("XmlSubtreeReader adds duplicate namespace declaration")]
public int XmlSubtreeReaderDoesntAddMultipleNamespaceDeclarations()
{
ReloadSource(new StringReader("<r xmlns:a='X'><a:e/></r>"));
DataReader.Read();
DataReader.Read();
if (IsBinaryReader())
DataReader.Read();
XmlReader r1 = DataReader.ReadSubtree();
r1.Read();
XmlReader r2 = r1.ReadSubtree();
r2.Read();
string xml = r2.ReadOuterXml();
CError.Compare(xml, "<a:e xmlns:a=\"X\" />", "Mismatch");
return TEST_PASS;
}
[Variation("XmlSubtreeReader.Dispose disposes the main reader")]
public int XmlReaderDisposeDoesntDisposeMainReader()
{
ReloadSource(new StringReader("<a><b></b></a>"));
DataReader.PositionOnElement("b");
using (XmlReader subtreeReader = DataReader.ReadSubtree()) { }
if (DataReader.NodeType.ToString() == "EndElement" && DataReader.Name.ToString() == "b" && DataReader.Read() == true)
return TEST_PASS;
return TEST_FAIL;
}
private string[] _s = new string[] {
"<root xmlns:p1='a' xmlns:p2='b'><e p1:a='' p2:a=''></e></root>",
"<root xmlns:p1='a' xmlns:p2='b'><e p1:a='' p2:a='' xmlns:p2='b' ></e></root>",
"<root xmlns:p1='a' xmlns:p2='b'><e xmlns:p2='b' p1:a='' p2:a='' ></e></root>",
"<root xmlns:p1='a' ><e p1:a='' p2:a='' xmlns:p2='b' ></e></root>",
"<root xmlns:p2='b'><e xmlns:p1='a' p1:a='' p2:a=''></e></root>",
"<root xmlns:p1='a' xmlns:p2='b'><e p1:a='' p2:a='' xmlns:p1='a' xmlns:p2='b'></e></root>"
};
private string[][] _exp = {
new string[] {"p1:a", "p2:a", "xmlns:p1", "xmlns:p2"},
new string[] {"p1:a", "p2:a", "xmlns:p2", "xmlns:p1"},
new string[] {"xmlns:p2", "p1:a", "p2:a", "xmlns:p1" },
new string[] {"p1:a", "p2:a", "xmlns:p2", "xmlns:p1"},
new string[] {"xmlns:p1", "p1:a", "p2:a", "xmlns:p2"},
new string[] {"p1:a", "p2:a", "xmlns:p1", "xmlns:p2"},
};
private string[][] _expXpath = {
new string[] {"p1:a", "p2:a", "xmlns:p1", "xmlns:p2"},
new string[] {"xmlns:p2", "p1:a", "p2:a", "xmlns:p1"},
new string[] {"xmlns:p2", "p1:a", "p2:a", "xmlns:p1" },
new string[] {"xmlns:p2", "p1:a", "p2:a", "xmlns:p1"},
new string[] {"xmlns:p1", "p1:a", "p2:a", "xmlns:p2"},
new string[] {"xmlns:p1", "xmlns:p2", "p1:a", "p2:a"},
};
private string[][] _expXslt = {
new string[] {"p1:a", "p2:a", "xmlns:p1", "xmlns:p2"},
new string[] {"p1:a", "p2:a", "xmlns:p1", "xmlns:p2"},
new string[] {"p1:a", "p2:a", "xmlns:p1", "xmlns:p2" },
new string[] {"p1:a", "p2:a", "xmlns:p2", "xmlns:p1"},
new string[] {"p1:a", "p2:a", "xmlns:p1", "xmlns:p2"},
new string[] {"p1:a", "p2:a", "xmlns:p1", "xmlns:p2"},
};
//[Variation("0. XmlReader.Name inconsistent when reading namespace node attribute", Param = 0)]
//[Variation("1. XmlReader.Name inconsistent when reading namespace node attribute", Param = 1)]
//[Variation("2. XmlReader.Name inconsistent when reading namespace node attribute", Param = 2)]
//[Variation("3. XmlReader.Name inconsistent when reading namespace node attribute", Param = 3)]
//[Variation("4. XmlReader.Name inconsistent when reading namespace node attribute", Param = 4)]
//[Variation("5. XmlReader.Name inconsistent when reading namespace node attribute", Param = 5)]
public int XmlReaderNameIsConsistentWhenReadingNamespaceNodeAttribute()
{
int param = (int)CurVariation.Param;
ReloadSource(new StringReader(_s[param]));
DataReader.PositionOnElement("e");
using (XmlReader r = DataReader.ReadSubtree())
{
while (r.Read())
{
for (int i = 0; i < r.AttributeCount; i++)
{
r.MoveToAttribute(i);
if (IsXPathNavigatorReader())
CError.Compare(r.Name, _expXpath[param][i], "Error");
else if (IsXsltReader())
CError.Compare(r.Name, _expXslt[param][i], "Error");
else
CError.Compare(r.Name, _exp[param][i], "Error");
}
}
}
return TEST_PASS;
}
[Variation("Indexing methods cause infinite recursion & stack overflow")]
public int IndexingMethodsWorksProperly()
{
string xml = "<e1 a='a1' b='b1'> 123 <e2 a='a2' b='b2'> abc</e2><e3 b='b3'/></e1>";
ReloadSourceStr(xml);
DataReader.Read();
XmlReader r2 = DataReader.ReadSubtree();
r2.Read();
CError.Compare(r2[0], "a1", "Error 1");
CError.Compare(r2["b"], "b1", "Error 2");
CError.Compare(r2["a", null], "a1", "Error 3");
return TEST_PASS;
}
//[Variation("1. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 1)]
//[Variation("2. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 2)]
//[Variation("3. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 3)]
//[Variation("4. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 4)]
//[Variation("5. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 5)]
//[Variation("6. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 6)]
//[Variation("7. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 7)]
//[Variation("8. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 8)]
//[Variation("9. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 9)]
//[Variation("10. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 10)]
//[Variation("11. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 11)]
//[Variation("12. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 12)]
//[Variation("13. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 13)]
//[Variation("14. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 14)]
//[Variation("15. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 15)]
//[Variation("16. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 16)]
//[Variation("17. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 17)]
//[Variation("18. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 18)]
//[Variation("19. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 19)]
//[Variation("20. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 20)]
//[Variation("21. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 21)]
//[Variation("22. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 22)]
//[Variation("23. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 23)]
//[Variation("24. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 24)]
public int DisposingSubtreeReaderThatIsInErrorStateWorksProperly()
{
int param = (int)CurVariation.Param;
byte[] b = new byte[4];
string xml = "<Report><Account><Balance>-4,095,783.00" +
"</Balance><LastActivity>2006/01/05</LastActivity>" +
"</Account></Report>";
ReloadSourceStr(xml);
while (DataReader.Name != "Account")
DataReader.Read();
XmlReader sub = DataReader.ReadSubtree();
while (sub.Read())
{
if (sub.Name == "Balance")
{
try
{
switch (param)
{
case 1: decimal num1 = sub.ReadElementContentAsDecimal(); break;
case 2: object num2 = sub.ReadElementContentAs(typeof(float), null); break;
case 3: bool num3 = sub.ReadElementContentAsBoolean(); break;
case 5: float num5 = sub.ReadElementContentAsFloat(); break;
case 6: double num6 = sub.ReadElementContentAsDouble(); break;
case 7: int num7 = sub.ReadElementContentAsInt(); break;
case 8: long num8 = sub.ReadElementContentAsLong(); break;
case 9: object num9 = sub.ReadElementContentAs(typeof(double), null); break;
case 10: object num10 = sub.ReadElementContentAs(typeof(decimal), null); break;
case 11: sub.Read(); decimal num11 = sub.ReadContentAsDecimal(); break;
case 12: sub.Read(); object num12 = sub.ReadContentAs(typeof(float), null); break;
case 13: sub.Read(); bool num13 = sub.ReadContentAsBoolean(); break;
case 15: sub.Read(); float num15 = sub.ReadContentAsFloat(); break;
case 16: sub.Read(); double num16 = sub.ReadContentAsDouble(); break;
case 17: sub.Read(); int num17 = sub.ReadContentAsInt(); break;
case 18: sub.Read(); long num18 = sub.ReadContentAsLong(); break;
case 19: sub.Read(); object num19 = sub.ReadContentAs(typeof(double), null); break;
case 20: sub.Read(); object num20 = sub.ReadContentAs(typeof(decimal), null); break;
case 21: object num21 = sub.ReadElementContentAsBase64(b, 0, 2); break;
case 22: object num22 = sub.ReadElementContentAsBinHex(b, 0, 2); break;
case 23: sub.Read(); object num23 = sub.ReadContentAsBase64(b, 0, 2); break;
case 24: sub.Read(); object num24 = sub.ReadContentAsBinHex(b, 0, 2); break;
}
}
catch (XmlException)
{
try
{
switch (param)
{
case 1: decimal num1 = sub.ReadElementContentAsDecimal(); break;
case 2: object num2 = sub.ReadElementContentAs(typeof(float), null); break;
case 3: bool num3 = sub.ReadElementContentAsBoolean(); break;
case 5: float num5 = sub.ReadElementContentAsFloat(); break;
case 6: double num6 = sub.ReadElementContentAsDouble(); break;
case 7: int num7 = sub.ReadElementContentAsInt(); break;
case 8: long num8 = sub.ReadElementContentAsLong(); break;
case 9: object num9 = sub.ReadElementContentAs(typeof(double), null); break;
case 10: object num10 = sub.ReadElementContentAs(typeof(decimal), null); break;
case 11: sub.Read(); decimal num11 = sub.ReadContentAsDecimal(); break;
case 12: sub.Read(); object num12 = sub.ReadContentAs(typeof(float), null); break;
case 13: sub.Read(); bool num13 = sub.ReadContentAsBoolean(); break;
case 15: sub.Read(); float num15 = sub.ReadContentAsFloat(); break;
case 16: sub.Read(); double num16 = sub.ReadContentAsDouble(); break;
case 17: sub.Read(); int num17 = sub.ReadContentAsInt(); break;
case 18: sub.Read(); long num18 = sub.ReadContentAsLong(); break;
case 19: sub.Read(); object num19 = sub.ReadContentAs(typeof(double), null); break;
case 20: sub.Read(); object num20 = sub.ReadContentAs(typeof(decimal), null); break;
case 21: object num21 = sub.ReadElementContentAsBase64(b, 0, 2); break;
case 22: object num22 = sub.ReadElementContentAsBinHex(b, 0, 2); break;
case 23: sub.Read(); object num23 = sub.ReadContentAsBase64(b, 0, 2); break;
case 24: sub.Read(); object num24 = sub.ReadContentAsBinHex(b, 0, 2); break;
}
}
catch (InvalidOperationException) { return TEST_PASS; }
catch (XmlException) { return TEST_PASS; }
if (param == 24 || param == 23) return TEST_PASS;
}
catch (NotSupportedException) { return TEST_PASS; }
}
}
return TEST_FAIL;
}
[Variation("SubtreeReader has empty namespace")]
public int v101()
{
string xml = @"<a xmlns:f='urn:foobar' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>" +
"<b><c xsi:type='f:mytype'>some content</c></b></a>";
ReloadSourceStr(xml);
DataReader.Read(); CError.Compare(DataReader.Name, "a", "a");
DataReader.Read(); CError.Compare(DataReader.Name, "b", "b");
using (XmlReader subtree = DataReader.ReadSubtree())
{
subtree.Read(); CError.Compare(subtree.Name, "b", "b2");
subtree.Read(); CError.Compare(subtree.Name, "c", "c");
subtree.MoveToAttribute("type", "http://www.w3.org/2001/XMLSchema-instance");
CError.Compare(subtree.Value, "f:mytype", "value");
string ns = subtree.LookupNamespace("f");
if (ns == null) { return TEST_PASS; }
}
return TEST_FAIL;
}
[Variation("ReadValueChunk on an xmlns attribute that has been added by the subtree reader")]
public int v102()
{
char[] c = new char[10];
string xml = @"<a xmlns:f='urn:foobar' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>" +
"<b><c xsi:type='f:mytype'>some content</c></b></a>";
ReloadSourceStr(xml);
DataReader.Read();
using (XmlReader subtree = DataReader.ReadSubtree())
{
subtree.Read();
CError.Compare(subtree.Name, "a", "a");
string s = subtree[0];
CError.Compare(s, "urn:foobar", "urn:foobar");
CError.Compare(subtree.LookupNamespace("xmlns"), "http://www.w3.org/2000/xmlns/", "xmlns");
CError.Compare(subtree.MoveToFirstAttribute(), "True");
try
{
CError.Compare(subtree.ReadValueChunk(c, 0, 10), 10, "ReadValueChunk");
CError.Compare(c[0].ToString(), "u", "u");
CError.Compare(c[9].ToString(), "r", "r");
}
catch (NotSupportedException) { if (IsCustomReader() || IsCharCheckingReader()) return TEST_PASS; }
}
return TEST_PASS;
}
}
}
| |
using System;
using System.Collections.Generic;
using NuGet.Packaging.Core;
using NuGet.Versioning;
using NuKeeper.Abstractions;
using NuKeeper.Abstractions.CollaborationPlatform;
using NuKeeper.Abstractions.RepositoryInspection;
using NuKeeper.Engine;
using NUnit.Framework;
namespace NuKeeper.Tests.Engine
{
[TestFixture]
public class DefaultCommitWorderTests
{
private ICommitWorder _sut;
[SetUp]
public void TestInitialize()
{
_sut = new DefaultCommitWorder();
}
[Test]
public void MarkPullRequestTitle_UpdateIsCorrect()
{
var updates = PackageUpdates.For(MakePackageForV110())
.InList();
var report = _sut.MakePullRequestTitle(updates);
Assert.That(report, Is.Not.Null);
Assert.That(report, Is.Not.Empty);
Assert.That(report, Is.EqualTo("Automatic update of foo.bar to 1.2.3"));
}
[Test]
public void MakeCommitMessage_OneUpdateIsCorrect()
{
var updates = PackageUpdates.For(MakePackageForV110());
var report = _sut.MakeCommitMessage(updates);
Assert.That(report, Is.Not.Null);
Assert.That(report, Is.Not.Empty);
Assert.That(report, Is.EqualTo(":package: Automatic update of foo.bar to 1.2.3"));
}
[Test]
public void MakeCommitMessage_TwoUpdatesIsCorrect()
{
var updates = PackageUpdates.For(MakePackageForV110(), MakePackageForV100());
var report = _sut.MakeCommitMessage(updates);
Assert.That(report, Is.Not.Null);
Assert.That(report, Is.Not.Empty);
Assert.That(report, Is.EqualTo(":package: Automatic update of foo.bar to 1.2.3"));
}
[Test]
public void MakeCommitMessage_TwoUpdatesSameVersionIsCorrect()
{
var updates = PackageUpdates.For(MakePackageForV110(), MakePackageForV110InProject3());
var report = _sut.MakeCommitMessage(updates);
Assert.That(report, Is.Not.Null);
Assert.That(report, Is.Not.Empty);
Assert.That(report, Is.EqualTo(":package: Automatic update of foo.bar to 1.2.3"));
}
[Test]
public void OneUpdate_MakeCommitDetails_IsNotEmpty()
{
var updates = PackageUpdates.For(MakePackageForV110())
.InList();
var report = _sut.MakeCommitDetails(updates);
Assert.That(report, Is.Not.Null);
Assert.That(report, Is.Not.Empty);
}
[Test]
public void OneUpdate_MakeCommitDetails_HasStandardTexts()
{
var updates = PackageUpdates.For(MakePackageForV110())
.InList();
var report = _sut.MakeCommitDetails(updates);
AssertContainsStandardText(report);
}
[Test]
public void OneUpdate_MakeCommitDetails_HasVersionInfo()
{
var updates = PackageUpdates.For(MakePackageForV110())
.InList();
var report = _sut.MakeCommitDetails(updates);
Assert.That(report, Does.StartWith("NuKeeper has generated a minor update of `foo.bar` to `1.2.3` from `1.1.0`"));
}
[Test]
public void OneUpdate_MakeCommitDetails_HasPublishedDate()
{
var updates = PackageUpdates.For(MakePackageForV110())
.InList();
var report = _sut.MakeCommitDetails(updates);
Assert.That(report, Does.Contain("`foo.bar 1.2.3` was published at `2018-02-19T11:12:07Z`"));
}
[Test]
public void OneUpdate_MakeCommitDetails_HasProjectDetails()
{
var updates = PackageUpdates.For(MakePackageForV110())
.InList();
var report = _sut.MakeCommitDetails(updates);
Assert.That(report, Does.Contain("1 project update:"));
Assert.That(report, Does.Contain("Updated `folder\\src\\project1\\packages.config` to `foo.bar` `1.2.3` from `1.1.0`"));
}
[Test]
public void TwoUpdates_MakeCommitDetails_NotEmpty()
{
var updates = PackageUpdates.For(MakePackageForV110(), MakePackageForV100())
.InList();
var report = _sut.MakeCommitDetails(updates);
Assert.That(report, Is.Not.Null);
Assert.That(report, Is.Not.Empty);
}
[Test]
public void TwoUpdates_MakeCommitDetails_HasStandardTexts()
{
var updates = PackageUpdates.For(MakePackageForV110(), MakePackageForV100())
.InList();
var report = _sut.MakeCommitDetails(updates);
AssertContainsStandardText(report);
Assert.That(report, Does.Contain("1.0.0"));
}
[Test]
public void TwoUpdates_MakeCommitDetails_HasVersionInfo()
{
var updates = PackageUpdates.For(MakePackageForV110(), MakePackageForV100())
.InList();
var report = _sut.MakeCommitDetails(updates);
Assert.That(report, Does.StartWith("NuKeeper has generated a minor update of `foo.bar` to `1.2.3`"));
Assert.That(report, Does.Contain("2 versions of `foo.bar` were found in use: `1.1.0`, `1.0.0`"));
}
[Test]
public void TwoUpdates_MakeCommitDetails_HasProjectList()
{
var updates = PackageUpdates.For(MakePackageForV110(), MakePackageForV100())
.InList();
var report = _sut.MakeCommitDetails(updates);
Assert.That(report, Does.Contain("2 project updates:"));
Assert.That(report, Does.Contain("Updated `folder\\src\\project1\\packages.config` to `foo.bar` `1.2.3` from `1.1.0`"));
Assert.That(report, Does.Contain("Updated `folder\\src\\project2\\packages.config` to `foo.bar` `1.2.3` from `1.0.0`"));
}
[Test]
public void TwoUpdatesSameVersion_MakeCommitDetails_NotEmpty()
{
var updates = PackageUpdates.For(MakePackageForV110(), MakePackageForV110InProject3())
.InList();
var report = _sut.MakeCommitDetails(updates);
Assert.That(report, Is.Not.Null);
Assert.That(report, Is.Not.Empty);
}
[Test]
public void TwoUpdatesSameVersion_MakeCommitDetails_HasStandardTexts()
{
var updates = PackageUpdates.For(MakePackageForV110(), MakePackageForV110InProject3())
.InList();
var report = _sut.MakeCommitDetails(updates);
AssertContainsStandardText(report);
}
[Test]
public void TwoUpdatesSameVersion_MakeCommitDetails_HasVersionInfo()
{
var updates = PackageUpdates.For(MakePackageForV110(), MakePackageForV110InProject3())
.InList();
var report = _sut.MakeCommitDetails(updates);
Assert.That(report, Does.StartWith("NuKeeper has generated a minor update of `foo.bar` to `1.2.3` from `1.1.0`"));
}
[Test]
public void TwoUpdatesSameVersion_MakeCommitDetails_HasProjectList()
{
var updates = PackageUpdates.For(MakePackageForV110(), MakePackageForV110InProject3())
.InList();
var report = _sut.MakeCommitDetails(updates);
Assert.That(report, Does.Contain("2 project updates:"));
Assert.That(report, Does.Contain("Updated `folder\\src\\project1\\packages.config` to `foo.bar` `1.2.3` from `1.1.0`"));
Assert.That(report, Does.Contain("Updated `folder\\src\\project3\\packages.config` to `foo.bar` `1.2.3` from `1.1.0`"));
}
[Test]
public void OneUpdate_MakeCommitDetails_HasVersionLimitData()
{
var updates = PackageUpdates.LimitedToMinor(MakePackageForV110())
.InList();
var report = _sut.MakeCommitDetails(updates);
Assert.That(report, Does.Contain("There is also a higher version, `foo.bar 2.3.4`, but this was not applied as only `Minor` version changes are allowed."));
}
[Test]
public void OneUpdateWithDate_MakeCommitDetails_HasVersionLimitDataWithDate()
{
var publishedAt = new DateTimeOffset(2018, 2, 20, 11, 32, 45, TimeSpan.Zero);
var updates = PackageUpdates.LimitedToMinor(publishedAt, MakePackageForV110())
.InList();
var report = _sut.MakeCommitDetails(updates);
Assert.That(report, Does.Contain("There is also a higher version, `foo.bar 2.3.4` published at `2018-02-20T11:32:45Z`,"));
Assert.That(report, Does.Contain(" ago, but this was not applied as only `Minor` version changes are allowed."));
}
[Test]
public void OneUpdateWithMajorVersionChange()
{
var updates = PackageUpdates.ForNewVersion(new PackageIdentity("foo.bar", new NuGetVersion("2.1.1")), MakePackageForV110())
.InList();
var report = _sut.MakeCommitDetails(updates);
Assert.That(report, Does.StartWith("NuKeeper has generated a major update of `foo.bar` to `2.1.1` from `1.1.0"));
}
[Test]
public void OneUpdateWithMinorVersionChange()
{
var updates = PackageUpdates.ForNewVersion(new PackageIdentity("foo.bar", new NuGetVersion("1.2.1")), MakePackageForV110())
.InList();
var report = _sut.MakeCommitDetails(updates);
Assert.That(report, Does.StartWith("NuKeeper has generated a minor update of `foo.bar` to `1.2.1` from `1.1.0"));
}
[Test]
public void OneUpdateWithPatchVersionChange()
{
var updates = PackageUpdates.ForNewVersion(new PackageIdentity("foo.bar", new NuGetVersion("1.1.9")), MakePackageForV110())
.InList();
var report = _sut.MakeCommitDetails(updates);
Assert.That(report, Does.StartWith("NuKeeper has generated a patch update of `foo.bar` to `1.1.9` from `1.1.0"));
}
[Test]
public void OneUpdateWithInternalPackageSource()
{
var updates = PackageUpdates.ForInternalSource(MakePackageForV110())
.InList();
var report = _sut.MakeCommitDetails(updates);
Assert.That(report, Does.Not.Contain("on NuGet.org"));
Assert.That(report, Does.Not.Contain("www.nuget.org"));
}
[Test]
public void TwoUpdateSets()
{
var packageTwo = new PackageIdentity("packageTwo", new NuGetVersion("3.4.5"));
var updates = new List<PackageUpdateSet>
{
PackageUpdates.ForNewVersion(new PackageIdentity("foo.bar", new NuGetVersion("2.1.1")), MakePackageForV110()),
PackageUpdates.ForNewVersion(packageTwo, MakePackageForV110("packageTwo"))
};
var report = _sut.MakeCommitDetails(updates);
Assert.That(report, Does.StartWith("2 packages were updated in 1 project:"));
Assert.That(report, Does.Contain("`foo.bar`, `packageTwo`"));
Assert.That(report, Does.Contain("<details>"));
Assert.That(report, Does.Contain("</details>"));
Assert.That(report, Does.Contain("<summary>"));
Assert.That(report, Does.Contain("</summary>"));
Assert.That(report, Does.Contain("NuKeeper has generated a major update of `foo.bar` to `2.1.1` from `1.1.0`"));
Assert.That(report, Does.Contain("NuKeeper has generated a major update of `packageTwo` to `3.4.5` from `1.1.0`"));
}
private static void AssertContainsStandardText(string report)
{
Assert.That(report, Does.StartWith("NuKeeper has generated a minor update of `foo.bar` to `1.2.3`"));
Assert.That(report, Does.Contain("This is an automated update. Merge only if it passes tests"));
Assert.That(report, Does.EndWith("**NuKeeper**: https://github.com/NuKeeperDotNet/NuKeeper" + Environment.NewLine));
Assert.That(report, Does.Contain("1.1.0"));
Assert.That(report, Does.Contain("[foo.bar 1.2.3 on NuGet.org](https://www.nuget.org/packages/foo.bar/1.2.3)"));
Assert.That(report, Does.Not.Contain("Exception"));
Assert.That(report, Does.Not.Contain("System.String"));
Assert.That(report, Does.Not.Contain("Generic"));
Assert.That(report, Does.Not.Contain("[ "));
Assert.That(report, Does.Not.Contain(" ]"));
Assert.That(report, Does.Not.Contain("There is also a higher version"));
}
private static PackageInProject MakePackageForV110(string packageName = "foo.bar")
{
var path = new PackagePath("c:\\temp", "folder\\src\\project1\\packages.config",
PackageReferenceType.PackagesConfig);
return new PackageInProject(packageName, "1.1.0", path);
}
private static PackageInProject MakePackageForV100()
{
var path2 = new PackagePath("c:\\temp", "folder\\src\\project2\\packages.config",
PackageReferenceType.PackagesConfig);
var currentPackage2 = new PackageInProject("foo.bar", "1.0.0", path2);
return currentPackage2;
}
private static PackageInProject MakePackageForV110InProject3()
{
var path = new PackagePath("c:\\temp", "folder\\src\\project3\\packages.config", PackageReferenceType.PackagesConfig);
return new PackageInProject("foo.bar", "1.1.0", path);
}
}
}
| |
using UnityEngine;
using System.Collections;
[AddComponentMenu("2D Toolkit/Camera/tk2dCameraAnchor")]
[ExecuteInEditMode]
/// <summary>
/// Anchors children to anchor position, offset by number of pixels
/// </summary>
public class tk2dCameraAnchor : MonoBehaviour
{
// Legacy anchor
// Order: Upper [Left, Center, Right], Middle, Lower
[SerializeField]
int anchor = -1;
// Backing variable for AnchorPoint accessor
[SerializeField]
tk2dBaseSprite.Anchor _anchorPoint = tk2dBaseSprite.Anchor.UpperLeft;
[SerializeField]
bool anchorToNativeBounds = false;
/// <summary>
/// Anchor point location
/// </summary>
public tk2dBaseSprite.Anchor AnchorPoint {
get {
if (anchor != -1) {
if (anchor >= 0 && anchor <= 2) _anchorPoint = (tk2dBaseSprite.Anchor)( anchor + 6 );
else if (anchor >= 6 && anchor <= 8) _anchorPoint = (tk2dBaseSprite.Anchor)( anchor - 6 );
else _anchorPoint = (tk2dBaseSprite.Anchor)( anchor );
anchor = -1;
#if UNITY_EDITOR
UnityEditor.EditorUtility.SetDirty(this);
#endif
}
return _anchorPoint;
}
set {
_anchorPoint = value;
}
}
[SerializeField]
Vector2 offset = Vector2.zero;
/// <summary>
/// Offset in pixels from the anchor.
/// This is consistently in screen space, i.e. +y = top of screen, +x = right of screen
/// Eg. If you need to inset 10 pixels from from top right anchor, you'd use (-10, -10)
/// </summary>
public Vector2 AnchorOffsetPixels {
get {
return offset;
}
set {
offset = value;
}
}
/// <summary>
/// Anchor this to the tk2dCamera native bounds, instead of the screen bounds.
/// </summary>
public bool AnchorToNativeBounds {
get {
return anchorToNativeBounds;
}
set {
anchorToNativeBounds = value;
}
}
// Another backwards compatiblity only thing here
[SerializeField]
tk2dCamera tk2dCamera = null;
// New field
[SerializeField]
Camera _anchorCamera = null;
// Used to decide when to try to find the tk2dCamera component again
Camera _anchorCameraCached = null;
tk2dCamera _anchorTk2dCamera = null;
/// <summary>
/// Offset in pixels from the anchor.
/// This is consistently in screen space, i.e. +y = top of screen, +x = right of screen
/// Eg. If you need to inset 10 pixels from from top right anchor, you'd use (-10, -10)
/// </summary>
public Camera AnchorCamera {
get {
if (tk2dCamera != null) {
_anchorCamera = tk2dCamera.camera;
tk2dCamera = null;
#if UNITY_EDITOR
UnityEditor.EditorUtility.SetDirty(this);
#endif
}
return _anchorCamera;
}
set {
_anchorCamera = value;
_anchorCameraCached = null;
}
}
tk2dCamera AnchorTk2dCamera {
get {
if (_anchorCameraCached != _anchorCamera) {
_anchorTk2dCamera = _anchorCamera.GetComponent<tk2dCamera>();
_anchorCameraCached = _anchorCamera;
}
return _anchorTk2dCamera;
}
}
// cache transform locally
Transform _myTransform;
Transform myTransform {
get {
if (_myTransform == null) _myTransform = transform;
return _myTransform;
}
}
void Start()
{
UpdateTransform();
}
void UpdateTransform()
{
// Break out if anchor camera is not bound
if (AnchorCamera == null) {
return;
}
float pixelScale = 1; // size of one pixel
Vector3 position = myTransform.localPosition;
// we're ignoring perspective tk2dCameras for now
tk2dCamera currentCamera = (AnchorTk2dCamera != null && AnchorTk2dCamera.CameraSettings.projection != tk2dCameraSettings.ProjectionType.Perspective) ? AnchorTk2dCamera : null;
Rect rect = new Rect();
if (currentCamera != null) {
rect = anchorToNativeBounds ? currentCamera.NativeScreenExtents : currentCamera.ScreenExtents;
pixelScale = currentCamera.GetSizeAtDistance( 1 );
}
else {
rect.Set(0, 0, AnchorCamera.pixelWidth, AnchorCamera.pixelHeight);
}
float y_bot = rect.yMin;
float y_top = rect.yMax;
float y_ctr = (y_bot + y_top) * 0.5f;
float x_lhs = rect.xMin;
float x_rhs = rect.xMax;
float x_ctr = (x_lhs + x_rhs) * 0.5f;
Vector3 anchoredPosition = Vector3.zero;
switch (AnchorPoint)
{
case tk2dBaseSprite.Anchor.UpperLeft: anchoredPosition = new Vector3(x_lhs, y_top, position.z); break;
case tk2dBaseSprite.Anchor.UpperCenter: anchoredPosition = new Vector3(x_ctr, y_top, position.z); break;
case tk2dBaseSprite.Anchor.UpperRight: anchoredPosition = new Vector3(x_rhs, y_top, position.z); break;
case tk2dBaseSprite.Anchor.MiddleLeft: anchoredPosition = new Vector3(x_lhs, y_ctr, position.z); break;
case tk2dBaseSprite.Anchor.MiddleCenter: anchoredPosition = new Vector3(x_ctr, y_ctr, position.z); break;
case tk2dBaseSprite.Anchor.MiddleRight: anchoredPosition = new Vector3(x_rhs, y_ctr, position.z); break;
case tk2dBaseSprite.Anchor.LowerLeft: anchoredPosition = new Vector3(x_lhs, y_bot, position.z); break;
case tk2dBaseSprite.Anchor.LowerCenter: anchoredPosition = new Vector3(x_ctr, y_bot, position.z); break;
case tk2dBaseSprite.Anchor.LowerRight: anchoredPosition = new Vector3(x_rhs, y_bot, position.z); break;
}
Vector3 screenAnchoredPosition = anchoredPosition + new Vector3(pixelScale * offset.x, pixelScale * offset.y, 0);
if (currentCamera == null) { // not a tk2dCamera, we need to transform
Vector3 worldAnchoredPosition = AnchorCamera.ScreenToWorldPoint( screenAnchoredPosition );
if (myTransform.position != worldAnchoredPosition) {
myTransform.position = worldAnchoredPosition;
}
}
else {
Vector3 oldPosition = myTransform.localPosition;
if (oldPosition != screenAnchoredPosition) {
myTransform.localPosition = screenAnchoredPosition;
}
}
}
public void ForceUpdateTransform()
{
UpdateTransform();
}
// Update is called once per frame
void LateUpdate ()
{
UpdateTransform();
}
}
| |
/*
* WebHeaderCollection.cs
*
* This code is derived from System.Net.WebHeaderCollection.cs of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2003 Ximian, Inc. (http://www.ximian.com)
* Copyright (c) 2007 Novell, Inc. (http://www.novell.com)
* Copyright (c) 2012-2014 sta.blockhead
*
* 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.
*/
/*
* Authors:
* - Lawrence Pit <[email protected]>
* - Gonzalo Paniagua Javier <[email protected]>
* - Miguel de Icaza <[email protected]>
*/
namespace WebSocketSharp.Net
{
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Text;
/// <summary>
/// Provides a collection of the HTTP headers associated with a request or response.
/// </summary>
[Serializable]
[ComVisible(true)]
internal class WebHeaderCollection : NameValueCollection, ISerializable
{
private static readonly Dictionary<string, HttpHeaderInfo> Headers;
private readonly bool _internallyCreated;
private HttpHeaderType _state;
static WebHeaderCollection()
{
Headers =
new Dictionary<string, HttpHeaderInfo>(StringComparer.InvariantCultureIgnoreCase) {
{
"Accept",
new HttpHeaderInfo {
Name = "Accept",
Type = HttpHeaderType.Request | HttpHeaderType.Restricted | HttpHeaderType.MultiValue
}
},
{
"AcceptCharset",
new HttpHeaderInfo {
Name = "Accept-Charset",
Type = HttpHeaderType.Request | HttpHeaderType.MultiValue
}
},
{
"AcceptEncoding",
new HttpHeaderInfo {
Name = "Accept-Encoding",
Type = HttpHeaderType.Request | HttpHeaderType.MultiValue
}
},
{
"AcceptLanguage",
new HttpHeaderInfo {
Name = "Accept-language",
Type = HttpHeaderType.Request | HttpHeaderType.MultiValue
}
},
{
"AcceptRanges",
new HttpHeaderInfo {
Name = "Accept-Ranges",
Type = HttpHeaderType.Response | HttpHeaderType.MultiValue
}
},
{
"Age",
new HttpHeaderInfo {
Name = "Age",
Type = HttpHeaderType.Response
}
},
{
"Allow",
new HttpHeaderInfo {
Name = "Allow",
Type = HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.MultiValue
}
},
{
"Authorization",
new HttpHeaderInfo {
Name = "Authorization",
Type = HttpHeaderType.Request | HttpHeaderType.MultiValue
}
},
{
"CacheControl",
new HttpHeaderInfo {
Name = "Cache-Control",
Type = HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.MultiValue
}
},
{
"Connection",
new HttpHeaderInfo {
Name = "Connection",
Type = HttpHeaderType.Request |
HttpHeaderType.Response |
HttpHeaderType.Restricted |
HttpHeaderType.MultiValue
}
},
{
"ContentEncoding",
new HttpHeaderInfo {
Name = "Content-Encoding",
Type = HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.MultiValue
}
},
{
"ContentLanguage",
new HttpHeaderInfo {
Name = "Content-Language",
Type = HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.MultiValue
}
},
{
"ContentLength",
new HttpHeaderInfo {
Name = "Content-Length",
Type = HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.Restricted
}
},
{
"ContentLocation",
new HttpHeaderInfo {
Name = "Content-Location",
Type = HttpHeaderType.Request | HttpHeaderType.Response
}
},
{
"ContentMd5",
new HttpHeaderInfo {
Name = "Content-MD5",
Type = HttpHeaderType.Request | HttpHeaderType.Response
}
},
{
"ContentRange",
new HttpHeaderInfo {
Name = "Content-Range",
Type = HttpHeaderType.Request | HttpHeaderType.Response
}
},
{
"ContentType",
new HttpHeaderInfo {
Name = "Content-Type",
Type = HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.Restricted
}
},
{
"Cookie",
new HttpHeaderInfo {
Name = "Cookie",
Type = HttpHeaderType.Request
}
},
{
"Cookie2",
new HttpHeaderInfo {
Name = "Cookie2",
Type = HttpHeaderType.Request
}
},
{
"Date",
new HttpHeaderInfo {
Name = "Date",
Type = HttpHeaderType.Request |
HttpHeaderType.Response |
HttpHeaderType.Restricted
}
},
{
"Expect",
new HttpHeaderInfo {
Name = "Expect",
Type = HttpHeaderType.Request | HttpHeaderType.Restricted | HttpHeaderType.MultiValue
}
},
{
"Expires",
new HttpHeaderInfo {
Name = "Expires",
Type = HttpHeaderType.Request | HttpHeaderType.Response
}
},
{
"ETag",
new HttpHeaderInfo {
Name = "ETag",
Type = HttpHeaderType.Response
}
},
{
"From",
new HttpHeaderInfo {
Name = "From",
Type = HttpHeaderType.Request
}
},
{
"Host",
new HttpHeaderInfo {
Name = "Host",
Type = HttpHeaderType.Request | HttpHeaderType.Restricted
}
},
{
"IfMatch",
new HttpHeaderInfo {
Name = "If-Match",
Type = HttpHeaderType.Request | HttpHeaderType.MultiValue
}
},
{
"IfModifiedSince",
new HttpHeaderInfo {
Name = "If-Modified-Since",
Type = HttpHeaderType.Request | HttpHeaderType.Restricted
}
},
{
"IfNoneMatch",
new HttpHeaderInfo {
Name = "If-None-Match",
Type = HttpHeaderType.Request | HttpHeaderType.MultiValue
}
},
{
"IfRange",
new HttpHeaderInfo {
Name = "If-Range",
Type = HttpHeaderType.Request
}
},
{
"IfUnmodifiedSince",
new HttpHeaderInfo {
Name = "If-Unmodified-Since",
Type = HttpHeaderType.Request
}
},
{
"KeepAlive",
new HttpHeaderInfo {
Name = "Keep-Alive",
Type = HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.MultiValue
}
},
{
"LastModified",
new HttpHeaderInfo {
Name = "Last-Modified",
Type = HttpHeaderType.Request | HttpHeaderType.Response
}
},
{
"Location",
new HttpHeaderInfo {
Name = "Location",
Type = HttpHeaderType.Response
}
},
{
"MaxForwards",
new HttpHeaderInfo {
Name = "Max-Forwards",
Type = HttpHeaderType.Request
}
},
{
"Pragma",
new HttpHeaderInfo {
Name = "Pragma",
Type = HttpHeaderType.Request | HttpHeaderType.Response
}
},
{
"ProxyConnection",
new HttpHeaderInfo {
Name = "Proxy-Connection",
Type = HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.Restricted
}
},
{
"ProxyAuthenticate",
new HttpHeaderInfo {
Name = "Proxy-Authenticate",
Type = HttpHeaderType.Response | HttpHeaderType.MultiValue
}
},
{
"ProxyAuthorization",
new HttpHeaderInfo {
Name = "Proxy-Authorization",
Type = HttpHeaderType.Request
}
},
{
"Public",
new HttpHeaderInfo {
Name = "Public",
Type = HttpHeaderType.Response | HttpHeaderType.MultiValue
}
},
{
"Range",
new HttpHeaderInfo {
Name = "Range",
Type = HttpHeaderType.Request | HttpHeaderType.Restricted | HttpHeaderType.MultiValue
}
},
{
"Referer",
new HttpHeaderInfo {
Name = "Referer",
Type = HttpHeaderType.Request | HttpHeaderType.Restricted
}
},
{
"RetryAfter",
new HttpHeaderInfo {
Name = "Retry-After",
Type = HttpHeaderType.Response
}
},
{
"SecWebSocketAccept",
new HttpHeaderInfo {
Name = "Sec-WebSocket-Accept",
Type = HttpHeaderType.Response | HttpHeaderType.Restricted
}
},
{
"SecWebSocketExtensions",
new HttpHeaderInfo {
Name = "Sec-WebSocket-Extensions",
Type = HttpHeaderType.Request |
HttpHeaderType.Response |
HttpHeaderType.Restricted |
HttpHeaderType.MultiValueInRequest
}
},
{
"SecWebSocketKey",
new HttpHeaderInfo {
Name = "Sec-WebSocket-Key",
Type = HttpHeaderType.Request | HttpHeaderType.Restricted
}
},
{
"SecWebSocketProtocol",
new HttpHeaderInfo {
Name = "Sec-WebSocket-Protocol",
Type = HttpHeaderType.Request |
HttpHeaderType.Response |
HttpHeaderType.MultiValueInRequest
}
},
{
"SecWebSocketVersion",
new HttpHeaderInfo {
Name = "Sec-WebSocket-Version",
Type = HttpHeaderType.Request |
HttpHeaderType.Response |
HttpHeaderType.Restricted |
HttpHeaderType.MultiValueInResponse
}
},
{
"Server",
new HttpHeaderInfo {
Name = "Server",
Type = HttpHeaderType.Response
}
},
{
"SetCookie",
new HttpHeaderInfo {
Name = "Set-Cookie",
Type = HttpHeaderType.Response | HttpHeaderType.MultiValue
}
},
{
"SetCookie2",
new HttpHeaderInfo {
Name = "Set-Cookie2",
Type = HttpHeaderType.Response | HttpHeaderType.MultiValue
}
},
{
"Te",
new HttpHeaderInfo {
Name = "TE",
Type = HttpHeaderType.Request
}
},
{
"Trailer",
new HttpHeaderInfo {
Name = "Trailer",
Type = HttpHeaderType.Request | HttpHeaderType.Response
}
},
{
"TransferEncoding",
new HttpHeaderInfo {
Name = "Transfer-Encoding",
Type = HttpHeaderType.Request |
HttpHeaderType.Response |
HttpHeaderType.Restricted |
HttpHeaderType.MultiValue
}
},
{
"Translate",
new HttpHeaderInfo {
Name = "Translate",
Type = HttpHeaderType.Request
}
},
{
"Upgrade",
new HttpHeaderInfo {
Name = "Upgrade",
Type = HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.MultiValue
}
},
{
"UserAgent",
new HttpHeaderInfo {
Name = "User-Agent",
Type = HttpHeaderType.Request | HttpHeaderType.Restricted
}
},
{
"Vary",
new HttpHeaderInfo {
Name = "Vary",
Type = HttpHeaderType.Response | HttpHeaderType.MultiValue
}
},
{
"Via",
new HttpHeaderInfo {
Name = "Via",
Type = HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.MultiValue
}
},
{
"Warning",
new HttpHeaderInfo {
Name = "Warning",
Type = HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.MultiValue
}
},
{
"WwwAuthenticate",
new HttpHeaderInfo {
Name = "WWW-Authenticate",
Type = HttpHeaderType.Response | HttpHeaderType.Restricted | HttpHeaderType.MultiValue
}
}
};
}
/// <summary>
/// Initializes a new instance of the <see cref="WebHeaderCollection"/> class from
/// the specified <see cref="SerializationInfo"/> and <see cref="StreamingContext"/>.
/// </summary>
/// <param name="serializationInfo">
/// A <see cref="SerializationInfo"/> that contains the serialized object data.
/// </param>
/// <param name="streamingContext">
/// A <see cref="StreamingContext"/> that specifies the source for the deserialization.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="serializationInfo"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// An element with the specified name isn't found in <paramref name="serializationInfo"/>.
/// </exception>
protected WebHeaderCollection(
SerializationInfo serializationInfo, StreamingContext streamingContext)
{
if (serializationInfo == null)
throw new ArgumentNullException("serializationInfo");
try
{
_internallyCreated = serializationInfo.GetBoolean("InternallyCreated");
_state = (HttpHeaderType)serializationInfo.GetInt32("State");
var cnt = serializationInfo.GetInt32("Count");
for (var i = 0; i < cnt; i++)
{
base.Add(
serializationInfo.GetString(i.ToString()),
serializationInfo.GetString((cnt + i).ToString()));
}
}
catch (SerializationException ex)
{
throw new ArgumentException(ex.Message, "serializationInfo", ex);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="WebHeaderCollection"/> class.
/// </summary>
public WebHeaderCollection()
{
_state = HttpHeaderType.Unspecified;
}
private void InnerAdd(string name, string value, bool ignoreRestricted)
{
var act = ignoreRestricted
? (Action<string, string>)AddWithoutCheckingNameAndRestricted
: AddWithoutCheckingName;
doWithCheckingState(act, CheckName(name), value, true);
}
private void AddWithoutCheckingName(string name, string value)
{
DoWithoutCheckingName(base.Add, name, value);
}
private void AddWithoutCheckingNameAndRestricted(string name, string value)
{
base.Add(name, CheckValue(value));
}
private static int CheckColonSeparated(string header)
{
var i = header.IndexOf(':');
if (i == -1)
throw new ArgumentException("No colon could be found.", "header");
return i;
}
private static HttpHeaderType CheckHeaderType(string name)
{
var info = GetHeaderInfo(name);
return info == null
? HttpHeaderType.Unspecified
: info.IsRequest && !info.IsResponse
? HttpHeaderType.Request
: !info.IsRequest && info.IsResponse
? HttpHeaderType.Response
: HttpHeaderType.Unspecified;
}
private static string CheckName(string name)
{
if (name == null || name.Length == 0)
throw new ArgumentNullException("name");
name = name.Trim();
if (!IsHeaderName(name))
throw new ArgumentException("Contains invalid characters.", "name");
return name;
}
private void CheckRestricted(string name)
{
if (!_internallyCreated && IsRestricted(name, true))
throw new ArgumentException("This header must be modified with the appropiate property.");
}
private void CheckState(bool response)
{
if (_state == HttpHeaderType.Unspecified)
return;
if (response && _state == HttpHeaderType.Request)
throw new InvalidOperationException(
"This collection has already been used to store the request headers.");
if (!response && _state == HttpHeaderType.Response)
throw new InvalidOperationException(
"This collection has already been used to store the response headers.");
}
private static string CheckValue(string value)
{
if (value == null || value.Length == 0)
return String.Empty;
value = value.Trim();
if (value.Length > 65535)
throw new ArgumentOutOfRangeException("value", "Greater than 65,535 characters.");
if (!IsHeaderValue(value))
throw new ArgumentException("Contains invalid characters.", "value");
return value;
}
private void doWithCheckingState(Action<string, string> action, string name, string value, bool setState)
{
var type = CheckHeaderType(name);
if (type == HttpHeaderType.Request)
doWithCheckingState(action, name, value, false, setState);
else if (type == HttpHeaderType.Response)
doWithCheckingState(action, name, value, true, setState);
else
action(name, value);
}
private void doWithCheckingState(Action<string, string> action, string name, string value, bool response, bool setState)
{
CheckState(response);
action(name, value);
if (setState && _state == HttpHeaderType.Unspecified)
_state = response ? HttpHeaderType.Response : HttpHeaderType.Request;
}
private void DoWithoutCheckingName(Action<string, string> action, string name, string value)
{
CheckRestricted(name);
action(name, CheckValue(value));
}
private static HttpHeaderInfo GetHeaderInfo(string name)
{
foreach (var info in Headers.Values)
if (info.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase))
return info;
return null;
}
private static bool IsRestricted(string name, bool response)
{
var info = GetHeaderInfo(name);
return info != null && info.IsRestricted(response);
}
private void RemoveWithoutCheckingName(string name, string unuse)
{
CheckRestricted(name);
base.Remove(name);
}
private void SetWithoutCheckingName(string name, string value)
{
DoWithoutCheckingName(base.Set, name, value);
}
internal void InternalSet(string header, bool response)
{
var pos = CheckColonSeparated(header);
InternalSet(header.Substring(0, pos), header.Substring(pos + 1), response);
}
private void InternalSet(string name, string value, bool response)
{
value = CheckValue(value);
if (IsMultiValue(name, response))
base.Add(name, value);
else
base.Set(name, value);
}
private static bool IsHeaderName(string name)
{
return name != null && name.Length > 0 && name.IsToken();
}
private static bool IsHeaderValue(string value)
{
return value.IsText();
}
private static bool IsMultiValue(string headerName, bool response)
{
if (string.IsNullOrEmpty(headerName))
{
return false;
}
var info = GetHeaderInfo(headerName);
return info != null && info.IsMultiValue(response);
}
/// <summary>
/// Adds a header with the specified <paramref name="name"/> and <paramref name="value"/>
/// to the collection.
/// </summary>
/// <param name="name">
/// A <see cref="string"/> that represents the name of the header to add.
/// </param>
/// <param name="value">
/// A <see cref="string"/> that represents the value of the header to add.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="name"/> is <see langword="null"/> or empty.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="name"/> or <paramref name="value"/> contains invalid characters.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="name"/> is a restricted header name.
/// </para>
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The length of <paramref name="value"/> is greater than 65,535 characters.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The current <see cref="WebHeaderCollection"/> instance doesn't allow the header
/// <paramref name="name"/>.
/// </exception>
public override void Add(string name, string value)
{
InnerAdd(name, value, false);
}
/// <summary>
/// Removes all headers from the collection.
/// </summary>
public override void Clear()
{
base.Clear();
_state = HttpHeaderType.Unspecified;
}
/// <summary>
/// Gets an array of header values stored in the specified <paramref name="index"/> position
/// of the collection.
/// </summary>
/// <returns>
/// An array of <see cref="string"/> that receives the header values if found; otherwise,
/// <see langword="null"/>.
/// </returns>
/// <param name="index">
/// An <see cref="int"/> that represents the zero-based index of the header to find.
/// </param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="index"/> is out of allowable range of indexes for the collection.
/// </exception>
public override string[] GetValues(int index)
{
var vals = base.GetValues(index);
return vals != null && vals.Length > 0
? vals
: null;
}
/// <summary>
/// Gets an array of header values stored in the specified <paramref name="header"/>.
/// </summary>
/// <returns>
/// An array of <see cref="string"/> that receives the header values if found; otherwise,
/// <see langword="null"/>.
/// </returns>
/// <param name="header">
/// A <see cref="string"/> that represents the name of the header to find.
/// </param>
public override string[] GetValues(string header)
{
var vals = base.GetValues(header);
return vals != null && vals.Length > 0
? vals
: null;
}
/// <summary>
/// Populates the specified <see cref="SerializationInfo"/> with the data needed to serialize
/// the <see cref="WebHeaderCollection"/>.
/// </summary>
/// <param name="serializationInfo">
/// A <see cref="SerializationInfo"/> that holds the serialized object data.
/// </param>
/// <param name="streamingContext">
/// A <see cref="StreamingContext"/> that specifies the destination for the serialization.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="serializationInfo"/> is <see langword="null"/>.
/// </exception>
[SecurityPermission(
SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
public override void GetObjectData(
SerializationInfo serializationInfo, StreamingContext streamingContext)
{
if (serializationInfo == null)
{
throw new ArgumentNullException(nameof(serializationInfo));
}
serializationInfo.AddValue("InternallyCreated", _internallyCreated);
serializationInfo.AddValue("State", (int)_state);
var cnt = Count;
serializationInfo.AddValue("Count", cnt);
for (int i = 0; i < cnt; i++)
{
serializationInfo.AddValue(i.ToString(), GetKey(i));
serializationInfo.AddValue((cnt + i).ToString(), Get(i));
}
}
/// <summary>
/// Implements the <see cref="ISerializable"/> interface and raises the deserialization event
/// when the deserialization is complete.
/// </summary>
/// <param name="sender">
/// An <see cref="object"/> that represents the source of the deserialization event.
/// </param>
public override void OnDeserialization(object sender)
{
}
/// <summary>
/// Removes the specified header from the collection.
/// </summary>
/// <param name="name">
/// A <see cref="string"/> that represents the name of the header to remove.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="name"/> is <see langword="null"/> or empty.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="name"/> contains invalid characters.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="name"/> is a restricted header name.
/// </para>
/// </exception>
/// <exception cref="InvalidOperationException">
/// The current <see cref="WebHeaderCollection"/> instance doesn't allow the header
/// <paramref name="name"/>.
/// </exception>
public override void Remove(string name)
{
doWithCheckingState(RemoveWithoutCheckingName, CheckName(name), null, false);
}
/// <summary>
/// Sets the specified header to the specified value.
/// </summary>
/// <param name="name">
/// A <see cref="string"/> that represents the name of the header to set.
/// </param>
/// <param name="value">
/// A <see cref="string"/> that represents the value of the header to set.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="name"/> is <see langword="null"/> or empty.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="name"/> or <paramref name="value"/> contains invalid characters.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="name"/> is a restricted header name.
/// </para>
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The length of <paramref name="value"/> is greater than 65,535 characters.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The current <see cref="WebHeaderCollection"/> instance doesn't allow the header
/// <paramref name="name"/>.
/// </exception>
public override void Set(string name, string value)
{
doWithCheckingState(SetWithoutCheckingName, CheckName(name), value, true);
}
/// <summary>
/// Returns a <see cref="string"/> that represents the current
/// <see cref="WebHeaderCollection"/>.
/// </summary>
/// <returns>
/// A <see cref="string"/> that represents the current <see cref="WebHeaderCollection"/>.
/// </returns>
public override string ToString()
{
var pairs = Enumerable.Range(0, Count).Select(i => $"{GetKey(i)}: {Get(i)}");
return string.Join(Environment.NewLine, pairs) + Environment.NewLine;
}
/// <summary>
/// Populates the specified <see cref="SerializationInfo"/> with the data needed to serialize
/// the current <see cref="WebHeaderCollection"/>.
/// </summary>
/// <param name="serializationInfo">
/// A <see cref="SerializationInfo"/> that holds the serialized object data.
/// </param>
/// <param name="streamingContext">
/// A <see cref="StreamingContext"/> that specifies the destination for the serialization.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="serializationInfo"/> is <see langword="null"/>.
/// </exception>
[SecurityPermission(
SecurityAction.LinkDemand,
Flags = SecurityPermissionFlag.SerializationFormatter,
SerializationFormatter = true)]
void ISerializable.GetObjectData(
SerializationInfo serializationInfo, StreamingContext streamingContext)
{
GetObjectData(serializationInfo, streamingContext);
}
}
}
| |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using System;
using System.Linq;
using Microsoft.WindowsAzure.Commands.Common;
using Microsoft.WindowsAzure.Commands.Utilities.Properties;
using Microsoft.WindowsAzure.Commands.Utilities.Scheduler.Common;
using Microsoft.WindowsAzure.Commands.Utilities.Scheduler.Model;
using Microsoft.WindowsAzure.Scheduler;
using Microsoft.WindowsAzure.Scheduler.Models;
using Microsoft.Azure.Common.Extensions;
namespace Microsoft.WindowsAzure.Commands.Utilities.Scheduler
{
public partial class SchedulerMgmntClient
{
#region Create Jobs
/// <summary>
/// Populates ErrorAction values from the request
/// </summary>
/// <param name="jobRequest">Request values</param>
/// <returns>Populated JobErrorAction object</returns>
private JobErrorAction PopulateErrorAction(PSCreateJobParams jobRequest)
{
if (!string.IsNullOrEmpty(jobRequest.ErrorActionMethod) && jobRequest.ErrorActionUri != null)
{
JobErrorAction errorAction = new JobErrorAction
{
Request = new JobHttpRequest
{
Uri = jobRequest.ErrorActionUri,
Method = jobRequest.ErrorActionMethod
}
};
if (jobRequest.ErrorActionHeaders != null)
{
errorAction.Request.Headers = jobRequest.ErrorActionHeaders.ToDictionary();
}
if (jobRequest.ErrorActionMethod.Equals("PUT", StringComparison.OrdinalIgnoreCase) || jobRequest.ErrorActionMethod.Equals("POST", StringComparison.OrdinalIgnoreCase))
errorAction.Request.Body = jobRequest.ErrorActionBody;
return errorAction;
}
if (!string.IsNullOrEmpty(jobRequest.ErrorActionSasToken) && !string.IsNullOrEmpty(jobRequest.ErrorActionStorageAccount) && !string.IsNullOrEmpty(jobRequest.ErrorActionQueueName))
{
return new JobErrorAction
{
QueueMessage = new JobQueueMessage
{
QueueName = jobRequest.ErrorActionQueueName,
StorageAccountName = jobRequest.ErrorActionStorageAccount,
SasToken = jobRequest.ErrorActionSasToken,
Message = jobRequest.ErrorActionQueueBody ?? ""
}
};
}
return null;
}
/// <summary>
/// Creates a new Http Scheduler job
/// </summary>
/// <param name="jobRequest">Request values</param>
/// <param name="status">Status of create action</param>
/// <returns>Created Http Scheduler job</returns>
public PSJobDetail CreateHttpJob(PSCreateJobParams jobRequest, out string status)
{
if (!this.AvailableRegions.Contains(jobRequest.Region, StringComparer.OrdinalIgnoreCase))
throw new Exception(Resources.SchedulerInvalidLocation);
SchedulerClient schedulerClient = AzureSession.ClientFactory.CreateCustomClient<SchedulerClient>(jobRequest.Region.ToCloudServiceName(), jobRequest.JobCollectionName, csmClient.Credentials, schedulerManagementClient.BaseUri);
JobCreateOrUpdateParameters jobCreateParams = new JobCreateOrUpdateParameters
{
Action = new JobAction
{
Request = new JobHttpRequest
{
Uri = jobRequest.Uri,
Method = jobRequest.Method
},
}
};
if (jobRequest.Headers != null)
{
jobCreateParams.Action.Request.Headers = jobRequest.Headers.ToDictionary();
}
if (jobRequest.HttpAuthType.Equals("ClientCertificate", StringComparison.OrdinalIgnoreCase))
{
if (jobRequest.ClientCertPfx != null && jobRequest.ClientCertPassword != null)
{
jobCreateParams.Action.Request.Authentication = new ClientCertAuthentication
{
Type = HttpAuthenticationType.ClientCertificate,
Password = jobRequest.ClientCertPassword,
Pfx = jobRequest.ClientCertPfx
};
}
else
{
throw new InvalidOperationException(Resources.SchedulerInvalidClientCertAuthRequest);
}
}
if (jobRequest.HttpAuthType.Equals("None", StringComparison.OrdinalIgnoreCase))
{
if (!string.IsNullOrEmpty(jobRequest.ClientCertPfx) || !string.IsNullOrEmpty(jobRequest.ClientCertPassword))
{
throw new InvalidOperationException(Resources.SchedulerInvalidNoneAuthRequest);
}
}
if (jobRequest.Method.Equals("PUT", StringComparison.OrdinalIgnoreCase) || jobRequest.Method.Equals("POST", StringComparison.OrdinalIgnoreCase))
jobCreateParams.Action.Request.Body = jobRequest.Body;
//Populate job error action
jobCreateParams.Action.ErrorAction = PopulateErrorAction(jobRequest);
jobCreateParams.StartTime = jobRequest.StartTime ?? default(DateTime?);
if (jobRequest.Interval != null || jobRequest.ExecutionCount != null || !string.IsNullOrEmpty(jobRequest.Frequency) || jobRequest.EndTime != null)
{
jobCreateParams.Recurrence = new JobRecurrence();
jobCreateParams.Recurrence.Count = jobRequest.ExecutionCount ?? default(int?);
if (!string.IsNullOrEmpty(jobRequest.Frequency))
jobCreateParams.Recurrence.Frequency = (JobRecurrenceFrequency)Enum.Parse(typeof(JobRecurrenceFrequency), jobRequest.Frequency);
jobCreateParams.Recurrence.Interval = jobRequest.Interval ?? default(int?);
jobCreateParams.Recurrence.EndTime = jobRequest.EndTime ?? default(DateTime?);
}
JobCreateOrUpdateResponse jobCreateResponse = schedulerClient.Jobs.CreateOrUpdate(jobRequest.JobName, jobCreateParams);
if (!string.IsNullOrEmpty(jobRequest.JobState) && jobRequest.JobState.Equals("DISABLED", StringComparison.OrdinalIgnoreCase))
schedulerClient.Jobs.UpdateState(jobRequest.JobName, new JobUpdateStateParameters { State = JobState.Disabled });
status = jobCreateResponse.StatusCode.ToString().Equals("OK") ? "Job has been updated" : jobCreateResponse.StatusCode.ToString();
return GetJobDetail(jobRequest.JobCollectionName, jobRequest.JobName, jobRequest.Region.ToCloudServiceName());
}
/// <summary>
/// Creates a Storage Queue Scheduler job
/// </summary>
/// <param name="jobRequest">Request values</param>
/// <param name="status">Status of create action</param>
/// <returns>Created Storage Queue Scheduler job</returns>
public PSJobDetail CreateStorageJob(PSCreateJobParams jobRequest, out string status)
{
if (!this.AvailableRegions.Contains(jobRequest.Region, StringComparer.OrdinalIgnoreCase))
throw new Exception(Resources.SchedulerInvalidLocation);
SchedulerClient schedulerClient = AzureSession.ClientFactory.CreateCustomClient<SchedulerClient>(jobRequest.Region.ToCloudServiceName(), jobRequest.JobCollectionName, csmClient.Credentials, schedulerManagementClient.BaseUri);
JobCreateOrUpdateParameters jobCreateParams = new JobCreateOrUpdateParameters
{
Action = new JobAction
{
Type = JobActionType.StorageQueue,
QueueMessage = new JobQueueMessage
{
Message = jobRequest.Body ?? string.Empty,
StorageAccountName = jobRequest.StorageAccount,
QueueName = jobRequest.QueueName,
SasToken = jobRequest.SasToken
},
}
};
//Populate job error action
jobCreateParams.Action.ErrorAction = PopulateErrorAction(jobRequest);
jobCreateParams.StartTime = jobRequest.StartTime ?? default(DateTime?);
if (jobRequest.Interval != null || jobRequest.ExecutionCount != null || !string.IsNullOrEmpty(jobRequest.Frequency) || jobRequest.EndTime != null)
{
jobCreateParams.Recurrence = new JobRecurrence();
jobCreateParams.Recurrence.Count = jobRequest.ExecutionCount ?? default(int?);
if (!string.IsNullOrEmpty(jobRequest.Frequency))
jobCreateParams.Recurrence.Frequency = (JobRecurrenceFrequency)Enum.Parse(typeof(JobRecurrenceFrequency), jobRequest.Frequency);
jobCreateParams.Recurrence.Interval = jobRequest.Interval ?? default(int?);
jobCreateParams.Recurrence.EndTime = jobRequest.EndTime ?? default(DateTime?);
}
JobCreateOrUpdateResponse jobCreateResponse = schedulerClient.Jobs.CreateOrUpdate(jobRequest.JobName, jobCreateParams);
if (!string.IsNullOrEmpty(jobRequest.JobState) && jobRequest.JobState.Equals("DISABLED", StringComparison.OrdinalIgnoreCase))
schedulerClient.Jobs.UpdateState(jobRequest.JobName, new JobUpdateStateParameters { State = JobState.Disabled });
status = jobCreateResponse.StatusCode.ToString().Equals("OK") ? "Job has been updated" : jobCreateResponse.StatusCode.ToString();
return GetJobDetail(jobRequest.JobCollectionName, jobRequest.JobName, jobRequest.Region.ToCloudServiceName());
}
#endregion
/// <summary>
/// Updates given Http Scheduler job
/// </summary>
/// <param name="jobRequest">Request values</param>
/// <param name="status">Status of uodate operation</param>
/// <returns>Updated Http Scheduler job</returns>
public PSJobDetail PatchHttpJob(PSCreateJobParams jobRequest, out string status)
{
if (!this.AvailableRegions.Contains(jobRequest.Region, StringComparer.OrdinalIgnoreCase))
throw new Exception(Resources.SchedulerInvalidLocation);
SchedulerClient schedulerClient = AzureSession.ClientFactory.CreateCustomClient<SchedulerClient>(jobRequest.Region.ToCloudServiceName(), jobRequest.JobCollectionName, csmClient.Credentials, schedulerManagementClient.BaseUri);
//Get Existing job
Job job = schedulerClient.Jobs.Get(jobRequest.JobName).Job;
JobCreateOrUpdateParameters jobUpdateParams = PopulateExistingJobParams(job, jobRequest, job.Action.Type);
JobCreateOrUpdateResponse jobUpdateResponse = schedulerClient.Jobs.CreateOrUpdate(jobRequest.JobName, jobUpdateParams);
if (!string.IsNullOrEmpty(jobRequest.JobState))
schedulerClient.Jobs.UpdateState(jobRequest.JobName, new JobUpdateStateParameters
{
State = jobRequest.JobState.Equals("Enabled", StringComparison.OrdinalIgnoreCase) ? JobState.Enabled
: JobState.Disabled
});
status = jobUpdateResponse.StatusCode.ToString().Equals("OK") ? "Job has been updated" : jobUpdateResponse.StatusCode.ToString();
return GetJobDetail(jobRequest.JobCollectionName, jobRequest.JobName, jobRequest.Region.ToCloudServiceName());
}
/// <summary>
/// If a scheduler job already exists, this will merge the existing job config values with the request
/// </summary>
/// <param name="job">Existing Scheduler job</param>
/// <param name="jobRequest">Request values</param>
/// <param name="type">Http or Storage</param>
/// <returns>JobCreateOrUpdateParameters object to use when updating Scheduler job</returns>
private JobCreateOrUpdateParameters PopulateExistingJobParams(Job job, PSCreateJobParams jobRequest, JobActionType type)
{
JobCreateOrUpdateParameters jobUpdateParams = new JobCreateOrUpdateParameters();
if (type.Equals(JobActionType.StorageQueue))
{
if (jobRequest.IsStorageActionSet())
{
jobUpdateParams.Action = new JobAction();
jobUpdateParams.Action.QueueMessage = new JobQueueMessage();
if (job.Action != null)
{
jobUpdateParams.Action.Type = job.Action.Type;
if (job.Action.QueueMessage != null)
{
jobUpdateParams.Action.QueueMessage.Message = string.IsNullOrEmpty(jobRequest.StorageQueueMessage) ? job.Action.QueueMessage.Message : jobRequest.StorageQueueMessage;
jobUpdateParams.Action.QueueMessage.QueueName = jobRequest.QueueName ?? job.Action.QueueMessage.QueueName;
jobUpdateParams.Action.QueueMessage.SasToken = jobRequest.SasToken ?? job.Action.QueueMessage.SasToken;
jobUpdateParams.Action.QueueMessage.StorageAccountName = job.Action.QueueMessage.StorageAccountName;
}
else if (job.Action.QueueMessage == null)
{
jobUpdateParams.Action.QueueMessage.Message = string.IsNullOrEmpty(jobRequest.StorageQueueMessage) ? string.Empty : jobRequest.StorageQueueMessage;
jobUpdateParams.Action.QueueMessage.QueueName = jobRequest.QueueName;
jobUpdateParams.Action.QueueMessage.SasToken = jobRequest.SasToken;
jobUpdateParams.Action.QueueMessage.StorageAccountName = jobRequest.StorageAccount;
}
}
else
{
jobUpdateParams.Action.QueueMessage.Message = string.IsNullOrEmpty(jobRequest.StorageQueueMessage) ? string.Empty : jobRequest.StorageQueueMessage;
jobUpdateParams.Action.QueueMessage.QueueName = jobRequest.QueueName;
jobUpdateParams.Action.QueueMessage.SasToken = jobRequest.SasToken;
jobUpdateParams.Action.QueueMessage.StorageAccountName = jobRequest.StorageAccount;
}
}
else
{
jobUpdateParams.Action = job.Action;
}
}
else //If it is a HTTP job action type
{
if (jobRequest.IsActionSet())
{
jobUpdateParams.Action = new JobAction();
jobUpdateParams.Action.Request = new JobHttpRequest();
if (job.Action != null)
{
jobUpdateParams.Action.Type = job.Action.Type;
if (job.Action.Request != null)
{
jobUpdateParams.Action.Request.Uri = jobRequest.Uri ?? job.Action.Request.Uri;
jobUpdateParams.Action.Request.Method = jobRequest.Method ?? job.Action.Request.Method;
jobUpdateParams.Action.Request.Headers = jobRequest.Headers == null ? job.Action.Request.Headers : jobRequest.Headers.ToDictionary();
jobUpdateParams.Action.Request.Body = jobRequest.Body ?? job.Action.Request.Body;
//Job has existing authentication
if (job.Action.Request.Authentication != null)
{
if (!string.IsNullOrEmpty(jobRequest.HttpAuthType))
{
jobUpdateParams.Action.Request.Authentication = SetHttpAuthentication(jobRequest, jobUpdateParams);
}
//the new request doesn't have any changes to auth, so preserve it
else
{
jobUpdateParams.Action.Request.Authentication = job.Action.Request.Authentication;
}
}
else if (job.Action.Request.Authentication == null)
{
jobUpdateParams.Action.Request.Authentication = SetHttpAuthentication(jobRequest, jobUpdateParams);
}
}
else if (job.Action.Request == null)
{
jobUpdateParams.Action.Request.Uri = jobRequest.Uri;
jobUpdateParams.Action.Request.Method = jobRequest.Method;
jobUpdateParams.Action.Request.Headers = jobRequest.Headers.ToDictionary();
jobUpdateParams.Action.Request.Body = jobRequest.Body;
jobUpdateParams.Action.Request.Authentication = SetHttpAuthentication(jobRequest, jobUpdateParams);
}
}
else
{
jobUpdateParams.Action.Request.Uri = jobRequest.Uri;
jobUpdateParams.Action.Request.Method = jobRequest.Method;
jobUpdateParams.Action.Request.Headers = jobRequest.Headers.ToDictionary();
jobUpdateParams.Action.Request.Body = jobRequest.Body;
jobUpdateParams.Action.Request.Authentication = SetHttpAuthentication(jobRequest, jobUpdateParams);
}
}
else
{
jobUpdateParams.Action = job.Action;
}
}
if (jobRequest.IsErrorActionSet())
{
jobUpdateParams.Action.ErrorAction = new JobErrorAction();
jobUpdateParams.Action.ErrorAction.Request = new JobHttpRequest();
jobUpdateParams.Action.ErrorAction.QueueMessage = new JobQueueMessage();
if (job.Action.ErrorAction != null)
{
if (job.Action.ErrorAction.Request != null)
{
jobUpdateParams.Action.ErrorAction.Request.Uri = jobRequest.ErrorActionUri ?? job.Action.ErrorAction.Request.Uri;
jobUpdateParams.Action.ErrorAction.Request.Method = jobRequest.ErrorActionMethod ?? job.Action.ErrorAction.Request.Method;
jobUpdateParams.Action.ErrorAction.Request.Headers = jobRequest.ErrorActionHeaders == null ? job.Action.ErrorAction.Request.Headers : jobRequest.Headers.ToDictionary();
jobUpdateParams.Action.ErrorAction.Request.Body = jobRequest.ErrorActionBody ?? job.Action.ErrorAction.Request.Body;
}
else if (job.Action.ErrorAction.Request == null)
{
jobUpdateParams.Action.ErrorAction.Request.Uri = jobRequest.ErrorActionUri;
jobUpdateParams.Action.ErrorAction.Request.Method = jobRequest.ErrorActionMethod;
jobUpdateParams.Action.ErrorAction.Request.Headers = jobRequest.ErrorActionHeaders.ToDictionary();
jobUpdateParams.Action.ErrorAction.Request.Body = jobRequest.ErrorActionBody;
}
if (job.Action.ErrorAction.QueueMessage != null)
{
jobUpdateParams.Action.ErrorAction.QueueMessage.Message = jobRequest.ErrorActionQueueBody ?? job.Action.ErrorAction.QueueMessage.Message;
jobUpdateParams.Action.ErrorAction.QueueMessage.QueueName = jobRequest.ErrorActionQueueName ?? job.Action.ErrorAction.QueueMessage.QueueName;
jobUpdateParams.Action.ErrorAction.QueueMessage.SasToken = jobRequest.ErrorActionSasToken ?? job.Action.ErrorAction.QueueMessage.SasToken;
jobUpdateParams.Action.ErrorAction.QueueMessage.StorageAccountName = jobRequest.ErrorActionStorageAccount ?? job.Action.ErrorAction.QueueMessage.StorageAccountName;
}
else if (job.Action.ErrorAction.QueueMessage == null)
{
jobUpdateParams.Action.ErrorAction.QueueMessage.Message = jobRequest.ErrorActionQueueBody;
jobUpdateParams.Action.ErrorAction.QueueMessage.QueueName = jobRequest.ErrorActionQueueName;
jobUpdateParams.Action.ErrorAction.QueueMessage.SasToken = jobRequest.ErrorActionSasToken;
jobUpdateParams.Action.ErrorAction.QueueMessage.StorageAccountName = jobRequest.ErrorActionStorageAccount;
}
}
else if (job.Action.ErrorAction == null)
{
jobUpdateParams.Action.ErrorAction.Request.Uri = jobRequest.ErrorActionUri;
jobUpdateParams.Action.ErrorAction.Request.Method = jobRequest.ErrorActionMethod;
jobUpdateParams.Action.ErrorAction.Request.Headers = jobRequest.ErrorActionHeaders.ToDictionary();
jobUpdateParams.Action.ErrorAction.Request.Body = jobRequest.ErrorActionBody;
jobUpdateParams.Action.ErrorAction.QueueMessage.Message = jobRequest.ErrorActionQueueBody;
jobUpdateParams.Action.ErrorAction.QueueMessage.QueueName = jobRequest.ErrorActionQueueName;
jobUpdateParams.Action.ErrorAction.QueueMessage.SasToken = jobRequest.ErrorActionSasToken;
jobUpdateParams.Action.ErrorAction.QueueMessage.StorageAccountName = jobRequest.ErrorActionStorageAccount;
}
}
else
{
jobUpdateParams.Action.ErrorAction = job.Action.ErrorAction;
}
if (jobRequest.IsRecurrenceSet())
{
jobUpdateParams.Recurrence = new JobRecurrence();
if (job.Recurrence != null)
{
jobUpdateParams.Recurrence.Count = jobRequest.ExecutionCount ?? job.Recurrence.Count;
jobUpdateParams.Recurrence.EndTime = jobRequest.EndTime ?? job.Recurrence.EndTime;
jobUpdateParams.Recurrence.Frequency = string.IsNullOrEmpty(jobRequest.Frequency) ? job.Recurrence.Frequency : (JobRecurrenceFrequency)Enum.Parse(typeof(JobRecurrenceFrequency), jobRequest.Frequency);
jobUpdateParams.Recurrence.Interval = jobRequest.Interval ?? job.Recurrence.Interval;
jobUpdateParams.Recurrence.Schedule = SetRecurrenceSchedule(job.Recurrence.Schedule);
}
else if (job.Recurrence == null)
{
jobUpdateParams.Recurrence.Count = jobRequest.ExecutionCount;
jobUpdateParams.Recurrence.EndTime = jobRequest.EndTime;
jobUpdateParams.Recurrence.Frequency = string.IsNullOrEmpty(jobRequest.Frequency) ? default(JobRecurrenceFrequency) : (JobRecurrenceFrequency)Enum.Parse(typeof(JobRecurrenceFrequency), jobRequest.Frequency);
jobUpdateParams.Recurrence.Interval = jobRequest.Interval;
jobUpdateParams.Recurrence.Schedule = null;
}
}
else
{
jobUpdateParams.Recurrence = job.Recurrence;
if (jobUpdateParams.Recurrence != null)
{
jobUpdateParams.Recurrence.Schedule = SetRecurrenceSchedule(job.Recurrence.Schedule);
}
}
jobUpdateParams.Action.RetryPolicy = job.Action.RetryPolicy;
jobUpdateParams.StartTime = jobRequest.StartTime ?? job.StartTime;
return jobUpdateParams;
}
private HttpAuthentication SetHttpAuthentication(PSCreateJobParams jobRequest, JobCreateOrUpdateParameters jobUpdateParams)
{
HttpAuthentication httpAuthentication = null;
if (!string.IsNullOrEmpty(jobRequest.HttpAuthType))
{
switch (jobRequest.HttpAuthType.ToLower())
{
case "clientcertificate":
if (jobRequest.ClientCertPfx != null && jobRequest.ClientCertPassword != null)
{
httpAuthentication = new ClientCertAuthentication
{
Type = HttpAuthenticationType.ClientCertificate,
Password = jobRequest.ClientCertPassword,
Pfx = jobRequest.ClientCertPfx
};
}
else
{
throw new InvalidOperationException(Resources.SchedulerInvalidClientCertAuthRequest);
}
break;
case "activedirectoryoauth":
if (jobRequest.Tenant != null && jobRequest.Audience != null && jobRequest.ClientId != null && jobRequest.Secret != null)
{
httpAuthentication = new AADOAuthAuthentication
{
Type = HttpAuthenticationType.ActiveDirectoryOAuth,
Tenant = jobRequest.Tenant,
Audience = jobRequest.Audience,
ClientId = jobRequest.ClientId,
Secret = jobRequest.Secret
};
}
else
{
throw new InvalidOperationException(Resources.SchedulerInvalidAADOAuthRequest);
}
break;
case "basic":
if (jobRequest.Username != null && jobRequest.Password != null)
{
httpAuthentication = new BasicAuthentication
{
Type = HttpAuthenticationType.Basic,
Username = jobRequest.Username,
Password = jobRequest.Password
};
}
else
{
throw new InvalidOperationException(Resources.SchedulerInvalidBasicAuthRequest);
}
break;
case "none":
if (!string.IsNullOrEmpty(jobRequest.ClientCertPfx) || !string.IsNullOrEmpty(jobRequest.ClientCertPassword) ||
!string.IsNullOrEmpty(jobRequest.Tenant) || !string.IsNullOrEmpty(jobRequest.Secret) || !string.IsNullOrEmpty(jobRequest.ClientId) || !string.IsNullOrEmpty(jobRequest.Audience) ||
!string.IsNullOrEmpty(jobRequest.Username) || !string.IsNullOrEmpty(jobRequest.Password))
{
throw new InvalidOperationException(Resources.SchedulerInvalidNoneAuthRequest);
}
break;
}
}
return httpAuthentication;
}
/// <summary>
/// Existing bug in SDK where recurrence counts are set to 0 instead of null
/// </summary>
/// <param name="jobRecurrenceSchedule">The JobRecurrenceSchedule</param>
/// <returns>The JobRecurrenceSchedule</returns>
private JobRecurrenceSchedule SetRecurrenceSchedule(JobRecurrenceSchedule jobRecurrenceSchedule)
{
if (jobRecurrenceSchedule != null)
{
JobRecurrenceSchedule schedule = new JobRecurrenceSchedule();
schedule.Days = jobRecurrenceSchedule.Days.Count == 0 ? null : jobRecurrenceSchedule.Days;
schedule.Hours = jobRecurrenceSchedule.Hours.Count == 0 ? null : jobRecurrenceSchedule.Hours;
schedule.Minutes = jobRecurrenceSchedule.Minutes.Count == 0 ? null : jobRecurrenceSchedule.Minutes;
schedule.MonthDays = jobRecurrenceSchedule.MonthDays.Count == 0 ? null : jobRecurrenceSchedule.MonthDays;
schedule.MonthlyOccurrences = jobRecurrenceSchedule.MonthlyOccurrences.Count == 0 ? null : jobRecurrenceSchedule.MonthlyOccurrences;
schedule.Months = jobRecurrenceSchedule.Months.Count == 0 ? null : jobRecurrenceSchedule.Months;
return schedule;
}
else
{
return null;
}
}
/// <summary>
/// Updates given Storage Queue Scheduler job
/// </summary>
/// <param name="jobRequest">Request values</param>
/// <param name="status">Status of uodate operation</param>
/// <returns>Updated Storage Queue Scheduler job</returns>
public PSJobDetail PatchStorageJob(PSCreateJobParams jobRequest, out string status)
{
if (!this.AvailableRegions.Contains(jobRequest.Region, StringComparer.OrdinalIgnoreCase))
throw new Exception(Resources.SchedulerInvalidLocation);
SchedulerClient schedulerClient = AzureSession.ClientFactory.CreateCustomClient<SchedulerClient>(jobRequest.Region.ToCloudServiceName(), jobRequest.JobCollectionName, csmClient.Credentials, schedulerManagementClient.BaseUri);
//Get Existing job
Job job = schedulerClient.Jobs.Get(jobRequest.JobName).Job;
JobCreateOrUpdateParameters jobUpdateParams = PopulateExistingJobParams(job, jobRequest, job.Action.Type);
JobCreateOrUpdateResponse jobUpdateResponse = schedulerClient.Jobs.CreateOrUpdate(jobRequest.JobName, jobUpdateParams);
if (!string.IsNullOrEmpty(jobRequest.JobState))
schedulerClient.Jobs.UpdateState(jobRequest.JobName, new JobUpdateStateParameters
{
State = jobRequest.JobState.Equals("Enabled", StringComparison.OrdinalIgnoreCase) ? JobState.Enabled
: JobState.Disabled
});
status = jobUpdateResponse.StatusCode.ToString().Equals("OK") ? "Job has been updated" : jobUpdateResponse.StatusCode.ToString();
return GetJobDetail(jobRequest.JobCollectionName, jobRequest.JobName, jobRequest.Region.ToCloudServiceName());
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reactive.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.Its.Configuration;
using Microsoft.Its.Domain;
using Microsoft.Its.Domain.ServiceBus;
using Microsoft.Its.Domain.Sql.CommandScheduler;
using Microsoft.Its.Domain.Sql.Tests;
using Microsoft.Its.Domain.Tests;
using Microsoft.Its.Log.Instrumentation;
using Microsoft.Its.Recipes;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NUnit.Framework;
using Sample.Domain.Ordering;
using Assert = NUnit.Framework.Assert;
using EventHandlingError = Microsoft.Its.Domain.EventHandlingError;
using TestContext = Microsoft.VisualStudio.TestTools.UnitTesting.TestContext;
namespace Microsoft.Its.Cqrs.Recipes.Tests
{
[NUnit.Framework.Ignore("Deprecating functionality"), VisualStudio.TestTools.UnitTesting.Ignore]
[TestClass, TestFixture]
public class ServiceBusConsequenterDurabilityTests : EventStoreDbTest
{
private static ServiceBusSettings settings;
private Domain.Configuration configuration;
[ClassInitialize]
public static void ClassInitialize(TestContext context)
{
CommandSchedulerDbContext.NameOrConnectionString = @"Data Source=(localdb)\v11.0; Integrated Security=True; MultipleActiveResultSets=False; Initial Catalog=ItsCqrsTestsCommandScheduler";
Settings.Sources = new ISettingsSource[] { new ConfigDirectorySettings(@"c:\dev\.config") }.Concat(Settings.Sources);
settings = Settings.Get<ServiceBusSettings>();
settings.ConfigureQueue = queue => queue.AutoDeleteOnIdle = TimeSpan.FromHours(24);
#if !DEBUG
new CommandSchedulerDbContext().Database.Delete();
#endif
using (var readModels = new CommandSchedulerDbContext())
{
new CommandSchedulerDatabaseInitializer().InitializeDatabase(readModels);
}
Console.WriteLine(Environment.MachineName);
Console.WriteLine(new DirectoryInfo(@"c:\dev\.config").GetFiles().Select(f => f.FullName).ToLogString());
Settings.Sources = new ISettingsSource[] { new ConfigDirectorySettings(@"c:\dev\.config") }.Concat(Settings.Sources);
}
[TestFixtureSetUp]
public void Initialize()
{
ClassInitialize(null);
}
[SetUp, TestInitialize]
public override void SetUp()
{
base.SetUp();
configuration = new Domain.Configuration();
}
[TearDown, TestCleanup]
public override void TearDown()
{
base.TearDown();
Settings.Reset();
configuration.Dispose();
}
[Test]
public async Task Catchup_can_be_used_with_intercepted_consequenters_to_queue_event_messages_on_the_service_bus()
{
var onCancelledCalled = new AsyncValue<bool>();
var onCreatedCalled = new AsyncValue<bool>();
var onDeliveredCalled = new AsyncValue<bool>();
var anonymousConsequenterCalled = new AsyncValue<bool>();
var consequenter1 = new TestConsequenter(
onCancelled: e => onCancelledCalled.Set(true),
onCreated: e => onCreatedCalled.Set(true),
onDelivered: e => onDeliveredCalled.Set(true))
.UseServiceBusForDurability(settings, configuration: configuration);
var name = MethodBase.GetCurrentMethod().Name;
var consequenter2 = Consequenter.Create<Order.Fulfilled>(e => anonymousConsequenterCalled.Set(true))
.Named(name)
.UseServiceBusForDurability(settings, configuration: configuration);
using (var catchup = CreateReadModelCatchup<CommandSchedulerDbContext>(
consequenter1,
consequenter2))
{
Events.Write(1, i => new Order.Created());
Events.Write(1, i => new Order.Delivered());
Events.Write(1, i => new Order.Fulfilled());
Events.Write(1, i => new Order.Cancelled());
catchup.Run();
// give the service bus messages times to be delivered
Task.WaitAll(new Task[]
{
onCancelledCalled,
onCreatedCalled,
onDeliveredCalled,
anonymousConsequenterCalled
}, DefaultTimeout());
onCancelledCalled.Result.Should().Be(true);
onCreatedCalled.Result.Should().Be(true);
onDeliveredCalled.Result.Should().Be(true);
anonymousConsequenterCalled.Result.Should().Be(true);
}
}
[Test]
public void When_the_same_message_is_handled_by_multiple_consequenters_it_is_delivered_to_each_only_once()
{
var aggregateId = Any.Guid();
var consequenter1WasCalled = new AsyncValue<bool>();
var consequenter2WasCalled = new AsyncValue<bool>();
var consequenter1CallCount = 0;
var consequenter2CallCount = 0;
var consequenter1 = Consequenter.Create<Order.Fulfilled>(e =>
{
if (e.AggregateId == aggregateId)
{
Interlocked.Increment(ref consequenter1CallCount);
consequenter1WasCalled.Set(true);
}
})
.Named(MethodBase.GetCurrentMethod().Name + "-1")
.UseServiceBusForDurability(settings, configuration: configuration);
var consequenter2 = Consequenter.Create<Order.Fulfilled>(e =>
{
if (e.AggregateId == aggregateId)
{
Interlocked.Increment(ref consequenter2CallCount);
consequenter2WasCalled.Set(true);
}
})
.Named(MethodBase.GetCurrentMethod().Name + "-2")
.UseServiceBusForDurability(settings, configuration: configuration);
using (var catchup = CreateReadModelCatchup<CommandSchedulerDbContext>(consequenter1, consequenter2))
{
Events.Write(1, i => new Order.Fulfilled { AggregateId = aggregateId });
catchup.Run();
// give the service bus messages times to be delivered
Task.WaitAll(new Task[]
{
consequenter1WasCalled,
consequenter2WasCalled
}, DefaultTimeout());
consequenter1CallCount.Should().Be(1);
consequenter2CallCount.Should().Be(1);
}
}
[NUnit.Framework.Ignore("Test not finished"), VisualStudio.TestTools.UnitTesting.Ignore]
[Test]
public void When_an_exception_is_thrown_by_the_consequenter_then_it_is_retried()
{
// TODO (When_an_exception_is_thrown_by_the_consequenter_then_it_is_retried) write test
Assert.Fail("Test not written yet.");
}
[NUnit.Framework.Ignore("Test not finished"), VisualStudio.TestTools.UnitTesting.Ignore]
[Test]
public void Errors_during_catchup_result_in_retries()
{
var consequenter = Consequenter.Create<Order.CreditCardCharged>(e => { })
.UseServiceBusForDurability(new ServiceBusSettings
{
ConnectionString = "this will never work"
});
var errors = new List<EventHandlingError>();
var aggregateId = Any.Guid();
Events.Write(1, i => new Order.CreditCardCharged
{
AggregateId = aggregateId
});
using (Domain.Configuration.Global.EventBus.Errors.Subscribe(errors.Add))
using (var catchup = CreateReadModelCatchup<CommandSchedulerDbContext>(consequenter))
{
catchup.Run();
errors.Should().Contain(e => e.AggregateId == aggregateId &&
e.Exception.ToString().Contains("excelsior!"));
}
// TODO (Errors_during_catchup_result_in_retries) this would require a slightly different catchup mechanism or a way to retry events found in the EventHandlingErrors table
Assert.Fail("Test not written yet.");
}
[Test]
public void Errors_during_event_handling_are_published_back_to_the_global_bus_on_delivery()
{
var consequenter = Consequenter.Create<Order.CreditCardCharged>(e => { throw new Exception("whoa that's bad..."); })
.UseServiceBusForDurability(settings, configuration: configuration);
var errors = new List<EventHandlingError>();
var aggregateId = Any.Guid();
Events.Write(1, i => new Order.CreditCardCharged
{
AggregateId = aggregateId
});
using (configuration.EventBus.Errors.Subscribe(errors.Add))
using (var catchup = CreateReadModelCatchup<CommandSchedulerDbContext>(consequenter))
{
catchup.Run();
errors.Should().Contain(e => e.AggregateId == aggregateId &&
e.Exception.ToString().Contains("whoa that's bad..."));
}
}
[Test]
public void Durable_consequenters_can_be_simulated_for_unit_testing_and_receive_messages()
{
var consequenter1WasCalled = false;
var consequenter2WasCalled = false;
var uselessSettings = new ServiceBusSettings();
using (ServiceBusDurabilityExtensions.Simulate())
{
var consequenter1 = Consequenter.Create<Order.Cancelled>(
e => { consequenter1WasCalled = true; });
var consequenter2 = Consequenter.Create<Order.CreditCardCharged>(
e => { consequenter2WasCalled = true; });
var bus = new InProcessEventBus();
bus.Subscribe(
consequenter1.UseServiceBusForDurability(uselessSettings),
consequenter2.UseServiceBusForDurability(uselessSettings));
bus.PublishAsync(new Order.Cancelled()).Wait();
consequenter1WasCalled.Should().BeTrue();
consequenter2WasCalled.Should().BeFalse();
}
}
private TimeSpan DefaultTimeout()
{
if (Debugger.IsAttached)
{
return TimeSpan.FromMinutes(30);
}
return TimeSpan.FromSeconds(30);
}
public class AsyncValue<T>
{
private readonly TaskCompletionSource<T> tcs = new TaskCompletionSource<T>();
public void Set(T value)
{
if (!tcs.Task.IsCompleted)
{
tcs.SetResult(value);
}
}
public TaskAwaiter<T> GetAwaiter()
{
return tcs.Task.GetAwaiter();
}
public T Result
{
get
{
return tcs.Task.Result;
}
}
public static implicit operator Task<T>(AsyncValue<T> asyncValue)
{
return asyncValue.tcs.Task;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Randomizer.Web.Data;
using Randomizer.Model;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Randomizer.Web.Models;
using Randomizer.Core;
using Microsoft.AspNetCore.Authorization;
using Randomizer.Web.Data.Repositories;
using Sakura.AspNetCore;
using Microsoft.Extensions.Localization;
namespace Randomizer.Web.Controllers
{
[Authorize]
public class ElementListsController : Controller
{
private readonly IElementListsRepository _repository;
private readonly IElementsRepository _elementsRepo;
private readonly UserManager<ApplicationUser> _userManager;
private readonly int _pageSize;
public ElementListsController(IElementListsRepository repository,
IElementsRepository elementsRepo,
UserManager<ApplicationUser> userManager,
int pageSize = 10)
{
_pageSize = pageSize;
_repository = repository;
_elementsRepo = elementsRepo;
_userManager = userManager;
}
public IActionResult Index(int page = 1)
{
var lists = _repository.AllWhere(l => l.UserID == _userManager.GetUserId(User))
.OrderBy(e => e.Name)
.AsNoTracking()
.ToPagedList(_pageSize, page);
return View(lists);
}
public async Task<IActionResult> Details(int? id)
{
if (id.HasValue == false)
{
return NotFound();
}
var list = await _repository.GetSingle(m => m.ID == id,
l => l.Elements);
if (list == null)
{
return NotFound();
}
return View(list);
}
[HttpGet]
public IActionResult Create()
{
var list = new ElementList();
return View(list);
}
[HttpPost]
public async Task<IActionResult> Create(ElementList model)
{
try
{
if (ModelState.IsValid)
{
if (User.Identity.IsAuthenticated)
{
model.UserID = _userManager.GetUserId(User);
}
_repository.Create(model);
await _repository.Save();
return RedirectToAction("Index");
}
}
catch (DbUpdateException)
{
ModelState.AddModelError("", "Unable to save changes. " +
"Try again, and if the problem persists " +
"see your system administrator.");
}
return View(model);
}
[HttpGet]
public async Task<IActionResult> Edit(int? id)
{
if (id.HasValue == false)
{
return NotFound();
}
var list = await _repository.GetSingle(m => m.ID == id,
l => l.Elements);
if (list == null)
{
return NotFound();
}
return View(list);
}
[HttpPost, ActionName("Edit")]
public async Task<IActionResult> EditPost(int? id)
{
if (id.HasValue == false)
{
return NotFound();
}
var listToUpdate = _repository.AllWhere(l => l.ID == id)
.Include(l => l.Elements)
.ThenInclude(e => e.User)
.SingleOrDefault();
if (await TryUpdateModelAsync<ElementList>(
listToUpdate,
"",
s => s.Name, s => s.Description))
{
try
{
await _repository.Save();
return RedirectToAction("Index");
}
catch (DbUpdateException)
{
ModelState.AddModelError("", "Unable to save changes. " +
"Try again, and if the problem persists, " +
"see your system administrator.");
}
}
return View(listToUpdate);
}
[HttpGet]
public async Task<IActionResult> Delete(int? id, bool? saveChangesError = false)
{
if (id.HasValue == false)
{
return NotFound();
}
var list = await _repository.GetSingle(m => m.ID == id);
if (list == null)
{
return NotFound();
}
if (saveChangesError.GetValueOrDefault())
{
ViewData["ErrorMessage"] =
"Delete failed. Try again, and if the problem persists " +
"see your system administrator.";
}
return View(list);
}
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var list = await _repository.GetSingle(m => m.ID == id,
l => l.Elements);
if (list == null)
{
return RedirectToAction("Index");
}
try
{
_repository.Delete(list);
await _repository.Save();
return RedirectToAction("Index");
}
catch (DbUpdateException)
{
return RedirectToAction("Delete", new { id = id, saveChangesError = true });
}
}
/// <summary>
/// Takes an item from a list.
/// </summary>
/// <param name="id">The ID of the list</param>
/// <returns>The name of the item</returns>
[HttpPost]
public async Task<IActionResult> DrawItem(int? id)
{
if (id.HasValue == false)
{
return NotFound();
}
var list = await _repository.GetSingle(m => m.ID == id,
l => l.Elements);
if (list == null)
{
return NotFound();
}
var randomizerEngine = new RandomizerEngine();
string elementName = "";
try
{
var randomElement = await randomizerEngine.GetElement(list.Elements.AsQueryable());
elementName = randomElement.Name;
}
catch (ArgumentOutOfRangeException)
{
return Json(new { ans = "There are not enough items in your list!" });
}
return Json(new { ans = elementName });
}
/// <summary>
/// Takes N number of items from a list.
/// </summary>
/// <param name="id">ID of the list</param>
/// <param name="count">The number of items to take</param>
/// <returns>A string with names of the items</returns>
[HttpPost]
public async Task<IActionResult> DrawItems(int? id, int count)
{
if (id.HasValue == false)
{
return NotFound();
}
var list = await _repository.GetSingle(m => m.ID == id,
l => l.Elements);
if (list == null)
{
return NotFound();
}
var randomizerEngine = new RandomizerEngine();
var names = "";
try
{
var randomElements = await randomizerEngine.GetElements(list.Elements.AsQueryable(), count);
foreach (var element in randomElements)
{
names += element.Name + "<br/>";
}
}
catch (ArgumentOutOfRangeException)
{
return Json(new { ans = "There are not enough items in your list!" });
}
return Json(new { ans = names });
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Net;
using System.Linq;
using Microsoft.Azure;
using Microsoft.Azure.Management.ResourceManager;
using Microsoft.Azure.Management.ResourceManager.Models;
using Microsoft.Azure.Test;
using Microsoft.Rest.TransientFaultHandling;
using Xunit;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using Newtonsoft.Json.Linq;
using Microsoft.Rest.Azure.OData;
namespace ResourceGroups.Tests
{
public class LiveResourceTests : TestBase
{
const string WebResourceProviderVersion = "2014-04-01";
const string StoreResourceProviderVersion = "2014-04-01-preview";
string ResourceGroupLocation
{
get { return "South Central US"; }
}
public static ResourceIdentity CreateResourceIdentity(GenericResource resource)
{
string[] parts = resource.Type.Split('/');
return new ResourceIdentity { ResourceType = parts[1], ResourceProviderNamespace = parts[0], ResourceName = resource.Name, ResourceProviderApiVersion = WebResourceProviderVersion };
}
public ResourceManagementClient GetResourceManagementClient(MockContext context, RecordedDelegatingHandler handler)
{
handler.IsPassThrough = true;
return this.GetResourceManagementClientWithHandler(context, handler);
}
public string GetWebsiteLocation(ResourceManagementClient client)
{
return "WestUS";
}
public string GetMySqlLocation(ResourceManagementClient client)
{
return ResourcesManagementTestUtilities.GetResourceLocation(client, "SuccessBricks.ClearDB/databases");
}
[Fact]
public void CleanupAllResources()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK };
using (MockContext context = MockContext.Start(this.GetType().FullName))
{
var client = GetResourceManagementClient(context, handler);
client.SetRetryPolicy(new RetryPolicy<HttpStatusCodeErrorDetectionStrategy>(1));
var groups = client.ResourceGroups.List();
foreach (var group in groups)
{
var resources = client.ResourceGroups.ListResources(group.Name, new ODataQuery<GenericResourceFilter>(r => r.ResourceType == "Microsoft.Web/sites"));
foreach (var resource in resources)
{
client.Resources.Delete(group.Name,
CreateResourceIdentity(resource).ResourceProviderNamespace,
string.Empty,
CreateResourceIdentity(resource).ResourceType,
resource.Name,
CreateResourceIdentity(resource).ResourceProviderApiVersion);
}
client.ResourceGroups.BeginDelete(group.Name);
}
}
}
[Fact]
public void CreateResourceWithPlan()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK };
using (MockContext context = MockContext.Start(this.GetType().FullName))
{
string groupName = TestUtilities.GenerateName("csmrg");
string resourceName = TestUtilities.GenerateName("csmr");
var client = GetResourceManagementClient(context, handler);
string mySqlLocation = GetMySqlLocation(client);
var groupIdentity = new ResourceIdentity
{
ResourceName = resourceName,
ResourceProviderNamespace = "SuccessBricks.ClearDB",
ResourceType = "databases",
ResourceProviderApiVersion = StoreResourceProviderVersion
};
client.SetRetryPolicy(new RetryPolicy<HttpStatusCodeErrorDetectionStrategy>(1));
client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = this.ResourceGroupLocation });
var createOrUpdateResult = client.Resources.CreateOrUpdate(groupName, groupIdentity.ResourceProviderNamespace, "", groupIdentity.ResourceType,
groupIdentity.ResourceName, groupIdentity.ResourceProviderApiVersion,
new GenericResource
{
Location = mySqlLocation,
Plan = new Plan {Name = "Free"},
Tags = new Dictionary<string, string> { { "provision_source", "RMS" } }
}
);
Assert.Equal(resourceName, createOrUpdateResult.Name);
Assert.True(ResourcesManagementTestUtilities.LocationsAreEqual(mySqlLocation, createOrUpdateResult.Location),
string.Format("Resource location for resource '{0}' does not match expected location '{1}'", createOrUpdateResult.Location, mySqlLocation));
Assert.NotNull(createOrUpdateResult.Plan);
Assert.Equal("Free", createOrUpdateResult.Plan.Name);
var getResult = client.Resources.Get(groupName, groupIdentity.ResourceProviderNamespace,
"", groupIdentity.ResourceType, groupIdentity.ResourceName, groupIdentity.ResourceProviderApiVersion);
Assert.Equal(resourceName, getResult.Name);
Assert.True(ResourcesManagementTestUtilities.LocationsAreEqual(mySqlLocation, getResult.Location),
string.Format("Resource location for resource '{0}' does not match expected location '{1}'", getResult.Location, mySqlLocation));
Assert.NotNull(getResult.Plan);
Assert.Equal("Free", getResult.Plan.Name);
}
}
[Fact]
public void CreatedResourceIsAvailableInList()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK };
using (MockContext context = MockContext.Start(this.GetType().FullName))
{
string groupName = TestUtilities.GenerateName("csmrg");
string resourceName = TestUtilities.GenerateName("csmr");
var client = GetResourceManagementClient(context, handler);
string websiteLocation = GetWebsiteLocation(client);
client.SetRetryPolicy(new RetryPolicy<HttpStatusCodeErrorDetectionStrategy>(1));
client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = this.ResourceGroupLocation });
var createOrUpdateResult = client.Resources.CreateOrUpdate(groupName, "Microsoft.Web", "", "sites",resourceName, WebResourceProviderVersion,
new GenericResource
{
Location = websiteLocation,
Properties = JObject.Parse("{'name':'" + resourceName + "','siteMode':'Limited','computeMode':'Shared', 'sku':'Free', 'workerSize': 0}"),
}
);
Assert.NotNull(createOrUpdateResult.Id);
Assert.Equal(resourceName, createOrUpdateResult.Name);
Assert.Equal("Microsoft.Web/sites", createOrUpdateResult.Type);
Assert.True(ResourcesManagementTestUtilities.LocationsAreEqual(websiteLocation, createOrUpdateResult.Location),
string.Format("Resource location for website '{0}' does not match expected location '{1}'", createOrUpdateResult.Location, websiteLocation));
var listResult = client.ResourceGroups.ListResources(groupName);
Assert.Equal(1, listResult.Count());
Assert.Equal(resourceName, listResult.First().Name);
Assert.Equal("Microsoft.Web/sites", listResult.First().Type);
Assert.True(ResourcesManagementTestUtilities.LocationsAreEqual(websiteLocation, listResult.First().Location),
string.Format("Resource list location for website '{0}' does not match expected location '{1}'", listResult.First().Location, websiteLocation));
listResult = client.ResourceGroups.ListResources(groupName, new ODataQuery<GenericResourceFilter> { Top = 10 });
Assert.Equal(1, listResult.Count());
Assert.Equal(resourceName, listResult.First().Name);
Assert.Equal("Microsoft.Web/sites", listResult.First().Type);
Assert.True(ResourcesManagementTestUtilities.LocationsAreEqual(websiteLocation, listResult.First().Location),
string.Format("Resource list location for website '{0}' does not match expected location '{1}'", listResult.First().Location, websiteLocation));
}
}
[Fact]
public void CreatedResourceIsAvailableInListFilteredByTagName()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK };
using (MockContext context = MockContext.Start(this.GetType().FullName))
{
string groupName = TestUtilities.GenerateName("csmrg");
string resourceName = TestUtilities.GenerateName("csmr");
string resourceNameNoTags = TestUtilities.GenerateName("csmr");
string tagName = TestUtilities.GenerateName("csmtn");
var client = GetResourceManagementClient(context, handler);
string websiteLocation = GetWebsiteLocation(client);
client.SetRetryPolicy(new RetryPolicy<HttpStatusCodeErrorDetectionStrategy>(1));
client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = this.ResourceGroupLocation });
client.Resources.CreateOrUpdate(
groupName,
"Microsoft.Web",
string.Empty,
"sites",
resourceName,
WebResourceProviderVersion,
new GenericResource
{
Tags = new Dictionary<string, string> { { tagName, "" } },
Location = websiteLocation,
Properties = JObject.Parse("{'name':'" + resourceName + "','siteMode':'Limited','computeMode':'Shared', 'sku':'Free', 'workerSize': 0}")
});
client.Resources.CreateOrUpdate(
groupName,
"Microsoft.Web",
string.Empty,
"sites",
resourceNameNoTags,
WebResourceProviderVersion,
new GenericResource
{
Location = websiteLocation,
Properties = JObject.Parse("{'name':'" + resourceNameNoTags + "','siteMode':'Limited','computeMode':'Shared', 'sku':'Free', 'workerSize': 0}")
});
var listResult = client.ResourceGroups.ListResources(groupName, new ODataQuery<GenericResourceFilter>(r => r.Tagname == tagName));
Assert.Equal(1, listResult.Count());
Assert.Equal(resourceName, listResult.First().Name);
var getResult = client.Resources.Get(
groupName,
"Microsoft.Web",
string.Empty,
"sites",
resourceName,
WebResourceProviderVersion);
Assert.Equal(resourceName, getResult.Name);
Assert.True(getResult.Tags.Keys.Contains(tagName));
}
}
[Fact]
public void CreatedResourceIsAvailableInListFilteredByTagNameAndValue()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK };
using (MockContext context = MockContext.Start(this.GetType().FullName))
{
string groupName = TestUtilities.GenerateName("csmrg");
string resourceName = TestUtilities.GenerateName("csmr");
string resourceNameNoTags = TestUtilities.GenerateName("csmr");
string tagName = TestUtilities.GenerateName("csmtn");
string tagValue = TestUtilities.GenerateName("csmtv");
var client = GetResourceManagementClient(context, handler);
string websiteLocation = GetWebsiteLocation(client);
client.SetRetryPolicy(new RetryPolicy<HttpStatusCodeErrorDetectionStrategy>(1));
client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = this.ResourceGroupLocation });
client.Resources.CreateOrUpdate(
groupName,
"Microsoft.Web",
"",
"sites",
resourceName,
WebResourceProviderVersion,
new GenericResource
{
Tags = new Dictionary<string, string> { { tagName, tagValue } },
Location = websiteLocation,
Properties = JObject.Parse("{'name':'" + resourceName + "','siteMode':'Limited','computeMode':'Shared', 'sku':'Free', 'workerSize': 0}")
}
);
client.Resources.CreateOrUpdate(
groupName,
"Microsoft.Web",
"",
"sites",
resourceNameNoTags,
WebResourceProviderVersion,
new GenericResource
{
Location = websiteLocation,
Properties = JObject.Parse("{'name':'" + resourceNameNoTags + "','siteMode':'Limited','computeMode':'Shared', 'sku':'Free', 'workerSize': 0}")
}
);
var listResult = client.ResourceGroups.ListResources(groupName,
new ODataQuery<GenericResourceFilter>(r => r.Tagname == tagName && r.Tagvalue == tagValue));
Assert.Equal(1, listResult.Count());
Assert.Equal(resourceName, listResult.First().Name);
var getResult = client.Resources.Get(
groupName,
"Microsoft.Web",
"",
"sites",
resourceName,
WebResourceProviderVersion);
Assert.Equal(resourceName, getResult.Name);
Assert.True(getResult.Tags.Keys.Contains(tagName));
}
}
[Fact]
public void CreatedAndDeleteResource()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK };
using (MockContext context = MockContext.Start(this.GetType().FullName))
{
string groupName = TestUtilities.GenerateName("csmrg");
string resourceName = TestUtilities.GenerateName("csmr");
var client = GetResourceManagementClient(context, handler);
client.SetRetryPolicy(new RetryPolicy<HttpStatusCodeErrorDetectionStrategy>(1));
string location = this.GetWebsiteLocation(client);
client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = location });
var createOrUpdateResult = client.Resources.CreateOrUpdate(
groupName,
"Microsoft.Web",
"",
"sites",
resourceName,
WebResourceProviderVersion,
new GenericResource
{
Location = location,
Properties = JObject.Parse("{'name':'" + resourceName + "','siteMode':'Limited','computeMode':'Shared', 'sku':'Free', 'workerSize': 0}")
}
);
var listResult = client.ResourceGroups.ListResources(groupName);
Assert.Equal(resourceName, listResult.First().Name);
client.Resources.Delete(
groupName,
"Microsoft.Web",
"",
"sites",
resourceName,
WebResourceProviderVersion);
}
}
[Fact]
public void CreatedAndDeleteResourceById()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK };
using (MockContext context = MockContext.Start(this.GetType().FullName))
{
string subscriptionId = "89ec4d1d-dcc7-4a3f-a701-0a5d074c8505";
string groupName = TestUtilities.GenerateName("csmrg");
string resourceName = TestUtilities.GenerateName("csmr");
var client = GetResourceManagementClient(context, handler);
client.SetRetryPolicy(new RetryPolicy<HttpStatusCodeErrorDetectionStrategy>(1));
string location = this.GetWebsiteLocation(client);
string resourceId = string.Format("/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Web/sites/{2}", subscriptionId, groupName, resourceName);
client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = location });
var createOrUpdateResult = client.Resources.CreateOrUpdateById(
resourceId,
WebResourceProviderVersion,
new GenericResource
{
Location = location,
Properties = JObject.Parse("{'name':'" + resourceName + "','siteMode':'Limited','computeMode':'Shared', 'sku':'Free', 'workerSize': 0}")
}
);
var listResult = client.ResourceGroups.ListResources(groupName);
Assert.Equal(resourceName, listResult.First().Name);
client.Resources.DeleteById(
resourceId,
WebResourceProviderVersion);
}
}
[Fact]
public void CreatedAndListResource()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK };
using (MockContext context = MockContext.Start(this.GetType().FullName))
{
string groupName = TestUtilities.GenerateName("csmrg");
string resourceName = TestUtilities.GenerateName("csmr");
var client = GetResourceManagementClient(context, handler);
string location = this.GetWebsiteLocation(client);
client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = location });
var createOrUpdateResult = client.Resources.CreateOrUpdate(
groupName,
"Microsoft.Web",
"",
"sites",
resourceName,
WebResourceProviderVersion,
new GenericResource
{
Location = location,
Tags = new Dictionary<string, string>() { { "department", "finance" }, { "tagname", "tagvalue" } },
Properties = JObject.Parse("{'name':'" + resourceName + "','siteMode':'Limited','computeMode':'Shared', 'sku':'Free', 'workerSize': 0}")
}
);
var listResult = client.Resources.List(new ODataQuery<GenericResourceFilter>(r => r.ResourceType == "Microsoft.Web/sites"));
Assert.NotEmpty(listResult);
Assert.Equal(2, listResult.First().Tags.Count);
}
}
}
}
| |
// ****************************************************************
// Copyright 2007, Charlie Poole
// This is free software licensed under the NUnit license. You may
// obtain a copy of the license at http://nunit.org
// ****************************************************************
using System.Collections;
namespace NUnit.Framework.Constraints
{
/// <summary>
/// Delegate used to delay evaluation of the actual value
/// to be used in evaluating a constraint
/// </summary>
public delegate object ActualValueDelegate();
/// <summary>
/// The Constraint class is the base of all built-in constraints
/// within NUnit. It provides the operator overloads used to combine
/// constraints.
/// </summary>
public abstract class Constraint : IResolveConstraint
{
#region UnsetObject Class
/// <summary>
/// Class used to detect any derived constraints
/// that fail to set the actual value in their
/// Matches override.
/// </summary>
private class UnsetObject
{
public override string ToString()
{
return "UNSET";
}
}
#endregion
#region Static and Instance Fields
/// <summary>
/// Static UnsetObject used to detect derived constraints
/// failing to set the actual value.
/// </summary>
protected static object UNSET = new UnsetObject();
/// <summary>
/// The actual value being tested against a constraint
/// </summary>
protected object actual = UNSET;
/// <summary>
/// The display name of this Constraint for use by ToString()
/// </summary>
private string displayName;
/// <summary>
/// Argument fields used by ToString();
/// </summary>
private readonly int argcnt;
private readonly object arg1;
private readonly object arg2;
/// <summary>
/// The builder holding this constraint
/// </summary>
private ConstraintBuilder builder;
#endregion
#region Constructors
/// <summary>
/// Construct a constraint with no arguments
/// </summary>
public Constraint()
{
argcnt = 0;
}
/// <summary>
/// Construct a constraint with one argument
/// </summary>
public Constraint(object arg)
{
argcnt = 1;
this.arg1 = arg;
}
/// <summary>
/// Construct a constraint with two arguments
/// </summary>
public Constraint(object arg1, object arg2)
{
argcnt = 2;
this.arg1 = arg1;
this.arg2 = arg2;
}
#endregion
#region Set Containing ConstraintBuilder
/// <summary>
/// Sets the ConstraintBuilder holding this constraint
/// </summary>
internal void SetBuilder(ConstraintBuilder builder)
{
this.builder = builder;
}
#endregion
#region Properties
/// <summary>
/// The display name of this Constraint for use by ToString().
/// The default value is the name of the constraint with
/// trailing "Constraint" removed. Derived classes may set
/// this to another name in their constructors.
/// </summary>
public string DisplayName
{
get
{
if (displayName == null)
{
displayName = this.GetType().Name.ToLower();
if (displayName.EndsWith("`1") || displayName.EndsWith("`2"))
displayName = displayName.Substring(0, displayName.Length - 2);
if (displayName.EndsWith("constraint"))
displayName = displayName.Substring(0, displayName.Length - 10);
}
return displayName;
}
set { displayName = value; }
}
#endregion
#region Abstract and Virtual Methods
/// <summary>
/// Write the failure message to the MessageWriter provided
/// as an argument. The default implementation simply passes
/// the constraint and the actual value to the writer, which
/// then displays the constraint description and the value.
///
/// Constraints that need to provide additional details,
/// such as where the error occured can override this.
/// </summary>
/// <param name="writer">The MessageWriter on which to display the message</param>
public virtual void WriteMessageTo(MessageWriter writer)
{
writer.DisplayDifferences(this);
}
/// <summary>
/// Test whether the constraint is satisfied by a given value
/// </summary>
/// <param name="actual">The value to be tested</param>
/// <returns>True for success, false for failure</returns>
public abstract bool Matches(object actual);
/// <summary>
/// Test whether the constraint is satisfied by an
/// ActualValueDelegate that returns the value to be tested.
/// The default implementation simply evaluates the delegate
/// but derived classes may override it to provide for delayed
/// processing.
/// </summary>
/// <param name="del">An ActualValueDelegate</param>
/// <returns>True for success, false for failure</returns>
public virtual bool Matches(ActualValueDelegate del)
{
return Matches(del());
}
#if CLR_2_0 || CLR_4_0
/// <summary>
/// Test whether the constraint is satisfied by a given reference.
/// The default implementation simply dereferences the value but
/// derived classes may override it to provide for delayed processing.
/// </summary>
/// <param name="actual">A reference to the value to be tested</param>
/// <returns>True for success, false for failure</returns>
public virtual bool Matches<T>(ref T actual)
{
return Matches(actual);
}
#else
/// <summary>
/// Test whether the constraint is satisfied by a given bool reference.
/// The default implementation simply dereferences the value but
/// derived classes may override it to provide for delayed processing.
/// </summary>
/// <param name="actual">A reference to the value to be tested</param>
/// <returns>True for success, false for failure</returns>
public virtual bool Matches(ref bool actual)
{
return Matches(actual);
}
#endif
/// <summary>
/// Write the constraint description to a MessageWriter
/// </summary>
/// <param name="writer">The writer on which the description is displayed</param>
public abstract void WriteDescriptionTo(MessageWriter writer);
/// <summary>
/// Write the actual value for a failing constraint test to a
/// MessageWriter. The default implementation simply writes
/// the raw value of actual, leaving it to the writer to
/// perform any formatting.
/// </summary>
/// <param name="writer">The writer on which the actual value is displayed</param>
public virtual void WriteActualValueTo(MessageWriter writer)
{
writer.WriteActualValue( actual );
}
#endregion
#region ToString Override
/// <summary>
/// Default override of ToString returns the constraint DisplayName
/// followed by any arguments within angle brackets.
/// </summary>
/// <returns></returns>
public override string ToString()
{
string rep = GetStringRepresentation();
return this.builder == null ? rep : string.Format("<unresolved {0}>", rep);
}
/// <summary>
/// Returns the string representation of this constraint
/// </summary>
protected virtual string GetStringRepresentation()
{
switch (argcnt)
{
default:
case 0:
return string.Format("<{0}>", DisplayName);
case 1:
return string.Format("<{0} {1}>", DisplayName, _displayable(arg1));
case 2:
return string.Format("<{0} {1} {2}>", DisplayName, _displayable(arg1), _displayable(arg2));
}
}
private string _displayable(object o)
{
if (o == null) return "null";
string fmt = o is string ? "\"{0}\"" : "{0}";
return string.Format(System.Globalization.CultureInfo.InvariantCulture, fmt, o);
}
#endregion
#region Operator Overloads
/// <summary>
/// This operator creates a constraint that is satisfied only if both
/// argument constraints are satisfied.
/// </summary>
public static Constraint operator &(Constraint left, Constraint right)
{
IResolveConstraint l = (IResolveConstraint)left;
IResolveConstraint r = (IResolveConstraint)right;
return new AndConstraint(l.Resolve(), r.Resolve());
}
/// <summary>
/// This operator creates a constraint that is satisfied if either
/// of the argument constraints is satisfied.
/// </summary>
public static Constraint operator |(Constraint left, Constraint right)
{
IResolveConstraint l = (IResolveConstraint)left;
IResolveConstraint r = (IResolveConstraint)right;
return new OrConstraint(l.Resolve(), r.Resolve());
}
/// <summary>
/// This operator creates a constraint that is satisfied if the
/// argument constraint is not satisfied.
/// </summary>
public static Constraint operator !(Constraint constraint)
{
IResolveConstraint r = constraint as IResolveConstraint;
return new NotConstraint(r == null ? new NullConstraint() : r.Resolve());
}
#endregion
#region Binary Operators
/// <summary>
/// Returns a ConstraintExpression by appending And
/// to the current constraint.
/// </summary>
public ConstraintExpression And
{
get
{
ConstraintBuilder builder = this.builder;
if (builder == null)
{
builder = new ConstraintBuilder();
builder.Append(this);
}
builder.Append(new AndOperator());
return new ConstraintExpression(builder);
}
}
/// <summary>
/// Returns a ConstraintExpression by appending And
/// to the current constraint.
/// </summary>
public ConstraintExpression With
{
get { return this.And; }
}
/// <summary>
/// Returns a ConstraintExpression by appending Or
/// to the current constraint.
/// </summary>
public ConstraintExpression Or
{
get
{
ConstraintBuilder builder = this.builder;
if (builder == null)
{
builder = new ConstraintBuilder();
builder.Append(this);
}
builder.Append(new OrOperator());
return new ConstraintExpression(builder);
}
}
#endregion
#region IResolveConstraint Members
Constraint IResolveConstraint.Resolve()
{
return builder == null ? this : builder.Resolve();
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
// (C) 2002 Ville Palo
// (C) 2003 Martin Willemoes Hansen
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using Xunit;
using System.Xml;
using System.Data.SqlTypes;
using System.Globalization;
namespace System.Data.Tests.SqlTypes
{
public class SqlByteTest
{
private const string Error = " does not work correctly";
// Test constructor
[Fact]
public void Create()
{
byte b = 29;
SqlByte TestByte = new SqlByte(b);
Assert.Equal((byte)29, TestByte.Value);
}
// Test public fields
[Fact]
public void PublicFields()
{
Assert.Equal((SqlByte)255, SqlByte.MaxValue);
Assert.Equal((SqlByte)0, SqlByte.MinValue);
Assert.True(SqlByte.Null.IsNull);
Assert.Equal((byte)0, SqlByte.Zero.Value);
}
// Test properties
[Fact]
public void Properties()
{
SqlByte TestByte = new SqlByte(54);
SqlByte TestByte2 = new SqlByte(1);
Assert.True(SqlByte.Null.IsNull);
Assert.Equal((byte)54, TestByte.Value);
Assert.Equal((byte)1, TestByte2.Value);
}
// PUBLIC STATIC METHODS
[Fact]
public void AddMethod()
{
SqlByte TestByte64 = new SqlByte(64);
SqlByte TestByte0 = new SqlByte(0);
SqlByte TestByte164 = new SqlByte(164);
SqlByte TestByte255 = new SqlByte(255);
Assert.Equal((byte)64, SqlByte.Add(TestByte64, TestByte0).Value);
Assert.Equal((byte)228, SqlByte.Add(TestByte64, TestByte164).Value);
Assert.Equal((byte)164, SqlByte.Add(TestByte0, TestByte164).Value);
Assert.Equal((byte)255, SqlByte.Add(TestByte255, TestByte0).Value);
try
{
SqlByte.Add(TestByte255, TestByte64);
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
}
[Fact]
public void BitwiseAndMethod()
{
SqlByte TestByte2 = new SqlByte(2);
SqlByte TestByte1 = new SqlByte(1);
SqlByte TestByte62 = new SqlByte(62);
SqlByte TestByte255 = new SqlByte(255);
Assert.Equal((byte)0, SqlByte.BitwiseAnd(TestByte2, TestByte1).Value);
Assert.Equal((byte)0, SqlByte.BitwiseAnd(TestByte1, TestByte62).Value);
Assert.Equal((byte)2, SqlByte.BitwiseAnd(TestByte62, TestByte2).Value);
Assert.Equal((byte)1, SqlByte.BitwiseAnd(TestByte1, TestByte255).Value);
Assert.Equal((byte)62, SqlByte.BitwiseAnd(TestByte62, TestByte255).Value);
}
[Fact]
public void BitwiseOrMethod()
{
SqlByte TestByte2 = new SqlByte(2);
SqlByte TestByte1 = new SqlByte(1);
SqlByte TestByte62 = new SqlByte(62);
SqlByte TestByte255 = new SqlByte(255);
Assert.Equal((byte)3, SqlByte.BitwiseOr(TestByte2, TestByte1).Value);
Assert.Equal((byte)63, SqlByte.BitwiseOr(TestByte1, TestByte62).Value);
Assert.Equal((byte)62, SqlByte.BitwiseOr(TestByte62, TestByte2).Value);
Assert.Equal((byte)255, SqlByte.BitwiseOr(TestByte1, TestByte255).Value);
Assert.Equal((byte)255, SqlByte.BitwiseOr(TestByte62, TestByte255).Value);
}
[Fact]
public void CompareTo()
{
SqlByte TestByte13 = new SqlByte(13);
SqlByte TestByte10 = new SqlByte(10);
SqlByte TestByte10II = new SqlByte(10);
SqlString TestString = new SqlString("This is a test");
Assert.True(TestByte13.CompareTo(TestByte10) > 0);
Assert.True(TestByte10.CompareTo(TestByte13) < 0);
Assert.True(TestByte10.CompareTo(TestByte10II) == 0);
try
{
TestByte13.CompareTo(TestString);
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(ArgumentException), e.GetType());
}
}
[Fact]
public void DivideMethod()
{
SqlByte TestByte13 = new SqlByte(13);
SqlByte TestByte0 = new SqlByte(0);
SqlByte TestByte2 = new SqlByte(2);
SqlByte TestByte180 = new SqlByte(180);
SqlByte TestByte3 = new SqlByte(3);
Assert.Equal((byte)6, SqlByte.Divide(TestByte13, TestByte2).Value);
Assert.Equal((byte)90, SqlByte.Divide(TestByte180, TestByte2).Value);
Assert.Equal((byte)60, SqlByte.Divide(TestByte180, TestByte3).Value);
Assert.Equal((byte)0, SqlByte.Divide(TestByte13, TestByte180).Value);
Assert.Equal((byte)0, SqlByte.Divide(TestByte13, TestByte180).Value);
try
{
SqlByte.Divide(TestByte13, TestByte0);
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(DivideByZeroException), e.GetType());
}
}
[Fact]
public void EqualsMethod()
{
SqlByte TestByte0 = new SqlByte(0);
SqlByte TestByte158 = new SqlByte(158);
SqlByte TestByte180 = new SqlByte(180);
SqlByte TestByte180II = new SqlByte(180);
Assert.True(!TestByte0.Equals(TestByte158));
Assert.True(!TestByte158.Equals(TestByte180));
Assert.True(!TestByte180.Equals(new SqlString("TEST")));
Assert.True(TestByte180.Equals(TestByte180II));
}
[Fact]
public void StaticEqualsMethod()
{
SqlByte TestByte34 = new SqlByte(34);
SqlByte TestByte34II = new SqlByte(34);
SqlByte TestByte15 = new SqlByte(15);
Assert.True(SqlByte.Equals(TestByte34, TestByte34II).Value);
Assert.True(!SqlByte.Equals(TestByte34, TestByte15).Value);
Assert.True(!SqlByte.Equals(TestByte15, TestByte34II).Value);
}
[Fact]
public void GetHashCodeTest()
{
SqlByte TestByte15 = new SqlByte(15);
SqlByte TestByte216 = new SqlByte(216);
Assert.Equal(15, TestByte15.GetHashCode());
Assert.Equal(216, TestByte216.GetHashCode());
}
[Fact]
public void GetTypeTest()
{
SqlByte TestByte = new SqlByte(84);
Assert.Equal("System.Data.SqlTypes.SqlByte", TestByte.GetType().ToString());
}
[Fact]
public void GreaterThan()
{
SqlByte TestByte10 = new SqlByte(10);
SqlByte TestByte10II = new SqlByte(10);
SqlByte TestByte110 = new SqlByte(110);
Assert.True(!SqlByte.GreaterThan(TestByte10, TestByte110).Value);
Assert.True(SqlByte.GreaterThan(TestByte110, TestByte10).Value);
Assert.True(!SqlByte.GreaterThan(TestByte10II, TestByte10).Value);
}
[Fact]
public void GreaterThanOrEqual()
{
SqlByte TestByte10 = new SqlByte(10);
SqlByte TestByte10II = new SqlByte(10);
SqlByte TestByte110 = new SqlByte(110);
Assert.True(!SqlByte.GreaterThanOrEqual(TestByte10, TestByte110).Value);
Assert.True(SqlByte.GreaterThanOrEqual(TestByte110, TestByte10).Value);
Assert.True(SqlByte.GreaterThanOrEqual(TestByte10II, TestByte10).Value);
}
[Fact]
public void LessThan()
{
SqlByte TestByte10 = new SqlByte(10);
SqlByte TestByte10II = new SqlByte(10);
SqlByte TestByte110 = new SqlByte(110);
Assert.True(SqlByte.LessThan(TestByte10, TestByte110).Value);
Assert.True(!SqlByte.LessThan(TestByte110, TestByte10).Value);
Assert.True(!SqlByte.LessThan(TestByte10II, TestByte10).Value);
}
[Fact]
public void LessThanOrEqual()
{
SqlByte TestByte10 = new SqlByte(10);
SqlByte TestByte10II = new SqlByte(10);
SqlByte TestByte110 = new SqlByte(110);
Assert.True(SqlByte.LessThanOrEqual(TestByte10, TestByte110).Value);
Assert.True(!SqlByte.LessThanOrEqual(TestByte110, TestByte10).Value);
Assert.True(SqlByte.LessThanOrEqual(TestByte10II, TestByte10).Value);
Assert.True(SqlByte.LessThanOrEqual(TestByte10II, SqlByte.Null).IsNull);
}
[Fact]
public void Mod()
{
SqlByte TestByte132 = new SqlByte(132);
SqlByte TestByte10 = new SqlByte(10);
SqlByte TestByte200 = new SqlByte(200);
Assert.Equal((SqlByte)2, SqlByte.Mod(TestByte132, TestByte10));
Assert.Equal((SqlByte)10, SqlByte.Mod(TestByte10, TestByte200));
Assert.Equal((SqlByte)0, SqlByte.Mod(TestByte200, TestByte10));
Assert.Equal((SqlByte)68, SqlByte.Mod(TestByte200, TestByte132));
}
[Fact]
public void Multiply()
{
SqlByte TestByte12 = new SqlByte(12);
SqlByte TestByte2 = new SqlByte(2);
SqlByte TestByte128 = new SqlByte(128);
Assert.Equal((byte)24, SqlByte.Multiply(TestByte12, TestByte2).Value);
Assert.Equal((byte)24, SqlByte.Multiply(TestByte2, TestByte12).Value);
try
{
SqlByte.Multiply(TestByte128, TestByte2);
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
}
[Fact]
public void NotEquals()
{
SqlByte TestByte12 = new SqlByte(12);
SqlByte TestByte128 = new SqlByte(128);
SqlByte TestByte128II = new SqlByte(128);
Assert.True(SqlByte.NotEquals(TestByte12, TestByte128).Value);
Assert.True(SqlByte.NotEquals(TestByte128, TestByte12).Value);
Assert.True(SqlByte.NotEquals(TestByte128II, TestByte12).Value);
Assert.True(!SqlByte.NotEquals(TestByte128II, TestByte128).Value);
Assert.True(!SqlByte.NotEquals(TestByte128, TestByte128II).Value);
}
[Fact]
public void OnesComplement()
{
SqlByte TestByte12 = new SqlByte(12);
SqlByte TestByte128 = new SqlByte(128);
Assert.Equal((SqlByte)243, SqlByte.OnesComplement(TestByte12));
Assert.Equal((SqlByte)127, SqlByte.OnesComplement(TestByte128));
}
[Fact]
public void Parse()
{
try
{
SqlByte.Parse(null);
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(ArgumentNullException), e.GetType());
}
try
{
SqlByte.Parse("not-a-number");
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(FormatException), e.GetType());
}
try
{
int OverInt = (int)SqlByte.MaxValue + 1;
SqlByte.Parse(OverInt.ToString());
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
Assert.Equal((byte)150, SqlByte.Parse("150").Value);
}
[Fact]
public void Subtract()
{
SqlByte TestByte12 = new SqlByte(12);
SqlByte TestByte128 = new SqlByte(128);
Assert.Equal((byte)116, SqlByte.Subtract(TestByte128, TestByte12).Value);
try
{
SqlByte.Subtract(TestByte12, TestByte128);
}
catch (Exception e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
}
[Fact]
public void ToSqlBoolean()
{
SqlByte TestByte12 = new SqlByte(12);
SqlByte TestByte0 = new SqlByte(0);
SqlByte TestByteNull = SqlByte.Null;
Assert.True(TestByte12.ToSqlBoolean().Value);
Assert.True(!TestByte0.ToSqlBoolean().Value);
Assert.True(TestByteNull.ToSqlBoolean().IsNull);
}
[Fact]
public void ToSqlDecimal()
{
SqlByte TestByte12 = new SqlByte(12);
SqlByte TestByte0 = new SqlByte(0);
SqlByte TestByte228 = new SqlByte(228);
Assert.Equal(12, TestByte12.ToSqlDecimal().Value);
Assert.Equal(0, TestByte0.ToSqlDecimal().Value);
Assert.Equal(228, TestByte228.ToSqlDecimal().Value);
}
[Fact]
public void ToSqlDouble()
{
SqlByte TestByte12 = new SqlByte(12);
SqlByte TestByte0 = new SqlByte(0);
SqlByte TestByte228 = new SqlByte(228);
Assert.Equal(12, TestByte12.ToSqlDouble().Value);
Assert.Equal(0, TestByte0.ToSqlDouble().Value);
Assert.Equal(228, TestByte228.ToSqlDouble().Value);
}
[Fact]
public void ToSqlInt16()
{
SqlByte TestByte12 = new SqlByte(12);
SqlByte TestByte0 = new SqlByte(0);
SqlByte TestByte228 = new SqlByte(228);
Assert.Equal((short)12, TestByte12.ToSqlInt16().Value);
Assert.Equal((short)0, TestByte0.ToSqlInt16().Value);
Assert.Equal((short)228, TestByte228.ToSqlInt16().Value);
}
[Fact]
public void ToSqlInt32()
{
SqlByte TestByte12 = new SqlByte(12);
SqlByte TestByte0 = new SqlByte(0);
SqlByte TestByte228 = new SqlByte(228);
Assert.Equal(12, TestByte12.ToSqlInt32().Value);
Assert.Equal(0, TestByte0.ToSqlInt32().Value);
Assert.Equal(228, TestByte228.ToSqlInt32().Value);
}
[Fact]
public void ToSqlInt64()
{
SqlByte TestByte12 = new SqlByte(12);
SqlByte TestByte0 = new SqlByte(0);
SqlByte TestByte228 = new SqlByte(228);
Assert.Equal(12, TestByte12.ToSqlInt64().Value);
Assert.Equal(0, TestByte0.ToSqlInt64().Value);
Assert.Equal(228, TestByte228.ToSqlInt64().Value);
}
[Fact]
public void ToSqlMoney()
{
SqlByte TestByte12 = new SqlByte(12);
SqlByte TestByte0 = new SqlByte(0);
SqlByte TestByte228 = new SqlByte(228);
Assert.Equal(12.0000M, TestByte12.ToSqlMoney().Value);
Assert.Equal(0, TestByte0.ToSqlMoney().Value);
Assert.Equal(228.0000M, TestByte228.ToSqlMoney().Value);
}
[Fact]
public void ToSqlSingle()
{
SqlByte TestByte12 = new SqlByte(12);
SqlByte TestByte0 = new SqlByte(0);
SqlByte TestByte228 = new SqlByte(228);
Assert.Equal(12, TestByte12.ToSqlSingle().Value);
Assert.Equal(0, TestByte0.ToSqlSingle().Value);
Assert.Equal(228, TestByte228.ToSqlSingle().Value);
}
[Fact]
public void ToSqlString()
{
SqlByte TestByte12 = new SqlByte(12);
SqlByte TestByte0 = new SqlByte(0);
SqlByte TestByte228 = new SqlByte(228);
Assert.Equal("12", TestByte12.ToSqlString().Value);
Assert.Equal("0", TestByte0.ToSqlString().Value);
Assert.Equal("228", TestByte228.ToSqlString().Value);
}
[Fact]
public void ToStringTest()
{
SqlByte TestByte12 = new SqlByte(12);
SqlByte TestByte0 = new SqlByte(0);
SqlByte TestByte228 = new SqlByte(228);
Assert.Equal("12", TestByte12.ToString());
Assert.Equal("0", TestByte0.ToString());
Assert.Equal("228", TestByte228.ToString());
}
[Fact]
public void TestXor()
{
SqlByte TestByte14 = new SqlByte(14);
SqlByte TestByte58 = new SqlByte(58);
SqlByte TestByte130 = new SqlByte(130);
Assert.Equal((byte)52, SqlByte.Xor(TestByte14, TestByte58).Value);
Assert.Equal((byte)140, SqlByte.Xor(TestByte14, TestByte130).Value);
Assert.Equal((byte)184, SqlByte.Xor(TestByte58, TestByte130).Value);
}
// OPERATORS
[Fact]
public void AdditionOperator()
{
SqlByte TestByte24 = new SqlByte(24);
SqlByte TestByte64 = new SqlByte(64);
SqlByte TestByte255 = new SqlByte(255);
Assert.Equal((SqlByte)88, TestByte24 + TestByte64);
try
{
SqlByte result = TestByte64 + TestByte255;
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
}
[Fact]
public void BitwiseAndOperator()
{
SqlByte TestByte2 = new SqlByte(2);
SqlByte TestByte4 = new SqlByte(4);
SqlByte TestByte255 = new SqlByte(255);
Assert.Equal((SqlByte)0, TestByte2 & TestByte4);
Assert.Equal((SqlByte)2, TestByte2 & TestByte255);
}
[Fact]
public void BitwiseOrOperator()
{
SqlByte TestByte2 = new SqlByte(2);
SqlByte TestByte4 = new SqlByte(4);
SqlByte TestByte255 = new SqlByte(255);
Assert.Equal((SqlByte)6, TestByte2 | TestByte4);
Assert.Equal((SqlByte)255, TestByte2 | TestByte255);
}
[Fact]
public void DivisionOperator()
{
SqlByte TestByte2 = new SqlByte(2);
SqlByte TestByte4 = new SqlByte(4);
SqlByte TestByte255 = new SqlByte(255);
SqlByte TestByte0 = new SqlByte(0);
Assert.Equal((SqlByte)2, TestByte4 / TestByte2);
Assert.Equal((SqlByte)127, TestByte255 / TestByte2);
try
{
TestByte2 = TestByte255 / TestByte0;
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(DivideByZeroException), e.GetType());
}
}
[Fact]
public void EqualityOperator()
{
SqlByte TestByte15 = new SqlByte(15);
SqlByte TestByte15II = new SqlByte(15);
SqlByte TestByte255 = new SqlByte(255);
Assert.True((TestByte15 == TestByte15II).Value);
Assert.True(!(TestByte15 == TestByte255).Value);
Assert.True(!(TestByte15 != TestByte15II).Value);
Assert.True((TestByte15 != TestByte255).Value);
}
[Fact]
public void ExclusiveOrOperator()
{
SqlByte TestByte15 = new SqlByte(15);
SqlByte TestByte10 = new SqlByte(10);
SqlByte TestByte255 = new SqlByte(255);
Assert.Equal((SqlByte)5, (TestByte15 ^ TestByte10));
Assert.Equal((SqlByte)240, (TestByte15 ^ TestByte255));
}
[Fact]
public void ThanOrEqualOperators()
{
SqlByte TestByte165 = new SqlByte(165);
SqlByte TestByte100 = new SqlByte(100);
SqlByte TestByte100II = new SqlByte(100);
SqlByte TestByte255 = new SqlByte(255);
Assert.True((TestByte165 > TestByte100).Value);
Assert.True(!(TestByte165 > TestByte255).Value);
Assert.True(!(TestByte100 > TestByte100II).Value);
Assert.True(!(TestByte165 >= TestByte255).Value);
Assert.True((TestByte255 >= TestByte165).Value);
Assert.True((TestByte100 >= TestByte100II).Value);
Assert.True(!(TestByte165 < TestByte100).Value);
Assert.True((TestByte165 < TestByte255).Value);
Assert.True(!(TestByte100 < TestByte100II).Value);
Assert.True((TestByte165 <= TestByte255).Value);
Assert.True(!(TestByte255 <= TestByte165).Value);
Assert.True((TestByte100 <= TestByte100II).Value);
}
[Fact]
public void MultiplicationOperator()
{
SqlByte TestByte4 = new SqlByte(4);
SqlByte TestByte12 = new SqlByte(12);
SqlByte TestByte128 = new SqlByte(128);
Assert.Equal((SqlByte)48, TestByte4 * TestByte12);
try
{
SqlByte test = (TestByte128 * TestByte4);
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
}
[Fact]
public void OnesComplementOperator()
{
SqlByte TestByte12 = new SqlByte(12);
SqlByte TestByte128 = new SqlByte(128);
Assert.Equal((SqlByte)243, ~TestByte12);
Assert.Equal((SqlByte)127, ~TestByte128);
}
[Fact]
public void SubtractionOperator()
{
SqlByte TestByte4 = new SqlByte(4);
SqlByte TestByte12 = new SqlByte(12);
SqlByte TestByte128 = new SqlByte(128);
Assert.Equal((SqlByte)8, TestByte12 - TestByte4);
try
{
SqlByte test = TestByte4 - TestByte128;
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
}
[Fact]
public void SqlBooleanToSqlByte()
{
SqlBoolean TestBoolean = new SqlBoolean(true);
SqlByte TestByte;
TestByte = (SqlByte)TestBoolean;
Assert.Equal((byte)1, TestByte.Value);
}
[Fact]
public void SqlByteToByte()
{
SqlByte TestByte = new SqlByte(12);
byte test = (byte)TestByte;
Assert.Equal((byte)12, test);
}
[Fact]
public void SqlDecimalToSqlByte()
{
SqlDecimal TestDecimal64 = new SqlDecimal(64);
SqlDecimal TestDecimal900 = new SqlDecimal(900);
Assert.Equal((byte)64, ((SqlByte)TestDecimal64).Value);
try
{
SqlByte test = (SqlByte)TestDecimal900;
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
}
[Fact]
public void SqlDoubleToSqlByte()
{
SqlDouble TestDouble64 = new SqlDouble(64);
SqlDouble TestDouble900 = new SqlDouble(900);
Assert.Equal((byte)64, ((SqlByte)TestDouble64).Value);
try
{
SqlByte test = (SqlByte)TestDouble900;
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
}
[Fact]
public void SqlInt16ToSqlByte()
{
SqlInt16 TestInt1664 = new SqlInt16(64);
SqlInt16 TestInt16900 = new SqlInt16(900);
Assert.Equal((byte)64, ((SqlByte)TestInt1664).Value);
try
{
SqlByte test = (SqlByte)TestInt16900;
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
}
[Fact]
public void SqlInt32ToSqlByte()
{
SqlInt32 TestInt3264 = new SqlInt32(64);
SqlInt32 TestInt32900 = new SqlInt32(900);
Assert.Equal((byte)64, ((SqlByte)TestInt3264).Value);
try
{
SqlByte test = (SqlByte)TestInt32900;
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
}
[Fact]
public void SqlInt64ToSqlByte()
{
SqlInt64 TestInt6464 = new SqlInt64(64);
SqlInt64 TestInt64900 = new SqlInt64(900);
Assert.Equal((byte)64, ((SqlByte)TestInt6464).Value);
try
{
SqlByte test = (SqlByte)TestInt64900;
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
}
[Fact]
public void SqlMoneyToSqlByte()
{
SqlMoney TestMoney64 = new SqlMoney(64);
SqlMoney TestMoney900 = new SqlMoney(900);
Assert.Equal((byte)64, ((SqlByte)TestMoney64).Value);
try
{
SqlByte test = (SqlByte)TestMoney900;
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
}
[Fact]
public void SqlSingleToSqlByte()
{
SqlSingle TestSingle64 = new SqlSingle(64);
SqlSingle TestSingle900 = new SqlSingle(900);
Assert.Equal((byte)64, ((SqlByte)TestSingle64).Value);
try
{
SqlByte test = (SqlByte)TestSingle900;
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
}
[Fact]
public void SqlStringToSqlByte()
{
SqlString TestString = new SqlString("Test string");
SqlString TestString100 = new SqlString("100");
SqlString TestString1000 = new SqlString("1000");
Assert.Equal((byte)100, ((SqlByte)TestString100).Value);
try
{
SqlByte test = (SqlByte)TestString1000;
}
catch (Exception e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
try
{
SqlByte test = (SqlByte)TestString;
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(FormatException), e.GetType());
}
}
[Fact]
public void ByteToSqlByte()
{
byte TestByte = 14;
Assert.Equal((byte)14, ((SqlByte)TestByte).Value);
}
[Fact]
public void GetXsdTypeTest()
{
XmlQualifiedName qualifiedName = SqlByte.GetXsdType(null);
Assert.Equal("unsignedByte", qualifiedName.Name);
}
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
namespace BinxEd
{
/// <summary>
/// Summary description for FormStruct.
/// </summary>
public class FormStruct : System.Windows.Forms.Form
{
private string typeName_;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox textBoxTypeName;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox textBoxBlockSize;
private System.Windows.Forms.Button buttonOK;
private System.Windows.Forms.Button buttonCancel;
private System.Windows.Forms.Label label2;
private EditListView listView1;
private System.Windows.Forms.Button buttonDelItem;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public FormStruct()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.textBoxTypeName = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.textBoxBlockSize = new System.Windows.Forms.TextBox();
this.buttonOK = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.label2 = new System.Windows.Forms.Label();
this.listView1 = new BinxEd.EditListView();
this.buttonDelItem = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// label1
//
this.label1.Location = new System.Drawing.Point(16, 8);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(72, 24);
this.label1.TabIndex = 0;
this.label1.Text = "Type Name: ";
//
// textBoxTypeName
//
this.textBoxTypeName.Location = new System.Drawing.Point(96, 8);
this.textBoxTypeName.Name = "textBoxTypeName";
this.textBoxTypeName.Size = new System.Drawing.Size(176, 20);
this.textBoxTypeName.TabIndex = 1;
this.textBoxTypeName.Text = "MyStruct-1";
//
// label3
//
this.label3.Location = new System.Drawing.Point(16, 40);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(64, 24);
this.label3.TabIndex = 0;
this.label3.Text = "Block Size:";
//
// textBoxBlockSize
//
this.textBoxBlockSize.Location = new System.Drawing.Point(96, 40);
this.textBoxBlockSize.Name = "textBoxBlockSize";
this.textBoxBlockSize.Size = new System.Drawing.Size(176, 20);
this.textBoxBlockSize.TabIndex = 3;
this.textBoxBlockSize.Text = "0";
//
// buttonOK
//
this.buttonOK.DialogResult = System.Windows.Forms.DialogResult.OK;
this.buttonOK.Location = new System.Drawing.Point(120, 224);
this.buttonOK.Name = "buttonOK";
this.buttonOK.Size = new System.Drawing.Size(72, 24);
this.buttonOK.TabIndex = 4;
this.buttonOK.Text = "OK";
//
// buttonCancel
//
this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.buttonCancel.Location = new System.Drawing.Point(200, 224);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(72, 24);
this.buttonCancel.TabIndex = 4;
this.buttonCancel.Text = "Cancel";
//
// label2
//
this.label2.Location = new System.Drawing.Point(16, 72);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(88, 16);
this.label2.TabIndex = 5;
this.label2.Text = "Members";
//
// listView1
//
this.listView1.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.listView1.GridLines = true;
this.listView1.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable;
this.listView1.LabelWrap = false;
this.listView1.Location = new System.Drawing.Point(16, 88);
this.listView1.MultiSelect = false;
this.listView1.Name = "listView1";
this.listView1.Scrollable = false;
this.listView1.Size = new System.Drawing.Size(256, 128);
this.listView1.TabIndex = 6;
this.listView1.View = System.Windows.Forms.View.Details;
//
// buttonDelItem
//
this.buttonDelItem.Location = new System.Drawing.Point(16, 224);
this.buttonDelItem.Name = "buttonDelItem";
this.buttonDelItem.Size = new System.Drawing.Size(24, 24);
this.buttonDelItem.TabIndex = 7;
this.buttonDelItem.Text = "X";
this.buttonDelItem.Click += new System.EventHandler(this.buttonDelItem_Click);
//
// FormStruct
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(288, 263);
this.Controls.Add(this.buttonDelItem);
this.Controls.Add(this.listView1);
this.Controls.Add(this.label2);
this.Controls.Add(this.buttonOK);
this.Controls.Add(this.textBoxBlockSize);
this.Controls.Add(this.textBoxTypeName);
this.Controls.Add(this.label1);
this.Controls.Add(this.label3);
this.Controls.Add(this.buttonCancel);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Name = "FormStruct";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Define a struct type";
this.Closing += new System.ComponentModel.CancelEventHandler(this.FormStruct_Closing);
this.Load += new System.EventHandler(this.FormStruct_Load);
this.ResumeLayout(false);
}
#endregion
private void FormStruct_Load(object sender, System.EventArgs e)
{
listView1.setColumnHeaders(new string[]{"Type","Variable Name"}, new int[]{150,listView1.Width-154});
if (typeName_ != null)
{
textBoxTypeName.Text = typeName_;
}
}
public string TypeName
{
get { return textBoxTypeName.Text; }
set { typeName_ = value; }
}
/// <summary>
/// Change label1 to either "Type Name" or "Var Name".
/// </summary>
/// <param name="text"></param>
public void ChangeLabel(string text)
{
label1.Text = text;
}
public string BlockSize
{
get { return textBoxBlockSize.Text; }
}
public void setDataTypeSource(string[] dataTypes)
{
listView1.addDataTypes(dataTypes);
}
public System.Windows.Forms.ListView.ListViewItemCollection getMemberItems()
{
return this.listView1.Items;
}
/// <summary>
/// Delete the selected member.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonDelItem_Click(object sender, System.EventArgs e)
{
if (listView1.SelectedItems.Count > 0)
{
foreach (ListViewItem itm in listView1.SelectedItems)
{
listView1.Items.Remove(itm);
}
}
}
/// <summary>
/// Validate before closing window.
/// </summary>
/// <remarks>The following are validated:
/// <ul>
/// <li>"There must be at least one member specified</li>
/// <li>If it is used to define a type, must give a type name</li>
/// <li>if blocksize is empty, set it to zero</li>
/// </ul>
/// </remarks>
/// <param name="sender"></param>
/// <param name="e"></param>
private void FormStruct_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if (this.DialogResult == DialogResult.Cancel)
{
return;
}
if (listView1.Items.Count <= 0)
{
MessageBox.Show(this, "At least have one member");
e.Cancel = true;
return;
}
if (label1.Text.Equals("Type Name: "))
{
if (textBoxTypeName.Text.Trim().Equals(""))
{
MessageBox.Show(this, "Must give a type name!");
e.Cancel = true;
return;
}
}
if (textBoxBlockSize.Text.Trim().Equals(""))
{
textBoxBlockSize.Text = "0";
}
}
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
/// <summary>
/// SyncStreamResource
/// </summary>
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
namespace Twilio.Rest.Sync.V1.Service
{
public class SyncStreamResource : Resource
{
private static Request BuildFetchRequest(FetchSyncStreamOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Sync,
"/v1/Services/" + options.PathServiceSid + "/Streams/" + options.PathSid + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Fetch a specific Stream.
/// </summary>
/// <param name="options"> Fetch SyncStream parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of SyncStream </returns>
public static SyncStreamResource Fetch(FetchSyncStreamOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// Fetch a specific Stream.
/// </summary>
/// <param name="options"> Fetch SyncStream parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of SyncStream </returns>
public static async System.Threading.Tasks.Task<SyncStreamResource> FetchAsync(FetchSyncStreamOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// Fetch a specific Stream.
/// </summary>
/// <param name="pathServiceSid"> The SID of the Sync Service with the Sync Stream resource to fetch </param>
/// <param name="pathSid"> The SID of the Stream resource to fetch </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of SyncStream </returns>
public static SyncStreamResource Fetch(string pathServiceSid, string pathSid, ITwilioRestClient client = null)
{
var options = new FetchSyncStreamOptions(pathServiceSid, pathSid);
return Fetch(options, client);
}
#if !NET35
/// <summary>
/// Fetch a specific Stream.
/// </summary>
/// <param name="pathServiceSid"> The SID of the Sync Service with the Sync Stream resource to fetch </param>
/// <param name="pathSid"> The SID of the Stream resource to fetch </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of SyncStream </returns>
public static async System.Threading.Tasks.Task<SyncStreamResource> FetchAsync(string pathServiceSid,
string pathSid,
ITwilioRestClient client = null)
{
var options = new FetchSyncStreamOptions(pathServiceSid, pathSid);
return await FetchAsync(options, client);
}
#endif
private static Request BuildDeleteRequest(DeleteSyncStreamOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Delete,
Rest.Domain.Sync,
"/v1/Services/" + options.PathServiceSid + "/Streams/" + options.PathSid + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Delete a specific Stream.
/// </summary>
/// <param name="options"> Delete SyncStream parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of SyncStream </returns>
public static bool Delete(DeleteSyncStreamOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildDeleteRequest(options, client));
return response.StatusCode == System.Net.HttpStatusCode.NoContent;
}
#if !NET35
/// <summary>
/// Delete a specific Stream.
/// </summary>
/// <param name="options"> Delete SyncStream parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of SyncStream </returns>
public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteSyncStreamOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildDeleteRequest(options, client));
return response.StatusCode == System.Net.HttpStatusCode.NoContent;
}
#endif
/// <summary>
/// Delete a specific Stream.
/// </summary>
/// <param name="pathServiceSid"> The SID of the Sync Service with the Sync Stream resource to delete </param>
/// <param name="pathSid"> The SID of the Stream resource to delete </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of SyncStream </returns>
public static bool Delete(string pathServiceSid, string pathSid, ITwilioRestClient client = null)
{
var options = new DeleteSyncStreamOptions(pathServiceSid, pathSid);
return Delete(options, client);
}
#if !NET35
/// <summary>
/// Delete a specific Stream.
/// </summary>
/// <param name="pathServiceSid"> The SID of the Sync Service with the Sync Stream resource to delete </param>
/// <param name="pathSid"> The SID of the Stream resource to delete </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of SyncStream </returns>
public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathServiceSid,
string pathSid,
ITwilioRestClient client = null)
{
var options = new DeleteSyncStreamOptions(pathServiceSid, pathSid);
return await DeleteAsync(options, client);
}
#endif
private static Request BuildCreateRequest(CreateSyncStreamOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.Sync,
"/v1/Services/" + options.PathServiceSid + "/Streams",
postParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Create a new Stream.
/// </summary>
/// <param name="options"> Create SyncStream parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of SyncStream </returns>
public static SyncStreamResource Create(CreateSyncStreamOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// Create a new Stream.
/// </summary>
/// <param name="options"> Create SyncStream parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of SyncStream </returns>
public static async System.Threading.Tasks.Task<SyncStreamResource> CreateAsync(CreateSyncStreamOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// Create a new Stream.
/// </summary>
/// <param name="pathServiceSid"> The SID of the Sync Service to create the new Stream in </param>
/// <param name="uniqueName"> An application-defined string that uniquely identifies the resource </param>
/// <param name="ttl"> How long, in seconds, before the Stream expires and is deleted </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of SyncStream </returns>
public static SyncStreamResource Create(string pathServiceSid,
string uniqueName = null,
int? ttl = null,
ITwilioRestClient client = null)
{
var options = new CreateSyncStreamOptions(pathServiceSid){UniqueName = uniqueName, Ttl = ttl};
return Create(options, client);
}
#if !NET35
/// <summary>
/// Create a new Stream.
/// </summary>
/// <param name="pathServiceSid"> The SID of the Sync Service to create the new Stream in </param>
/// <param name="uniqueName"> An application-defined string that uniquely identifies the resource </param>
/// <param name="ttl"> How long, in seconds, before the Stream expires and is deleted </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of SyncStream </returns>
public static async System.Threading.Tasks.Task<SyncStreamResource> CreateAsync(string pathServiceSid,
string uniqueName = null,
int? ttl = null,
ITwilioRestClient client = null)
{
var options = new CreateSyncStreamOptions(pathServiceSid){UniqueName = uniqueName, Ttl = ttl};
return await CreateAsync(options, client);
}
#endif
private static Request BuildUpdateRequest(UpdateSyncStreamOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.Sync,
"/v1/Services/" + options.PathServiceSid + "/Streams/" + options.PathSid + "",
postParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Update a specific Stream.
/// </summary>
/// <param name="options"> Update SyncStream parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of SyncStream </returns>
public static SyncStreamResource Update(UpdateSyncStreamOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildUpdateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// Update a specific Stream.
/// </summary>
/// <param name="options"> Update SyncStream parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of SyncStream </returns>
public static async System.Threading.Tasks.Task<SyncStreamResource> UpdateAsync(UpdateSyncStreamOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildUpdateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// Update a specific Stream.
/// </summary>
/// <param name="pathServiceSid"> The SID of the Sync Service with the Sync Stream resource to update </param>
/// <param name="pathSid"> The SID of the Stream resource to update </param>
/// <param name="ttl"> How long, in seconds, before the Stream expires and is deleted </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of SyncStream </returns>
public static SyncStreamResource Update(string pathServiceSid,
string pathSid,
int? ttl = null,
ITwilioRestClient client = null)
{
var options = new UpdateSyncStreamOptions(pathServiceSid, pathSid){Ttl = ttl};
return Update(options, client);
}
#if !NET35
/// <summary>
/// Update a specific Stream.
/// </summary>
/// <param name="pathServiceSid"> The SID of the Sync Service with the Sync Stream resource to update </param>
/// <param name="pathSid"> The SID of the Stream resource to update </param>
/// <param name="ttl"> How long, in seconds, before the Stream expires and is deleted </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of SyncStream </returns>
public static async System.Threading.Tasks.Task<SyncStreamResource> UpdateAsync(string pathServiceSid,
string pathSid,
int? ttl = null,
ITwilioRestClient client = null)
{
var options = new UpdateSyncStreamOptions(pathServiceSid, pathSid){Ttl = ttl};
return await UpdateAsync(options, client);
}
#endif
private static Request BuildReadRequest(ReadSyncStreamOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Sync,
"/v1/Services/" + options.PathServiceSid + "/Streams",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Retrieve a list of all Streams in a Service Instance.
/// </summary>
/// <param name="options"> Read SyncStream parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of SyncStream </returns>
public static ResourceSet<SyncStreamResource> Read(ReadSyncStreamOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildReadRequest(options, client));
var page = Page<SyncStreamResource>.FromJson("streams", response.Content);
return new ResourceSet<SyncStreamResource>(page, options, client);
}
#if !NET35
/// <summary>
/// Retrieve a list of all Streams in a Service Instance.
/// </summary>
/// <param name="options"> Read SyncStream parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of SyncStream </returns>
public static async System.Threading.Tasks.Task<ResourceSet<SyncStreamResource>> ReadAsync(ReadSyncStreamOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildReadRequest(options, client));
var page = Page<SyncStreamResource>.FromJson("streams", response.Content);
return new ResourceSet<SyncStreamResource>(page, options, client);
}
#endif
/// <summary>
/// Retrieve a list of all Streams in a Service Instance.
/// </summary>
/// <param name="pathServiceSid"> The SID of the Sync Service with the Stream resources to read </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of SyncStream </returns>
public static ResourceSet<SyncStreamResource> Read(string pathServiceSid,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadSyncStreamOptions(pathServiceSid){PageSize = pageSize, Limit = limit};
return Read(options, client);
}
#if !NET35
/// <summary>
/// Retrieve a list of all Streams in a Service Instance.
/// </summary>
/// <param name="pathServiceSid"> The SID of the Sync Service with the Stream resources to read </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of SyncStream </returns>
public static async System.Threading.Tasks.Task<ResourceSet<SyncStreamResource>> ReadAsync(string pathServiceSid,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadSyncStreamOptions(pathServiceSid){PageSize = pageSize, Limit = limit};
return await ReadAsync(options, client);
}
#endif
/// <summary>
/// Fetch the target page of records
/// </summary>
/// <param name="targetUrl"> API-generated URL for the requested results page </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The target page of records </returns>
public static Page<SyncStreamResource> GetPage(string targetUrl, ITwilioRestClient client)
{
client = client ?? TwilioClient.GetRestClient();
var request = new Request(
HttpMethod.Get,
targetUrl
);
var response = client.Request(request);
return Page<SyncStreamResource>.FromJson("streams", response.Content);
}
/// <summary>
/// Fetch the next page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The next page of records </returns>
public static Page<SyncStreamResource> NextPage(Page<SyncStreamResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetNextPageUrl(Rest.Domain.Sync)
);
var response = client.Request(request);
return Page<SyncStreamResource>.FromJson("streams", response.Content);
}
/// <summary>
/// Fetch the previous page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The previous page of records </returns>
public static Page<SyncStreamResource> PreviousPage(Page<SyncStreamResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetPreviousPageUrl(Rest.Domain.Sync)
);
var response = client.Request(request);
return Page<SyncStreamResource>.FromJson("streams", response.Content);
}
/// <summary>
/// Converts a JSON string into a SyncStreamResource object
/// </summary>
/// <param name="json"> Raw JSON string </param>
/// <returns> SyncStreamResource object represented by the provided JSON </returns>
public static SyncStreamResource FromJson(string json)
{
// Convert all checked exceptions to Runtime
try
{
return JsonConvert.DeserializeObject<SyncStreamResource>(json);
}
catch (JsonException e)
{
throw new ApiException(e.Message, e);
}
}
/// <summary>
/// The unique string that identifies the resource
/// </summary>
[JsonProperty("sid")]
public string Sid { get; private set; }
/// <summary>
/// An application-defined string that uniquely identifies the resource
/// </summary>
[JsonProperty("unique_name")]
public string UniqueName { get; private set; }
/// <summary>
/// The SID of the Account that created the resource
/// </summary>
[JsonProperty("account_sid")]
public string AccountSid { get; private set; }
/// <summary>
/// The SID of the Sync Service that the resource is associated with
/// </summary>
[JsonProperty("service_sid")]
public string ServiceSid { get; private set; }
/// <summary>
/// The absolute URL of the Message Stream resource
/// </summary>
[JsonProperty("url")]
public Uri Url { get; private set; }
/// <summary>
/// The URLs of the Stream's nested resources
/// </summary>
[JsonProperty("links")]
public Dictionary<string, string> Links { get; private set; }
/// <summary>
/// The ISO 8601 date and time in GMT when the Message Stream expires
/// </summary>
[JsonProperty("date_expires")]
public DateTime? DateExpires { get; private set; }
/// <summary>
/// The ISO 8601 date and time in GMT when the resource was created
/// </summary>
[JsonProperty("date_created")]
public DateTime? DateCreated { get; private set; }
/// <summary>
/// The ISO 8601 date and time in GMT when the resource was last updated
/// </summary>
[JsonProperty("date_updated")]
public DateTime? DateUpdated { get; private set; }
/// <summary>
/// The Identity of the Stream's creator
/// </summary>
[JsonProperty("created_by")]
public string CreatedBy { get; private set; }
private SyncStreamResource()
{
}
}
}
| |
/*
* 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.
*/
using System;
using System.Net;
using System.Threading;
using OpenMetaverse.StructuredData;
namespace OpenMetaverse.Http
{
public class EventQueueClient
{
/// <summary>=</summary>
public const int REQUEST_TIMEOUT = 1000 * 120;
public delegate void ConnectedCallback();
public delegate void EventCallback(string eventName, OSDMap body);
public ConnectedCallback OnConnected;
public EventCallback OnEvent;
public bool Running { get { return _Running; } }
protected Uri _Address;
protected bool _Dead;
protected bool _Running;
protected HttpWebRequest _Request;
/// <summary>Number of times we've received an unknown CAPS exception in series.</summary>
private int _errorCount;
/// <summary>For exponential backoff on error.</summary>
private static Random _random = new Random();
public EventQueueClient(Uri eventQueueLocation)
{
_Address = eventQueueLocation;
}
public void Start()
{
_Dead = false;
// Create an EventQueueGet request
OSDMap request = new OSDMap();
request["ack"] = new OSD();
request["done"] = OSD.FromBoolean(false);
byte[] postData = OSDParser.SerializeLLSDXmlBytes(request);
_Request = CapsBase.UploadDataAsync(_Address, null, "application/xml", postData, REQUEST_TIMEOUT, OpenWriteHandler, null, RequestCompletedHandler);
}
public void Stop(bool immediate)
{
_Dead = true;
if (immediate)
_Running = false;
if (_Request != null)
_Request.Abort();
}
void OpenWriteHandler(HttpWebRequest request)
{
_Running = true;
_Request = request;
Logger.DebugLog("Capabilities event queue connected");
// The event queue is starting up for the first time
if (OnConnected != null)
{
try { OnConnected(); }
catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Error, ex); }
}
}
void RequestCompletedHandler(HttpWebRequest request, HttpWebResponse response, byte[] responseData, Exception error)
{
// We don't care about this request now that it has completed
_Request = null;
OSDArray events = null;
int ack = 0;
if (responseData != null)
{
_errorCount = 0;
// Got a response
OSDMap result = OSDParser.DeserializeLLSDXml(responseData) as OSDMap;
if (result != null)
{
events = result["events"] as OSDArray;
ack = result["id"].AsInteger();
}
else
{
Logger.Log("Got an unparseable response from the event queue: \"" +
System.Text.Encoding.UTF8.GetString(responseData) + "\"", Helpers.LogLevel.Warning);
}
}
else if (error != null)
{
#region Error handling
HttpStatusCode code = HttpStatusCode.OK;
if (error is WebException)
{
WebException webException = (WebException)error;
if (webException.Response != null)
code = ((HttpWebResponse)webException.Response).StatusCode;
else if (webException.Status == WebExceptionStatus.RequestCanceled)
goto HandlingDone;
}
if (error is WebException && ((WebException)error).Response != null)
code = ((HttpWebResponse)((WebException)error).Response).StatusCode;
if (code == HttpStatusCode.NotFound || code == HttpStatusCode.Gone)
{
Logger.Log(String.Format("Closing event queue at {0} due to missing caps URI", _Address), Helpers.LogLevel.Info);
_Running = false;
_Dead = true;
}
else if (code == HttpStatusCode.BadGateway)
{
// This is not good (server) protocol design, but it's normal.
// The EventQueue server is a proxy that connects to a Squid
// cache which will time out periodically. The EventQueue server
// interprets this as a generic error and returns a 502 to us
// that we ignore
}
else
{
++_errorCount;
// Try to log a meaningful error message
if (code != HttpStatusCode.OK)
{
Logger.Log(String.Format("Unrecognized caps connection problem from {0}: {1}",
_Address, code), Helpers.LogLevel.Warning);
}
else if (error.InnerException != null)
{
Logger.Log(String.Format("Unrecognized internal caps exception from {0}: {1}",
_Address, error.InnerException.Message), Helpers.LogLevel.Warning);
}
else
{
Logger.Log(String.Format("Unrecognized caps exception from {0}: {1}",
_Address, error.Message), Helpers.LogLevel.Warning);
}
}
#endregion Error handling
}
else
{
++_errorCount;
Logger.Log("No response from the event queue but no reported error either", Helpers.LogLevel.Warning);
}
HandlingDone:
#region Resume the connection
if (_Running)
{
OSDMap osdRequest = new OSDMap();
if (ack != 0) osdRequest["ack"] = OSD.FromInteger(ack);
else osdRequest["ack"] = new OSD();
osdRequest["done"] = OSD.FromBoolean(_Dead);
byte[] postData = OSDParser.SerializeLLSDXmlBytes(osdRequest);
if (_errorCount > 0) // Exponentially back off, so we don't hammer the CPU
Thread.Sleep(_random.Next(500 + (int)Math.Pow(2, _errorCount)));
// Resume the connection. The event handler for the connection opening
// just sets class _Request variable to the current HttpWebRequest
CapsBase.UploadDataAsync(_Address, null, "application/xml", postData, REQUEST_TIMEOUT,
delegate(HttpWebRequest newRequest) { _Request = newRequest; }, null, RequestCompletedHandler);
// If the event queue is dead at this point, turn it off since
// that was the last thing we want to do
if (_Dead)
{
_Running = false;
Logger.DebugLog("Sent event queue shutdown message");
}
}
#endregion Resume the connection
#region Handle incoming events
if (OnEvent != null && events != null && events.Count > 0)
{
// Fire callbacks for each event received
foreach (OSDMap evt in events)
{
string msg = evt["message"].AsString();
OSDMap body = (OSDMap)evt["body"];
try { OnEvent(msg, body); }
catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Error, ex); }
}
}
#endregion Handle incoming events
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Runtime;
namespace System.ServiceModel.Channels
{
internal abstract class LayeredChannelFactory<TChannel> : ChannelFactoryBase<TChannel>
{
private IChannelFactory _innerChannelFactory;
public LayeredChannelFactory(IDefaultCommunicationTimeouts timeouts, IChannelFactory innerChannelFactory)
: base(timeouts)
{
_innerChannelFactory = innerChannelFactory;
}
protected IChannelFactory InnerChannelFactory
{
get { return _innerChannelFactory; }
}
public override T GetProperty<T>()
{
if (typeof(T) == typeof(IChannelFactory<TChannel>))
{
return (T)(object)this;
}
T baseProperty = base.GetProperty<T>();
if (baseProperty != null)
{
return baseProperty;
}
return _innerChannelFactory.GetProperty<T>();
}
protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
return _innerChannelFactory.BeginOpen(timeout, callback, state);
}
protected override void OnEndOpen(IAsyncResult result)
{
_innerChannelFactory.EndOpen(result);
}
protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
return new ChainedCloseAsyncResult(timeout, callback, state, base.OnBeginClose, base.OnEndClose, _innerChannelFactory);
}
protected override void OnEndClose(IAsyncResult result)
{
ChainedCloseAsyncResult.End(result);
}
protected override void OnClose(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
base.OnClose(timeoutHelper.RemainingTime());
_innerChannelFactory.Close(timeoutHelper.RemainingTime());
}
protected override void OnOpen(TimeSpan timeout)
{
_innerChannelFactory.Open(timeout);
}
protected override void OnAbort()
{
base.OnAbort();
_innerChannelFactory.Abort();
}
}
internal class LayeredInputChannel : LayeredChannel<IInputChannel>, IInputChannel
{
public LayeredInputChannel(ChannelManagerBase channelManager, IInputChannel innerChannel)
: base(channelManager, innerChannel)
{
}
public virtual EndpointAddress LocalAddress
{
get { return InnerChannel.LocalAddress; }
}
private void InternalOnReceive(Message message)
{
if (message != null)
{
this.OnReceive(message);
}
}
protected virtual void OnReceive(Message message)
{
}
public Message Receive()
{
Message message = InnerChannel.Receive();
this.InternalOnReceive(message);
return message;
}
public Message Receive(TimeSpan timeout)
{
Message message = InnerChannel.Receive(timeout);
this.InternalOnReceive(message);
return message;
}
public IAsyncResult BeginReceive(AsyncCallback callback, object state)
{
return InnerChannel.BeginReceive(callback, state);
}
public IAsyncResult BeginReceive(TimeSpan timeout, AsyncCallback callback, object state)
{
return InnerChannel.BeginReceive(timeout, callback, state);
}
public Message EndReceive(IAsyncResult result)
{
Message message = InnerChannel.EndReceive(result);
this.InternalOnReceive(message);
return message;
}
public IAsyncResult BeginTryReceive(TimeSpan timeout, AsyncCallback callback, object state)
{
return InnerChannel.BeginTryReceive(timeout, callback, state);
}
public bool EndTryReceive(IAsyncResult result, out Message message)
{
bool retVal = InnerChannel.EndTryReceive(result, out message);
this.InternalOnReceive(message);
return retVal;
}
public bool TryReceive(TimeSpan timeout, out Message message)
{
bool retVal = InnerChannel.TryReceive(timeout, out message);
this.InternalOnReceive(message);
return retVal;
}
public bool WaitForMessage(TimeSpan timeout)
{
return InnerChannel.WaitForMessage(timeout);
}
public IAsyncResult BeginWaitForMessage(TimeSpan timeout, AsyncCallback callback, object state)
{
return InnerChannel.BeginWaitForMessage(timeout, callback, state);
}
public bool EndWaitForMessage(IAsyncResult result)
{
return InnerChannel.EndWaitForMessage(result);
}
}
internal class LayeredDuplexChannel : LayeredInputChannel, IDuplexChannel
{
private IOutputChannel _innerOutputChannel;
private EndpointAddress _localAddress;
private EventHandler _onInnerOutputChannelFaulted;
public LayeredDuplexChannel(ChannelManagerBase channelManager, IInputChannel innerInputChannel, EndpointAddress localAddress, IOutputChannel innerOutputChannel)
: base(channelManager, innerInputChannel)
{
_localAddress = localAddress;
_innerOutputChannel = innerOutputChannel;
_onInnerOutputChannelFaulted = new EventHandler(OnInnerOutputChannelFaulted);
_innerOutputChannel.Faulted += _onInnerOutputChannelFaulted;
}
public override EndpointAddress LocalAddress
{
get { return _localAddress; }
}
public EndpointAddress RemoteAddress
{
get { return _innerOutputChannel.RemoteAddress; }
}
public Uri Via
{
get { return _innerOutputChannel.Via; }
}
protected override void OnClosing()
{
_innerOutputChannel.Faulted -= _onInnerOutputChannelFaulted;
base.OnClosing();
}
protected override void OnAbort()
{
_innerOutputChannel.Abort();
base.OnAbort();
}
protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
return new ChainedCloseAsyncResult(timeout, callback, state, base.OnBeginClose, base.OnEndClose, _innerOutputChannel);
}
protected override void OnEndClose(IAsyncResult result)
{
ChainedCloseAsyncResult.End(result);
}
protected override void OnClose(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
_innerOutputChannel.Close(timeoutHelper.RemainingTime());
base.OnClose(timeoutHelper.RemainingTime());
}
protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
return new ChainedOpenAsyncResult(timeout, callback, state, base.OnBeginOpen, base.OnEndOpen, _innerOutputChannel);
}
protected override void OnEndOpen(IAsyncResult result)
{
ChainedOpenAsyncResult.End(result);
}
protected override void OnOpen(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
base.OnOpen(timeoutHelper.RemainingTime());
_innerOutputChannel.Open(timeoutHelper.RemainingTime());
}
public void Send(Message message)
{
this.Send(message, this.DefaultSendTimeout);
}
public void Send(Message message, TimeSpan timeout)
{
_innerOutputChannel.Send(message, timeout);
}
public IAsyncResult BeginSend(Message message, AsyncCallback callback, object state)
{
return this.BeginSend(message, this.DefaultSendTimeout, callback, state);
}
public IAsyncResult BeginSend(Message message, TimeSpan timeout, AsyncCallback callback, object state)
{
return _innerOutputChannel.BeginSend(message, timeout, callback, state);
}
public void EndSend(IAsyncResult result)
{
_innerOutputChannel.EndSend(result);
}
private void OnInnerOutputChannelFaulted(object sender, EventArgs e)
{
this.Fault();
}
}
}
| |
// 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.Buffers;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Numerics;
using System.Reflection;
namespace System.Security.Cryptography.Asn1
{
internal class AsnSerializationConstraintException : CryptographicException
{
public AsnSerializationConstraintException()
{
}
public AsnSerializationConstraintException(string message)
: base(message)
{
}
public AsnSerializationConstraintException(string message, Exception inner)
: base(message, inner)
{
}
}
internal class AsnAmbiguousFieldTypeException : AsnSerializationConstraintException
{
public AsnAmbiguousFieldTypeException(FieldInfo fieldInfo, Type ambiguousType)
: base(SR.Format(SR.Cryptography_AsnSerializer_AmbiguousFieldType, fieldInfo.Name, fieldInfo.DeclaringType.FullName, ambiguousType.Namespace))
{
}
}
internal class AsnSerializerInvalidDefaultException : AsnSerializationConstraintException
{
internal AsnSerializerInvalidDefaultException()
{
}
internal AsnSerializerInvalidDefaultException(Exception innerException)
: base(string.Empty, innerException)
{
}
}
internal static class AsnSerializer
{
private const BindingFlags FieldFlags =
BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.Instance;
private delegate void Serializer(object value, AsnWriter writer);
private delegate object Deserializer(AsnReader reader);
private delegate bool TryDeserializer<T>(AsnReader reader, out T value);
private static Deserializer TryOrFail<T>(TryDeserializer<T> tryDeserializer)
{
return reader =>
{
if (tryDeserializer(reader, out T value))
return value;
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
};
}
private static ChoiceAttribute GetChoiceAttribute(Type typeT)
{
ChoiceAttribute attr = typeT.GetCustomAttribute<ChoiceAttribute>(inherit: false);
if (attr == null)
{
return null;
}
if (attr.AllowNull)
{
if (!CanBeNull(typeT))
{
throw new AsnSerializationConstraintException(
SR.Format(SR.Cryptography_AsnSerializer_Choice_AllowNullNonNullable, typeT.FullName));
}
}
return attr;
}
private static bool CanBeNull(Type t)
{
return !t.IsValueType ||
(t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));
}
private static void PopulateChoiceLookup(
Dictionary<(TagClass, int), LinkedList<FieldInfo>> lookup,
Type typeT,
LinkedList<FieldInfo> currentSet)
{
FieldInfo[] fieldInfos = typeT.GetFields(FieldFlags);
// https://github.com/dotnet/corefx/issues/14606 asserts that ordering by the metadata
// token on a SequentialLayout will produce the fields in their layout order.
//
// Some other alternatives:
// * Add an attribute for controlling the field read order.
// fieldInfos.Select(fi => (fi, fi.GetCustomAttribute<AsnFieldOrderAttribute>(false)).
// Where(val => val.Item2 != null).OrderBy(val => val.Item2.OrderWeight).Select(val => val.Item1);
//
// * Use Marshal.OffsetOf as a sort key
//
// * Invent more alternatives
foreach (FieldInfo fieldInfo in fieldInfos.OrderBy(fi => fi.MetadataToken))
{
Type fieldType = fieldInfo.FieldType;
if (!CanBeNull(fieldType))
{
throw new AsnSerializationConstraintException(
SR.Format(
SR.Cryptography_AsnSerializer_Choice_NonNullableField,
fieldInfo.Name,
fieldInfo.DeclaringType.FullName));
}
fieldType = UnpackIfNullable(fieldType);
if (currentSet.Contains(fieldInfo))
{
throw new AsnSerializationConstraintException(
SR.Format(
SR.Cryptography_AsnSerializer_Choice_TypeCycle,
fieldInfo.Name,
fieldInfo.DeclaringType.FullName));
}
LinkedListNode<FieldInfo> newNode = new LinkedListNode<FieldInfo>(fieldInfo);
currentSet.AddLast(newNode);
if (GetChoiceAttribute(fieldType) != null)
{
PopulateChoiceLookup(lookup, fieldType, currentSet);
}
else
{
GetFieldInfo(
fieldType,
fieldInfo,
out SerializerFieldData fieldData);
if (fieldData.DefaultContents != null)
{
// ITU-T-REC-X.680-201508
// The application of the DEFAULT keyword is in SEQUENCE (sec 25, "ComponentType" grammar)
// There is no such keyword in the grammar for CHOICE.
throw new AsnSerializationConstraintException(
SR.Format(
SR.Cryptography_AsnSerializer_Choice_DefaultValueDisallowed,
fieldInfo.Name,
fieldInfo.DeclaringType.FullName));
}
var key = (fieldData.ExpectedTag.TagClass, fieldData.ExpectedTag.TagValue);
if (lookup.TryGetValue(key, out LinkedList<FieldInfo> existingSet))
{
FieldInfo existing = existingSet.Last.Value;
throw new AsnSerializationConstraintException(
SR.Format(
SR.Cryptography_AsnSerializer_Choice_ConflictingTagMapping,
fieldData.ExpectedTag.TagClass,
fieldData.ExpectedTag.TagValue,
fieldInfo.Name,
fieldInfo.DeclaringType.FullName,
existing.Name,
existing.DeclaringType.FullName));
}
lookup.Add(key, new LinkedList<FieldInfo>(currentSet));
}
currentSet.RemoveLast();
}
}
private static void SerializeChoice(Type typeT, object value, AsnWriter writer)
{
// Ensure that the type is consistent with a Choice by using the same logic
// as the deserializer.
var lookup = new Dictionary<(TagClass, int), LinkedList<FieldInfo>>();
LinkedList<FieldInfo> fields = new LinkedList<FieldInfo>();
PopulateChoiceLookup(lookup, typeT, fields);
FieldInfo relevantField = null;
object relevantObject = null;
// If the value is itself null and the choice allows it, write null.
if (value == null)
{
if (GetChoiceAttribute(typeT).AllowNull)
{
writer.WriteNull();
return;
}
}
else
{
FieldInfo[] fieldInfos = typeT.GetFields(FieldFlags);
for (int i = 0; i < fieldInfos.Length; i++)
{
FieldInfo fieldInfo = fieldInfos[i];
object fieldValue = fieldInfo.GetValue(value);
if (fieldValue != null)
{
if (relevantField != null)
{
throw new AsnSerializationConstraintException(
SR.Format(
SR.Cryptography_AsnSerializer_Choice_TooManyValues,
fieldInfo.Name,
relevantField.Name,
typeT.FullName));
}
relevantField = fieldInfo;
relevantObject = fieldValue;
}
}
}
// If the element in the SEQUENCE (class/struct) is non-null it must resolve to a value.
// If the SEQUENCE field was OPTIONAL then the element should have been null.
if (relevantField == null)
{
throw new AsnSerializationConstraintException(
SR.Format(
SR.Cryptography_AsnSerializer_Choice_NoChoiceWasMade,
typeT.FullName));
}
Serializer serializer = GetSerializer(relevantField.FieldType, relevantField);
serializer(relevantObject, writer);
}
private static object DeserializeChoice(AsnReader reader, Type typeT)
{
var lookup = new Dictionary<(TagClass, int), LinkedList<FieldInfo>>();
LinkedList<FieldInfo> fields = new LinkedList<FieldInfo>();
PopulateChoiceLookup(lookup, typeT, fields);
Asn1Tag next = reader.PeekTag();
if (next == Asn1Tag.Null)
{
ChoiceAttribute choiceAttr = GetChoiceAttribute(typeT);
if (choiceAttr.AllowNull)
{
reader.ReadNull();
return null;
}
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
var key = (next.TagClass, next.TagValue);
if (lookup.TryGetValue(key, out LinkedList<FieldInfo> fieldInfos))
{
LinkedListNode<FieldInfo> currentNode = fieldInfos.Last;
FieldInfo currentField = currentNode.Value;
object currentObject = Activator.CreateInstance(currentField.DeclaringType);
Deserializer deserializer = GetDeserializer(currentField.FieldType, currentField);
object deserialized = deserializer(reader);
currentField.SetValue(currentObject, deserialized);
while (currentNode.Previous != null)
{
currentNode = currentNode.Previous;
currentField = currentNode.Value;
object nextObject = Activator.CreateInstance(currentField.DeclaringType);
currentField.SetValue(nextObject, currentObject);
currentObject = nextObject;
}
return currentObject;
}
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
private static void SerializeCustomType(Type typeT, object value, AsnWriter writer, Asn1Tag tag)
{
writer.PushSequence(tag);
foreach (FieldInfo fieldInfo in typeT.GetFields(FieldFlags))
{
Serializer serializer = GetSerializer(fieldInfo.FieldType, fieldInfo);
serializer(fieldInfo.GetValue(value), writer);
}
writer.PopSequence(tag);
}
private static object DeserializeCustomType(AsnReader reader, Type typeT)
{
object target = Activator.CreateInstance(typeT);
AsnReader sequence = reader.ReadSequence();
foreach (FieldInfo fieldInfo in typeT.GetFields(FieldFlags))
{
Deserializer deserializer = GetDeserializer(fieldInfo.FieldType, fieldInfo);
try
{
fieldInfo.SetValue(target, deserializer(sequence));
}
catch (Exception e)
{
throw new CryptographicException(
SR.Format(
SR.Cryptography_AsnSerializer_SetValueException,
fieldInfo.Name,
fieldInfo.DeclaringType.FullName),
e);
}
}
sequence.ThrowIfNotEmpty();
return target;
}
private static Deserializer ExplicitValueDeserializer(Deserializer valueDeserializer, Asn1Tag expectedTag)
{
return reader => ExplicitValueDeserializer(reader, valueDeserializer, expectedTag);
}
private static object ExplicitValueDeserializer(
AsnReader reader,
Deserializer valueDeserializer,
Asn1Tag expectedTag)
{
AsnReader innerReader = reader.ReadSequence(expectedTag);
object val = valueDeserializer(innerReader);
innerReader.ThrowIfNotEmpty();
return val;
}
private static Deserializer DefaultValueDeserializer(
Deserializer valueDeserializer,
bool isOptional,
byte[] defaultContents,
Asn1Tag? expectedTag)
{
return reader =>
DefaultValueDeserializer(
reader,
expectedTag,
valueDeserializer,
defaultContents,
isOptional);
}
private static object DefaultValueDeserializer(
AsnReader reader,
Asn1Tag? expectedTag,
Deserializer valueDeserializer,
byte[] defaultContents,
bool isOptional)
{
if (reader.HasData)
{
Asn1Tag actualTag = reader.PeekTag();
if (expectedTag == null ||
// Normalize the constructed bit so only class and value are compared
actualTag.AsPrimitive() == expectedTag.Value.AsPrimitive())
{
return valueDeserializer(reader);
}
}
if (isOptional)
{
return null;
}
if (defaultContents != null)
{
return DefaultValue(defaultContents, valueDeserializer);
}
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
private static Serializer GetSerializer(Type typeT, FieldInfo fieldInfo)
{
Serializer literalValueSerializer = GetSimpleSerializer(
typeT,
fieldInfo,
out byte[] defaultContents,
out bool isOptional,
out Asn1Tag? explicitTag);
Serializer serializer = literalValueSerializer;
if (isOptional)
{
serializer = (obj, writer) =>
{
if (obj != null)
literalValueSerializer(obj, writer);
};
}
else if (defaultContents != null)
{
serializer = (obj, writer) =>
{
AsnReader reader;
using (AsnWriter tmp = new AsnWriter(AsnEncodingRules.DER))
{
literalValueSerializer(obj, tmp);
reader = new AsnReader(tmp.Encode(), AsnEncodingRules.DER);
}
ReadOnlySpan<byte> encoded = reader.GetEncodedValue().Span;
bool equal = false;
if (encoded.Length == defaultContents.Length)
{
equal = true;
for (int i = 0; i < encoded.Length; i++)
{
if (encoded[i] != defaultContents[i])
{
equal = false;
break;
}
}
}
if (!equal)
{
literalValueSerializer(obj, writer);
}
};
}
if (explicitTag.HasValue)
{
return (obj, writer) =>
{
using (AsnWriter tmp = new AsnWriter(AsnEncodingRules.DER))
{
serializer(obj, tmp);
if (tmp.Encode().Length > 0)
{
writer.PushSequence(explicitTag.Value);
serializer(obj, writer);
writer.PopSequence(explicitTag.Value);
}
}
};
}
return serializer;
}
private static Serializer GetSimpleSerializer(
Type typeT,
FieldInfo fieldInfo,
out byte[] defaultContents,
out bool isOptional,
out Asn1Tag? explicitTag)
{
if (!typeT.IsSealed || typeT.ContainsGenericParameters)
{
throw new AsnSerializationConstraintException(
SR.Format(SR.Cryptography_AsnSerializer_NoOpenTypes, typeT.FullName));
}
GetFieldInfo(
typeT,
fieldInfo,
out SerializerFieldData fieldData);
defaultContents = fieldData.DefaultContents;
isOptional = fieldData.IsOptional;
typeT = UnpackIfNullable(typeT);
bool isChoice = GetChoiceAttribute(typeT) != null;
Asn1Tag tag;
if (fieldData.HasExplicitTag)
{
explicitTag = fieldData.ExpectedTag;
tag = new Asn1Tag(fieldData.TagType.GetValueOrDefault());
}
else
{
explicitTag = null;
tag = fieldData.ExpectedTag;
}
// EXPLICIT Any can result in a TagType of null, as can CHOICE types.
// In either of those cases we'll get a tag of EoC, but otherwise the tag should be valid.
Debug.Assert(
tag != Asn1Tag.EndOfContents || fieldData.IsAny || isChoice,
$"Unknown state for typeT={typeT.FullName} on field {fieldInfo?.Name} of type {fieldInfo?.DeclaringType.FullName}");
if (typeT.IsPrimitive)
{
// The AsnTypeAttribute resolved in GetFieldInfo currently doesn't allow
// type modification for any of the primitive types. If that changes, we
// need to either pass it through here or do some other form of rerouting.
Debug.Assert(!fieldData.WasCustomized);
return GetPrimitiveSerializer(typeT, tag);
}
if (typeT.IsEnum)
{
if (typeT.GetCustomAttributes(typeof(FlagsAttribute), false).Length > 0)
{
return (value, writer) => writer.WriteNamedBitList(tag, value);
}
return (value, writer) => writer.WriteEnumeratedValue(tag, value);
}
if (typeT == typeof(string))
{
if (fieldData.TagType == UniversalTagNumber.ObjectIdentifier)
{
return (value, writer) => writer.WriteObjectIdentifier(tag, (string)value);
}
// Because all string types require an attribute saying their type, we'll
// definitely have a value.
return (value, writer) => writer.WriteCharacterString(tag, fieldData.TagType.Value, (string)value);
}
if (typeT == typeof(ReadOnlyMemory<byte>) && !fieldData.IsCollection)
{
if (fieldData.IsAny)
{
// If a tag was specified via [ExpectedTag] (other than because it's wrapped in an EXPLICIT)
// then don't let the serializer write a violation of that expectation.
if (fieldData.SpecifiedTag && !fieldData.HasExplicitTag)
{
return (value, writer) =>
{
ReadOnlyMemory<byte> data = (ReadOnlyMemory<byte>)value;
if (!Asn1Tag.TryParse(data.Span, out Asn1Tag actualTag, out _) ||
actualTag.AsPrimitive() != fieldData.ExpectedTag.AsPrimitive())
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
writer.WriteEncodedValue(data);
};
}
return (value, writer) => writer.WriteEncodedValue((ReadOnlyMemory<byte>)value);
}
if (fieldData.TagType == UniversalTagNumber.BitString)
{
return (value, writer) => writer.WriteBitString(tag, ((ReadOnlyMemory<byte>)value).Span);
}
if (fieldData.TagType == UniversalTagNumber.OctetString)
{
return (value, writer) => writer.WriteOctetString(tag, ((ReadOnlyMemory<byte>)value).Span);
}
if (fieldData.TagType == UniversalTagNumber.Integer)
{
return (value, writer) =>
{
// TODO: split netstandard/netcoreapp for span usage?
ReadOnlyMemory<byte> valAsMemory = (ReadOnlyMemory<byte>)value;
byte[] tooBig = new byte[valAsMemory.Length + 1];
valAsMemory.Span.CopyTo(tooBig.AsSpan().Slice(1));
Array.Reverse(tooBig);
BigInteger bigInt = new BigInteger(tooBig);
writer.WriteInteger(bigInt);
};
}
Debug.Fail($"No ReadOnlyMemory<byte> handler for {fieldData.TagType}");
throw new CryptographicException();
}
if (typeT == typeof(Oid))
{
return (value, writer) => writer.WriteObjectIdentifier(fieldData.ExpectedTag, (Oid)value);
}
if (typeT.IsArray)
{
if (typeT.GetArrayRank() != 1)
{
throw new AsnSerializationConstraintException(
SR.Format(SR.Cryptography_AsnSerializer_NoMultiDimensionalArrays, typeT.FullName));
}
Type baseType = typeT.GetElementType();
if (baseType.IsArray)
{
throw new AsnSerializationConstraintException(
SR.Format(SR.Cryptography_AsnSerializer_NoJaggedArrays, typeT.FullName));
}
Serializer serializer = GetSerializer(baseType, null);
if (fieldData.TagType == UniversalTagNumber.SetOf)
{
return (value, writer) =>
{
writer.PushSetOf(tag);
foreach (var item in (Array)value)
{
serializer(item, writer);
}
writer.PopSetOf(tag);
};
}
Debug.Assert(fieldData.TagType == 0 || fieldData.TagType == UniversalTagNumber.SequenceOf);
return (value, writer) =>
{
writer.PushSequence(tag);
foreach (var item in (Array)value)
{
serializer(item, writer);
}
writer.PopSequence(tag);
};
}
if (typeT == typeof(DateTimeOffset))
{
if (fieldData.TagType == UniversalTagNumber.UtcTime)
{
return (value, writer) => writer.WriteUtcTime(tag, (DateTimeOffset)value);
}
if (fieldData.TagType == UniversalTagNumber.GeneralizedTime)
{
Debug.Assert(fieldData.DisallowGeneralizedTimeFractions != null);
return (value, writer) =>
writer.WriteGeneralizedTime(tag, (DateTimeOffset)value, fieldData.DisallowGeneralizedTimeFractions.Value);
}
Debug.Fail($"No DateTimeOffset handler for {fieldData.TagType}");
throw new CryptographicException();
}
if (typeT == typeof(BigInteger))
{
return (value, writer) => writer.WriteInteger(tag, (BigInteger)value);
}
if (typeT.IsLayoutSequential)
{
if (isChoice)
{
return (value, writer) => SerializeChoice(typeT, value, writer);
}
if (fieldData.TagType == UniversalTagNumber.Sequence)
{
return (value, writer) => SerializeCustomType(typeT, value, writer, tag);
}
}
throw new AsnSerializationConstraintException(
SR.Format(SR.Cryptography_AsnSerializer_UnhandledType, typeT.FullName));
}
private static Deserializer GetDeserializer(Type typeT, FieldInfo fieldInfo)
{
Deserializer literalValueDeserializer = GetSimpleDeserializer(
typeT,
fieldInfo,
out SerializerFieldData fieldData);
Deserializer deserializer = literalValueDeserializer;
if (fieldData.HasExplicitTag)
{
deserializer = ExplicitValueDeserializer(deserializer, fieldData.ExpectedTag);
}
if (fieldData.IsOptional || fieldData.DefaultContents != null)
{
Asn1Tag? expectedTag = null;
if (fieldData.SpecifiedTag || fieldData.TagType != null)
{
expectedTag = fieldData.ExpectedTag;
}
deserializer = DefaultValueDeserializer(
deserializer,
fieldData.IsOptional,
fieldData.DefaultContents,
expectedTag);
}
return deserializer;
}
private static Deserializer GetSimpleDeserializer(
Type typeT,
FieldInfo fieldInfo,
out SerializerFieldData fieldData)
{
if (!typeT.IsSealed || typeT.ContainsGenericParameters)
{
throw new AsnSerializationConstraintException(
SR.Format(SR.Cryptography_AsnSerializer_NoOpenTypes, typeT.FullName));
}
GetFieldInfo(typeT, fieldInfo, out fieldData);
SerializerFieldData localFieldData = fieldData;
typeT = UnpackIfNullable(typeT);
if (fieldData.IsAny)
{
if (typeT == typeof(ReadOnlyMemory<byte>))
{
Asn1Tag matchTag = fieldData.ExpectedTag;
// EXPLICIT Any can't be validated, just return the value.
if (fieldData.HasExplicitTag || !fieldData.SpecifiedTag)
{
return reader => reader.GetEncodedValue();
}
// If it's not declared EXPLICIT but an [ExpectedTag] was provided,
// use it as a validation/filter.
return reader =>
{
Asn1Tag nextTag = reader.PeekTag();
if (matchTag.TagClass != nextTag.TagClass ||
matchTag.TagValue != nextTag.TagValue)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
return reader.GetEncodedValue();
};
}
throw new AsnSerializationConstraintException(
SR.Format(SR.Cryptography_AsnSerializer_UnhandledType, typeT.FullName));
}
if (GetChoiceAttribute(typeT) != null)
{
return reader => DeserializeChoice(reader, typeT);
}
Debug.Assert(fieldData.TagType != null);
Asn1Tag expectedTag = fieldData.HasExplicitTag ? new Asn1Tag(fieldData.TagType.Value) : fieldData.ExpectedTag;
if (typeT.IsPrimitive)
{
// The AsnTypeAttribute resolved in GetFieldInfo currently doesn't allow
// type modification for any of the primitive types. If that changes, we
// need to either pass it through here or do some other form of rerouting.
Debug.Assert(!fieldData.WasCustomized);
return GetPrimitiveDeserializer(typeT, expectedTag);
}
if (typeT.IsEnum)
{
if (typeT.GetCustomAttributes(typeof(FlagsAttribute), false).Length > 0)
{
return reader => reader.GetNamedBitListValue(expectedTag, typeT);
}
return reader => reader.GetEnumeratedValue(expectedTag, typeT);
}
if (typeT == typeof(string))
{
if (fieldData.TagType == UniversalTagNumber.ObjectIdentifier)
{
return reader => reader.ReadObjectIdentifierAsString(expectedTag);
}
// Because all string types require an attribute saying their type, we'll
// definitely have a value.
Debug.Assert(localFieldData.TagType != null);
return reader => reader.GetCharacterString(expectedTag, localFieldData.TagType.Value);
}
if (typeT == typeof(ReadOnlyMemory<byte>) && !fieldData.IsCollection)
{
if (fieldData.TagType == UniversalTagNumber.BitString)
{
return reader =>
{
if (reader.TryGetPrimitiveBitStringValue(expectedTag, out _, out ReadOnlyMemory<byte> contents))
{
return contents;
}
// Guaranteed too big, because it has the tag and length.
int length = reader.PeekEncodedValue().Length;
byte[] rented = ArrayPool<byte>.Shared.Rent(length);
try
{
if (reader.TryCopyBitStringBytes(rented, out _, out int bytesWritten))
{
return new ReadOnlyMemory<byte>(rented.AsReadOnlySpan().Slice(0, bytesWritten).ToArray());
}
Debug.Fail("TryCopyBitStringBytes produced more data than the encoded size");
throw new CryptographicException();
}
finally
{
Array.Clear(rented, 0, length);
ArrayPool<byte>.Shared.Return(rented);
}
};
}
if (fieldData.TagType == UniversalTagNumber.OctetString)
{
return reader =>
{
if (reader.TryGetPrimitiveOctetStringBytes(expectedTag, out ReadOnlyMemory<byte> contents))
{
return contents;
}
// Guaranteed too big, because it has the tag and length.
int length = reader.PeekEncodedValue().Length;
byte[] rented = ArrayPool<byte>.Shared.Rent(length);
try
{
if (reader.TryCopyOctetStringBytes(rented, out int bytesWritten))
{
return new ReadOnlyMemory<byte>(rented.AsReadOnlySpan().Slice(0, bytesWritten).ToArray());
}
Debug.Fail("TryCopyOctetStringBytes produced more data than the encoded size");
throw new CryptographicException();
}
finally
{
Array.Clear(rented, 0, length);
ArrayPool<byte>.Shared.Return(rented);
}
};
}
if (fieldData.TagType == UniversalTagNumber.Integer)
{
return reader => reader.GetIntegerBytes(expectedTag);
}
Debug.Fail($"No ReadOnlyMemory<byte> handler for {fieldData.TagType}");
throw new CryptographicException();
}
if (typeT == typeof(Oid))
{
bool skipFriendlyName = !fieldData.PopulateOidFriendlyName.GetValueOrDefault();
return reader => reader.ReadObjectIdentifier(expectedTag, skipFriendlyName);
}
if (typeT.IsArray)
{
if (typeT.GetArrayRank() != 1)
{
throw new AsnSerializationConstraintException(
SR.Format(SR.Cryptography_AsnSerializer_NoMultiDimensionalArrays, typeT.FullName));
}
Type baseType = typeT.GetElementType();
if (baseType.IsArray)
{
throw new AsnSerializationConstraintException(
SR.Format(SR.Cryptography_AsnSerializer_NoJaggedArrays, typeT.FullName));
}
return reader =>
{
LinkedList<object> linkedList = new LinkedList<object>();
AsnReader collectionReader;
if (localFieldData.TagType == UniversalTagNumber.SetOf)
{
collectionReader = reader.ReadSetOf(expectedTag);
}
else
{
Debug.Assert(localFieldData.TagType == 0 || localFieldData.TagType == UniversalTagNumber.SequenceOf);
collectionReader = reader.ReadSequence(expectedTag);
}
Deserializer deserializer = GetDeserializer(baseType, null);
while (collectionReader.HasData)
{
object elem = deserializer(collectionReader);
LinkedListNode<object> node = new LinkedListNode<object>(elem);
linkedList.AddLast(node);
}
object[] objArr = linkedList.ToArray();
Array arr = Array.CreateInstance(baseType, objArr.Length);
Array.Copy(objArr, arr, objArr.Length);
return arr;
};
}
if (typeT == typeof(DateTimeOffset))
{
if (fieldData.TagType == UniversalTagNumber.UtcTime)
{
if (fieldData.TwoDigitYearMax != null)
{
return reader =>
reader.GetUtcTime(expectedTag, localFieldData.TwoDigitYearMax.Value);
}
return reader => reader.GetUtcTime(expectedTag);
}
if (fieldData.TagType == UniversalTagNumber.GeneralizedTime)
{
Debug.Assert(fieldData.DisallowGeneralizedTimeFractions != null);
bool disallowFractions = fieldData.DisallowGeneralizedTimeFractions.Value;
return reader => reader.GetGeneralizedTime(expectedTag, disallowFractions);
}
Debug.Fail($"No DateTimeOffset handler for {fieldData.TagType}");
throw new CryptographicException();
}
if (typeT == typeof(BigInteger))
{
return reader => reader.GetInteger(expectedTag);
}
if (typeT.IsLayoutSequential)
{
if (fieldData.TagType == UniversalTagNumber.Sequence)
{
return reader => DeserializeCustomType(reader, typeT);
}
}
throw new AsnSerializationConstraintException(
SR.Format(SR.Cryptography_AsnSerializer_UnhandledType, typeT.FullName));
}
private static object DefaultValue(
byte[] defaultContents,
Deserializer valueDeserializer)
{
Debug.Assert(defaultContents != null);
try
{
AsnReader defaultValueReader = new AsnReader(defaultContents, AsnEncodingRules.DER);
object obj = valueDeserializer(defaultValueReader);
if (defaultValueReader.HasData)
{
throw new AsnSerializerInvalidDefaultException();
}
return obj;
}
catch (AsnSerializerInvalidDefaultException)
{
throw;
}
catch (CryptographicException e)
{
throw new AsnSerializerInvalidDefaultException(e);
}
}
private static void GetFieldInfo(
Type typeT,
FieldInfo fieldInfo,
out SerializerFieldData serializerFieldData)
{
serializerFieldData = new SerializerFieldData();
object[] typeAttrs = fieldInfo?.GetCustomAttributes(typeof(AsnTypeAttribute), false) ??
Array.Empty<object>();
if (typeAttrs.Length > 1)
{
throw new AsnSerializationConstraintException(
SR.Format(
fieldInfo.Name,
fieldInfo.DeclaringType.FullName,
typeof(AsnTypeAttribute).FullName));
}
Type unpackedType = UnpackIfNullable(typeT);
if (typeAttrs.Length == 1)
{
Type[] expectedTypes;
object attr = typeAttrs[0];
serializerFieldData.WasCustomized = true;
if (attr is AnyValueAttribute)
{
serializerFieldData.IsAny = true;
expectedTypes = new[] { typeof(ReadOnlyMemory<byte>) };
}
else if (attr is IntegerAttribute)
{
expectedTypes = new[] { typeof(ReadOnlyMemory<byte>) };
serializerFieldData.TagType = UniversalTagNumber.Integer;
}
else if (attr is BitStringAttribute)
{
expectedTypes = new[] { typeof(ReadOnlyMemory<byte>) };
serializerFieldData.TagType = UniversalTagNumber.BitString;
}
else if (attr is OctetStringAttribute)
{
expectedTypes = new[] { typeof(ReadOnlyMemory<byte>) };
serializerFieldData.TagType = UniversalTagNumber.OctetString;
}
else if (attr is ObjectIdentifierAttribute oid)
{
serializerFieldData.PopulateOidFriendlyName = oid.PopulateFriendlyName;
expectedTypes = new[] { typeof(Oid), typeof(string) };
serializerFieldData.TagType = UniversalTagNumber.ObjectIdentifier;
if (oid.PopulateFriendlyName && unpackedType == typeof(string))
{
throw new AsnSerializationConstraintException(
SR.Format(
SR.Cryptography_AsnSerializer_PopulateFriendlyNameOnString,
fieldInfo.Name,
fieldInfo.DeclaringType.FullName,
typeof(Oid).FullName));
}
}
else if (attr is BMPStringAttribute)
{
expectedTypes = new[] { typeof(string) };
serializerFieldData.TagType = UniversalTagNumber.BMPString;
}
else if (attr is IA5StringAttribute)
{
expectedTypes = new[] { typeof(string) };
serializerFieldData.TagType = UniversalTagNumber.IA5String;
}
else if (attr is UTF8StringAttribute)
{
expectedTypes = new[] { typeof(string) };
serializerFieldData.TagType = UniversalTagNumber.UTF8String;
}
else if (attr is PrintableStringAttribute)
{
expectedTypes = new[] { typeof(string) };
serializerFieldData.TagType = UniversalTagNumber.PrintableString;
}
else if (attr is VisibleStringAttribute)
{
expectedTypes = new[] { typeof(string) };
serializerFieldData.TagType = UniversalTagNumber.VisibleString;
}
else if (attr is SequenceOfAttribute)
{
serializerFieldData.IsCollection = true;
expectedTypes = null;
serializerFieldData.TagType = UniversalTagNumber.SequenceOf;
}
else if (attr is SetOfAttribute)
{
serializerFieldData.IsCollection = true;
expectedTypes = null;
serializerFieldData.TagType = UniversalTagNumber.SetOf;
}
else if (attr is UtcTimeAttribute utcAttr)
{
expectedTypes = new[] { typeof(DateTimeOffset) };
serializerFieldData.TagType = UniversalTagNumber.UtcTime;
if (utcAttr.TwoDigitYearMax != 0)
{
serializerFieldData.TwoDigitYearMax = utcAttr.TwoDigitYearMax;
if (serializerFieldData.TwoDigitYearMax < 99)
{
throw new AsnSerializationConstraintException(
SR.Format(
SR.Cryptography_AsnSerializer_UtcTimeTwoDigitYearMaxTooSmall,
fieldInfo.Name,
fieldInfo.DeclaringType.FullName,
serializerFieldData.TwoDigitYearMax));
}
}
}
else if (attr is GeneralizedTimeAttribute genTimeAttr)
{
expectedTypes = new[] { typeof(DateTimeOffset) };
serializerFieldData.TagType = UniversalTagNumber.GeneralizedTime;
serializerFieldData.DisallowGeneralizedTimeFractions = genTimeAttr.DisallowFractions;
}
else
{
Debug.Fail($"Unregistered {nameof(AsnTypeAttribute)} kind: {attr.GetType().FullName}");
throw new CryptographicException();
}
Debug.Assert(serializerFieldData.IsCollection || expectedTypes != null);
if (!serializerFieldData.IsCollection && Array.IndexOf(expectedTypes, unpackedType) < 0)
{
throw new AsnSerializationConstraintException(
SR.Format(
SR.Cryptography_AsnSerializer_UnexpectedTypeForAttribute,
fieldInfo.Name,
fieldInfo.DeclaringType.Namespace,
unpackedType.FullName,
string.Join(", ", expectedTypes.Select(t => t.FullName))));
}
}
var defaultValueAttr = fieldInfo?.GetCustomAttribute<DefaultValueAttribute>(false);
serializerFieldData.DefaultContents = defaultValueAttr?.EncodedBytes;
if (serializerFieldData.TagType == null && !serializerFieldData.IsAny)
{
if (unpackedType == typeof(bool))
{
serializerFieldData.TagType = UniversalTagNumber.Boolean;
}
else if (unpackedType == typeof(sbyte) ||
unpackedType == typeof(byte) ||
unpackedType == typeof(short) ||
unpackedType == typeof(ushort) ||
unpackedType == typeof(int) ||
unpackedType == typeof(uint) ||
unpackedType == typeof(long) ||
unpackedType == typeof(ulong) ||
unpackedType == typeof(BigInteger))
{
serializerFieldData.TagType = UniversalTagNumber.Integer;
}
else if (unpackedType.IsLayoutSequential)
{
serializerFieldData.TagType = UniversalTagNumber.Sequence;
}
else if (unpackedType == typeof(ReadOnlyMemory<byte>) ||
unpackedType == typeof(string) ||
unpackedType == typeof(DateTimeOffset))
{
throw new AsnAmbiguousFieldTypeException(fieldInfo, unpackedType);
}
else if (unpackedType == typeof(Oid))
{
serializerFieldData.TagType = UniversalTagNumber.ObjectIdentifier;
}
else if (unpackedType.IsArray)
{
serializerFieldData.TagType = UniversalTagNumber.SequenceOf;
}
else if (unpackedType.IsEnum)
{
if (typeT.GetCustomAttributes(typeof(FlagsAttribute), false).Length > 0)
{
serializerFieldData.TagType = UniversalTagNumber.BitString;
}
else
{
serializerFieldData.TagType = UniversalTagNumber.Enumerated;
}
}
else if (fieldInfo != null)
{
Debug.Fail($"No tag type bound for {fieldInfo.DeclaringType.FullName}.{fieldInfo.Name}");
throw new AsnSerializationConstraintException();
}
}
serializerFieldData.IsOptional = fieldInfo?.GetCustomAttribute<OptionalValueAttribute>(false) != null;
if (serializerFieldData.IsOptional && !CanBeNull(typeT))
{
throw new AsnSerializationConstraintException(
SR.Format(
SR.Cryptography_AsnSerializer_Optional_NonNullableField,
fieldInfo.Name,
fieldInfo.DeclaringType.FullName));
}
bool isChoice = GetChoiceAttribute(typeT) != null;
var tagOverride = fieldInfo?.GetCustomAttribute<ExpectedTagAttribute>(false);
if (tagOverride != null)
{
if (isChoice && !tagOverride.ExplicitTag)
{
throw new AsnSerializationConstraintException(
SR.Format(
SR.Cryptography_AsnSerializer_SpecificTagChoice,
fieldInfo.Name,
fieldInfo.DeclaringType.FullName,
typeT.FullName));
}
// This will throw for unmapped TagClass values
serializerFieldData.ExpectedTag = new Asn1Tag(tagOverride.TagClass, tagOverride.TagValue);
serializerFieldData.HasExplicitTag = tagOverride.ExplicitTag;
serializerFieldData.SpecifiedTag = true;
return;
}
if (isChoice)
{
serializerFieldData.TagType = null;
}
serializerFieldData.SpecifiedTag = false;
serializerFieldData.HasExplicitTag = false;
serializerFieldData.ExpectedTag = new Asn1Tag(serializerFieldData.TagType.GetValueOrDefault());
}
private static Type UnpackIfNullable(Type typeT)
{
return Nullable.GetUnderlyingType(typeT) ?? typeT;
}
private static Deserializer GetPrimitiveDeserializer(Type typeT, Asn1Tag tag)
{
if (typeT == typeof(bool))
return reader => reader.ReadBoolean(tag);
if (typeT == typeof(int))
return TryOrFail((AsnReader reader, out int value) => reader.TryReadInt32(tag, out value));
if (typeT == typeof(uint))
return TryOrFail((AsnReader reader, out uint value) => reader.TryReadUInt32(tag, out value));
if (typeT == typeof(short))
return TryOrFail((AsnReader reader, out short value) => reader.TryReadInt16(tag, out value));
if (typeT == typeof(ushort))
return TryOrFail((AsnReader reader, out ushort value) => reader.TryReadUInt16(tag, out value));
if (typeT == typeof(byte))
return TryOrFail((AsnReader reader, out byte value) => reader.TryReadUInt8(tag, out value));
if (typeT == typeof(sbyte))
return TryOrFail((AsnReader reader, out sbyte value) => reader.TryReadInt8(tag, out value));
if (typeT == typeof(long))
return TryOrFail((AsnReader reader, out long value) => reader.TryReadInt64(tag, out value));
if (typeT == typeof(ulong))
return TryOrFail((AsnReader reader, out ulong value) => reader.TryReadUInt64(tag, out value));
throw new AsnSerializationConstraintException(
SR.Format(
SR.Cryptography_AsnSerializer_UnhandledType,
typeT.FullName));
}
private static Serializer GetPrimitiveSerializer(Type typeT, Asn1Tag primitiveTag)
{
if (typeT == typeof(bool))
return (value, writer) => writer.WriteBoolean(primitiveTag, (bool)value);
if (typeT == typeof(int))
return (value, writer) => writer.WriteInteger(primitiveTag, (int)value);
if (typeT == typeof(uint))
return (value, writer) => writer.WriteInteger(primitiveTag, (uint)value);
if (typeT == typeof(short))
return (value, writer) => writer.WriteInteger(primitiveTag, (short)value);
if (typeT == typeof(ushort))
return (value, writer) => writer.WriteInteger(primitiveTag, (ushort)value);
if (typeT == typeof(byte))
return (value, writer) => writer.WriteInteger(primitiveTag, (byte)value);
if (typeT == typeof(sbyte))
return (value, writer) => writer.WriteInteger(primitiveTag, (sbyte)value);
if (typeT == typeof(long))
return (value, writer) => writer.WriteInteger(primitiveTag, (long)value);
if (typeT == typeof(ulong))
return (value, writer) => writer.WriteInteger(primitiveTag, (ulong)value);
throw new AsnSerializationConstraintException(
SR.Format(
SR.Cryptography_AsnSerializer_UnhandledType,
typeT.FullName));
}
/// <summary>
/// Read ASN.1 data from <paramref name="source"/> encoded under the specified encoding rules into
/// the typed structure.
/// </summary>
/// <typeparam name="T">
/// The type to deserialize as.
/// In order to be deserialized the type must have sequential layout, be sealed, and be composed of
/// members that are also able to be deserialized by this method.
/// </typeparam>
/// <param name="source">A view of the encoded bytes to be deserialized.</param>
/// <param name="ruleSet">The ASN.1 encoding ruleset to use for reading <paramref name="source"/>.</param>
/// <returns>A deserialized instance of <typeparamref name="T"/>.</returns>
/// <remarks>
/// Except for where required to for avoiding ambiguity, this method does not check that there are
/// no cycles in the type graph for <typeparamref name="T"/>. If <typeparamref name="T"/> is a
/// reference type (class) which includes a cycle in the type graph,
/// then it is possible for the data in <paramref name="source"/> to cause
/// an arbitrary extension to the maximum stack depth of this routine, leading to a
/// <see cref="StackOverflowException"/>.
///
/// If <typeparamref name="T"/> is a value type (struct) the compiler will enforce that there are no
/// cycles in the type graph.
///
/// When reference types are used the onus is on the caller of this method to prevent cycles, or to
/// mitigate the possibility of the stack overflow.
/// </remarks>
/// <exception cref="AsnSerializationConstraintException">
/// A portion of <typeparamref name="T"/> is invalid for deserialization.
/// </exception>
/// <exception cref="CryptographicException">
/// Any of the data in <paramref name="source"/> is invalid for mapping to the return value,
/// or data remains after deserialization.
/// </exception>
public static T Deserialize<T>(ReadOnlyMemory<byte> source, AsnEncodingRules ruleSet)
{
Deserializer deserializer = GetDeserializer(typeof(T), null);
AsnReader reader = new AsnReader(source, ruleSet);
T t = (T)deserializer(reader);
reader.ThrowIfNotEmpty();
return t;
}
/// <summary>
/// Serialize <paramref name="value"/> into an ASN.1 writer under the specified encoding rules.
/// </summary>
/// <typeparam name="T">
/// The type to serialize as.
/// In order to be serialized the type must have sequential layout, be sealed, and be composed of
/// members that are also able to be serialized by this method.
/// </typeparam>
/// <param name="value">The value to serialize.</param>
/// <param name="ruleSet">The ASN.1 encoding ruleset to use for writing <paramref name="value"/>.</param>
/// <returns>A deserialized instance of <typeparamref name="T"/>.</returns>
/// <remarks>
/// Except for where required to for avoiding ambiguity, this method does not check that there are
/// no cycles in the type graph for <typeparamref name="T"/>. If <typeparamref name="T"/> is a
/// reference type (class) which includes a cycle in the type graph, and there is a cycle within the
/// object graph this method will consume memory and stack space until one is exhausted.
///
/// If <typeparamref name="T"/> is a value type (struct) the compiler will enforce that there are no
/// cycles in the type graph.
///
/// When reference types are used the onus is on the caller of this method to prevent object cycles,
/// or to mitigate the possibility of the stack overflow or memory exhaustion.
/// </remarks>
/// <exception cref="AsnSerializationConstraintException">
/// A portion of <typeparamref name="T"/> is invalid for deserialization.
/// </exception>
public static AsnWriter Serialize<T>(T value, AsnEncodingRules ruleSet)
{
AsnWriter writer = new AsnWriter(ruleSet);
try
{
Serialize(value, writer);
return writer;
}
catch
{
writer.Dispose();
throw;
}
}
/// <summary>
/// Serialize <paramref name="value"/> into an ASN.1 writer under the specified encoding rules.
/// </summary>
/// <typeparam name="T">
/// The type to serialize as.
/// In order to be serialized the type must have sequential layout, be sealed, and be composed of
/// members that are also able to be serialized by this method.
/// </typeparam>
/// <param name="value">The value to serialize.</param>
/// <param name="existingWriter">An existing writer into which <paramref name="value"/> should be written.</param>
/// <returns>A deserialized instance of <typeparamref name="T"/>.</returns>
/// <remarks>
/// Except for where required to for avoiding ambiguity, this method does not check that there are
/// no cycles in the type graph for <typeparamref name="T"/>. If <typeparamref name="T"/> is a
/// reference type (class) which includes a cycle in the type graph, and there is a cycle within the
/// object graph this method will consume memory and stack space until one is exhausted.
///
/// If <typeparamref name="T"/> is a value type (struct) the compiler will enforce that there are no
/// cycles in the type graph.
///
/// When reference types are used the onus is on the caller of this method to prevent object cycles,
/// or to mitigate the possibility of the stack overflow or memory exhaustion.
/// </remarks>
/// <exception cref="AsnSerializationConstraintException">
/// A portion of <typeparamref name="T"/> is invalid for deserialization.
/// </exception>
public static void Serialize<T>(T value, AsnWriter existingWriter)
{
if (existingWriter == null)
{
throw new ArgumentNullException(nameof(existingWriter));
}
Serializer serializer = GetSerializer(typeof(T), null);
serializer(value, existingWriter);
}
private struct SerializerFieldData
{
internal bool WasCustomized;
internal UniversalTagNumber? TagType;
internal bool? PopulateOidFriendlyName;
internal bool IsAny;
internal bool IsCollection;
internal byte[] DefaultContents;
internal bool HasExplicitTag;
internal bool SpecifiedTag;
internal bool IsOptional;
internal int? TwoDigitYearMax;
internal Asn1Tag ExpectedTag;
internal bool? DisallowGeneralizedTimeFractions;
}
}
[AttributeUsage(AttributeTargets.Field)]
internal sealed class ExpectedTagAttribute : Attribute
{
public TagClass TagClass { get; }
public int TagValue { get; }
public bool ExplicitTag { get; set; }
public ExpectedTagAttribute(int tagValue)
: this(TagClass.ContextSpecific, tagValue)
{
}
public ExpectedTagAttribute(TagClass tagClass, int tagValue)
{
TagClass = tagClass;
TagValue = tagValue;
}
}
internal abstract class AsnTypeAttribute : Attribute
{
internal AsnTypeAttribute()
{
}
}
internal abstract class AsnEncodingRuleAttribute : Attribute
{
internal AsnEncodingRuleAttribute()
{
}
}
[AttributeUsage(AttributeTargets.Field)]
internal sealed class OctetStringAttribute : AsnTypeAttribute
{
}
[AttributeUsage(AttributeTargets.Field)]
internal sealed class BitStringAttribute : AsnTypeAttribute
{
}
[AttributeUsage(AttributeTargets.Field)]
internal sealed class AnyValueAttribute : AsnTypeAttribute
{
}
[AttributeUsage(AttributeTargets.Field)]
internal sealed class ObjectIdentifierAttribute : AsnTypeAttribute
{
public ObjectIdentifierAttribute()
{
}
public bool PopulateFriendlyName { get; set; }
}
[AttributeUsage(AttributeTargets.Field)]
internal sealed class BMPStringAttribute : AsnTypeAttribute
{
}
[AttributeUsage(AttributeTargets.Field)]
internal sealed class IA5StringAttribute : AsnTypeAttribute
{
}
[AttributeUsage(AttributeTargets.Field)]
internal sealed class UTF8StringAttribute : AsnTypeAttribute
{
}
[AttributeUsage(AttributeTargets.Field)]
internal sealed class PrintableStringAttribute : AsnTypeAttribute
{
}
[AttributeUsage(AttributeTargets.Field)]
internal sealed class VisibleStringAttribute : AsnTypeAttribute
{
}
[AttributeUsage(AttributeTargets.Field)]
internal sealed class SequenceOfAttribute : AsnTypeAttribute
{
}
[AttributeUsage(AttributeTargets.Field)]
internal sealed class SetOfAttribute : AsnTypeAttribute
{
}
[AttributeUsage(AttributeTargets.Field)]
internal sealed class IntegerAttribute : AsnTypeAttribute
{
}
[AttributeUsage(AttributeTargets.Field)]
internal sealed class UtcTimeAttribute : AsnTypeAttribute
{
public int TwoDigitYearMax { get; set; }
}
[AttributeUsage(AttributeTargets.Field)]
internal sealed class GeneralizedTimeAttribute : AsnTypeAttribute
{
public bool DisallowFractions { get; set; }
}
[AttributeUsage(AttributeTargets.Field)]
internal sealed class OptionalValueAttribute : AsnEncodingRuleAttribute
{
}
[AttributeUsage(AttributeTargets.Field)]
internal sealed class DefaultValueAttribute : AsnEncodingRuleAttribute
{
internal byte[] EncodedBytes { get; }
public DefaultValueAttribute(params byte[] encodedValue)
{
EncodedBytes = encodedValue;
}
public ReadOnlyMemory<byte> EncodedValue => EncodedBytes;
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
internal sealed class ChoiceAttribute : Attribute
{
public bool AllowNull { 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.Globalization;
using System.Net.Internals;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net
{
/// <devdoc>
/// <para>Provides simple
/// domain name resolution functionality.</para>
/// </devdoc>
public static class Dns
{
// Host names any longer than this automatically fail at the winsock level.
// If the host name is 255 chars, the last char must be a dot.
private const int MaxHostName = 255;
[Obsolete("GetHostByName is obsoleted for this type, please use GetHostEntry instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public static IPHostEntry GetHostByName(string hostName)
{
NameResolutionPal.EnsureSocketsAreInitialized();
if (hostName == null)
{
throw new ArgumentNullException(nameof(hostName));
}
// See if it's an IP Address.
IPAddress address;
if (IPAddress.TryParse(hostName, out address))
{
return NameResolutionUtilities.GetUnresolvedAnswer(address);
}
return InternalGetHostByName(hostName, false);
}
private static IPHostEntry InternalGetHostByName(string hostName, bool includeIPv6)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(null, hostName);
IPHostEntry ipHostEntry = null;
if (hostName.Length > MaxHostName // If 255 chars, the last one must be a dot.
|| hostName.Length == MaxHostName && hostName[MaxHostName - 1] != '.')
{
throw new ArgumentOutOfRangeException(nameof(hostName), SR.Format(SR.net_toolong,
nameof(hostName), MaxHostName.ToString(NumberFormatInfo.CurrentInfo)));
}
//
// IPv6 Changes: IPv6 requires the use of getaddrinfo() rather
// than the traditional IPv4 gethostbyaddr() / gethostbyname().
// getaddrinfo() is also protocol independent in that it will also
// resolve IPv4 names / addresses. As a result, it is the preferred
// resolution mechanism on platforms that support it (Windows 5.1+).
// If getaddrinfo() is unsupported, IPv6 resolution does not work.
//
// Consider : If IPv6 is disabled, we could detect IPv6 addresses
// and throw an unsupported platform exception.
//
// Note : Whilst getaddrinfo is available on WinXP+, we only
// use it if IPv6 is enabled (platform is part of that
// decision). This is done to minimize the number of
// possible tests that are needed.
//
if (includeIPv6 || SocketProtocolSupportPal.OSSupportsIPv6)
{
//
// IPv6 enabled: use getaddrinfo() to obtain DNS information.
//
int nativeErrorCode;
SocketError errorCode = NameResolutionPal.TryGetAddrInfo(hostName, out ipHostEntry, out nativeErrorCode);
if (errorCode != SocketError.Success)
{
throw SocketExceptionFactory.CreateSocketException(errorCode, nativeErrorCode);
}
}
else
{
ipHostEntry = NameResolutionPal.GetHostByName(hostName);
}
if (NetEventSource.IsEnabled) NetEventSource.Exit(null, ipHostEntry);
return ipHostEntry;
} // GetHostByName
[Obsolete("GetHostByAddress is obsoleted for this type, please use GetHostEntry instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public static IPHostEntry GetHostByAddress(string address)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(null, address);
NameResolutionPal.EnsureSocketsAreInitialized();
if (address == null)
{
throw new ArgumentNullException(nameof(address));
}
IPHostEntry ipHostEntry = InternalGetHostByAddress(IPAddress.Parse(address), false);
if (NetEventSource.IsEnabled) NetEventSource.Exit(null, ipHostEntry);
return ipHostEntry;
} // GetHostByAddress
[Obsolete("GetHostByAddress is obsoleted for this type, please use GetHostEntry instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public static IPHostEntry GetHostByAddress(IPAddress address)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(null, address);
NameResolutionPal.EnsureSocketsAreInitialized();
if (address == null)
{
throw new ArgumentNullException(nameof(address));
}
IPHostEntry ipHostEntry = InternalGetHostByAddress(address, false);
if (NetEventSource.IsEnabled) NetEventSource.Exit(null, ipHostEntry);
return ipHostEntry;
} // GetHostByAddress
// Does internal IPAddress reverse and then forward lookups (for Legacy and current public methods).
private static IPHostEntry InternalGetHostByAddress(IPAddress address, bool includeIPv6)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(null, address);
//
// IPv6 Changes: We need to use the new getnameinfo / getaddrinfo functions
// for resolution of IPv6 addresses.
//
if (SocketProtocolSupportPal.OSSupportsIPv6 || includeIPv6)
{
//
// Try to get the data for the host from it's address
//
// We need to call getnameinfo first, because getaddrinfo w/ the ipaddress string
// will only return that address and not the full list.
// Do a reverse lookup to get the host name.
SocketError errorCode;
int nativeErrorCode;
string name = NameResolutionPal.TryGetNameInfo(address, out errorCode, out nativeErrorCode);
if (errorCode == SocketError.Success)
{
// Do the forward lookup to get the IPs for that host name
IPHostEntry hostEntry;
errorCode = NameResolutionPal.TryGetAddrInfo(name, out hostEntry, out nativeErrorCode);
if (errorCode == SocketError.Success)
{
return hostEntry;
}
if (NetEventSource.IsEnabled) NetEventSource.Error(null, SocketExceptionFactory.CreateSocketException(errorCode, nativeErrorCode));
// One of two things happened:
// 1. There was a ptr record in dns, but not a corollary A/AAA record.
// 2. The IP was a local (non-loopback) IP that resolved to a connection specific dns suffix.
// - Workaround, Check "Use this connection's dns suffix in dns registration" on that network
// adapter's advanced dns settings.
// Just return the resolved host name and no IPs.
return hostEntry;
}
throw SocketExceptionFactory.CreateSocketException(errorCode, nativeErrorCode);
}
//
// If IPv6 is not enabled (maybe config switch) but we've been
// given an IPv6 address then we need to bail out now.
//
else
{
if (address.AddressFamily == AddressFamily.InterNetworkV6)
{
//
// Protocol not supported
//
throw new SocketException((int)SocketError.ProtocolNotSupported);
}
//
// Use gethostbyaddr() to try to resolve the IP address
//
// End IPv6 Changes
//
return NameResolutionPal.GetHostByAddr(address);
}
} // InternalGetHostByAddress
/*****************************************************************************
Function : gethostname
Abstract: Queries the hostname from DNS
Input Parameters:
Returns: String
******************************************************************************/
/// <devdoc>
/// <para>Gets the host name of the local machine.</para>
/// </devdoc>
public static string GetHostName()
{
if (NetEventSource.IsEnabled) NetEventSource.Info(null, null);
NameResolutionPal.EnsureSocketsAreInitialized();
return NameResolutionPal.GetHostName();
}
[Obsolete("Resolve is obsoleted for this type, please use GetHostEntry instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public static IPHostEntry Resolve(string hostName)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(null, hostName);
NameResolutionPal.EnsureSocketsAreInitialized();
if (hostName == null)
{
throw new ArgumentNullException(nameof(hostName));
}
// See if it's an IP Address.
IPAddress address;
IPHostEntry ipHostEntry;
if (IPAddress.TryParse(hostName, out address) && (address.AddressFamily != AddressFamily.InterNetworkV6 || SocketProtocolSupportPal.OSSupportsIPv6))
{
try
{
ipHostEntry = InternalGetHostByAddress(address, false);
}
catch (SocketException ex)
{
if (NetEventSource.IsEnabled) NetEventSource.Error(null, ex);
ipHostEntry = NameResolutionUtilities.GetUnresolvedAnswer(address);
}
}
else
{
ipHostEntry = InternalGetHostByName(hostName, false);
}
if (NetEventSource.IsEnabled) NetEventSource.Exit(null, ipHostEntry);
return ipHostEntry;
}
private class ResolveAsyncResult : ContextAwareResult
{
// Forward lookup
internal ResolveAsyncResult(string hostName, object myObject, bool includeIPv6, object myState, AsyncCallback myCallBack) :
base(myObject, myState, myCallBack)
{
this.hostName = hostName;
this.includeIPv6 = includeIPv6;
}
// Reverse lookup
internal ResolveAsyncResult(IPAddress address, object myObject, bool includeIPv6, object myState, AsyncCallback myCallBack) :
base(myObject, myState, myCallBack)
{
this.includeIPv6 = includeIPv6;
this.address = address;
}
internal readonly string hostName;
internal bool includeIPv6;
internal IPAddress address;
}
private static void ResolveCallback(object context)
{
ResolveAsyncResult result = (ResolveAsyncResult)context;
IPHostEntry hostEntry;
try
{
if (result.address != null)
{
hostEntry = InternalGetHostByAddress(result.address, result.includeIPv6);
}
else
{
hostEntry = InternalGetHostByName(result.hostName, result.includeIPv6);
}
}
catch (OutOfMemoryException)
{
throw;
}
catch (Exception exception)
{
result.InvokeCallback(exception);
return;
}
result.InvokeCallback(hostEntry);
}
// Helpers for async GetHostByName, ResolveToAddresses, and Resolve - they're almost identical
// If hostName is an IPString and justReturnParsedIP==true then no reverse lookup will be attempted, but the original address is returned.
private static IAsyncResult HostResolutionBeginHelper(string hostName, bool justReturnParsedIp, bool includeIPv6, bool throwOnIIPAny, AsyncCallback requestCallback, object state)
{
if (hostName == null)
{
throw new ArgumentNullException(nameof(hostName));
}
if (NetEventSource.IsEnabled) NetEventSource.Info(null, hostName);
// See if it's an IP Address.
IPAddress address;
ResolveAsyncResult asyncResult;
if (IPAddress.TryParse(hostName, out address))
{
if (throwOnIIPAny && (address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any)))
{
throw new ArgumentException(SR.net_invalid_ip_addr, nameof(hostName));
}
asyncResult = new ResolveAsyncResult(address, null, includeIPv6, state, requestCallback);
if (justReturnParsedIp)
{
IPHostEntry hostEntry = NameResolutionUtilities.GetUnresolvedAnswer(address);
asyncResult.StartPostingAsyncOp(false);
asyncResult.InvokeCallback(hostEntry);
asyncResult.FinishPostingAsyncOp();
return asyncResult;
}
}
else
{
asyncResult = new ResolveAsyncResult(hostName, null, includeIPv6, state, requestCallback);
}
// Set up the context, possibly flow.
asyncResult.StartPostingAsyncOp(false);
// Start the resolve.
Task.Factory.StartNew(
s => ResolveCallback(s),
asyncResult,
CancellationToken.None,
TaskCreationOptions.DenyChildAttach,
TaskScheduler.Default);
// Finish the flowing, maybe it completed? This does nothing if we didn't initiate the flowing above.
asyncResult.FinishPostingAsyncOp();
return asyncResult;
}
private static IAsyncResult HostResolutionBeginHelper(IPAddress address, bool flowContext, bool includeIPv6, AsyncCallback requestCallback, object state)
{
if (address == null)
{
throw new ArgumentNullException(nameof(address));
}
if (address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any))
{
throw new ArgumentException(SR.net_invalid_ip_addr, nameof(address));
}
if (NetEventSource.IsEnabled) NetEventSource.Info(null, address);
// Set up the context, possibly flow.
ResolveAsyncResult asyncResult = new ResolveAsyncResult(address, null, includeIPv6, state, requestCallback);
if (flowContext)
{
asyncResult.StartPostingAsyncOp(false);
}
// Start the resolve.
Task.Factory.StartNew(
s => ResolveCallback(s),
asyncResult,
CancellationToken.None,
TaskCreationOptions.DenyChildAttach,
TaskScheduler.Default);
// Finish the flowing, maybe it completed? This does nothing if we didn't initiate the flowing above.
asyncResult.FinishPostingAsyncOp();
return asyncResult;
}
private static IPHostEntry HostResolutionEndHelper(IAsyncResult asyncResult)
{
//
// parameter validation
//
if (asyncResult == null)
{
throw new ArgumentNullException(nameof(asyncResult));
}
ResolveAsyncResult castedResult = asyncResult as ResolveAsyncResult;
if (castedResult == null)
{
throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
}
if (castedResult.EndCalled)
{
throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, nameof(EndResolve)));
}
if (NetEventSource.IsEnabled) NetEventSource.Info(null);
castedResult.InternalWaitForCompletion();
castedResult.EndCalled = true;
Exception exception = castedResult.Result as Exception;
if (exception != null)
{
throw exception;
}
return (IPHostEntry)castedResult.Result;
}
[Obsolete("BeginGetHostByName is obsoleted for this type, please use BeginGetHostEntry instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public static IAsyncResult BeginGetHostByName(string hostName, AsyncCallback requestCallback, object stateObject)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(null, hostName);
NameResolutionPal.EnsureSocketsAreInitialized();
IAsyncResult asyncResult = HostResolutionBeginHelper(hostName, true, true, false, requestCallback, stateObject);
if (NetEventSource.IsEnabled) NetEventSource.Exit(null, asyncResult);
return asyncResult;
} // BeginGetHostByName
[Obsolete("EndGetHostByName is obsoleted for this type, please use EndGetHostEntry instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public static IPHostEntry EndGetHostByName(IAsyncResult asyncResult)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(null, asyncResult);
NameResolutionPal.EnsureSocketsAreInitialized();
IPHostEntry ipHostEntry = HostResolutionEndHelper(asyncResult);
if (NetEventSource.IsEnabled) NetEventSource.Exit(null, ipHostEntry);
return ipHostEntry;
} // EndGetHostByName()
public static IPHostEntry GetHostEntry(string hostNameOrAddress)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(null, hostNameOrAddress);
NameResolutionPal.EnsureSocketsAreInitialized();
if (hostNameOrAddress == null)
{
throw new ArgumentNullException(nameof(hostNameOrAddress));
}
// See if it's an IP Address.
IPAddress address;
IPHostEntry ipHostEntry;
if (IPAddress.TryParse(hostNameOrAddress, out address))
{
if (address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any))
{
throw new ArgumentException(SR.Format(SR.net_invalid_ip_addr, nameof(hostNameOrAddress)));
}
ipHostEntry = InternalGetHostByAddress(address, true);
}
else
{
ipHostEntry = InternalGetHostByName(hostNameOrAddress, true);
}
if (NetEventSource.IsEnabled) NetEventSource.Exit(null, ipHostEntry);
return ipHostEntry;
}
public static IPHostEntry GetHostEntry(IPAddress address)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(null, address);
NameResolutionPal.EnsureSocketsAreInitialized();
if (address == null)
{
throw new ArgumentNullException(nameof(address));
}
if (address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any))
{
throw new ArgumentException(SR.Format(SR.net_invalid_ip_addr, nameof(address)));
}
IPHostEntry ipHostEntry = InternalGetHostByAddress(address, true);
if (NetEventSource.IsEnabled) NetEventSource.Exit(null, ipHostEntry);
return ipHostEntry;
} // GetHostEntry
public static IPAddress[] GetHostAddresses(string hostNameOrAddress)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(null, hostNameOrAddress);
NameResolutionPal.EnsureSocketsAreInitialized();
if (hostNameOrAddress == null)
{
throw new ArgumentNullException(nameof(hostNameOrAddress));
}
// See if it's an IP Address.
IPAddress address;
IPAddress[] addresses;
if (IPAddress.TryParse(hostNameOrAddress, out address))
{
if (address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any))
{
throw new ArgumentException(SR.Format(SR.net_invalid_ip_addr, nameof(hostNameOrAddress)));
}
addresses = new IPAddress[] { address };
}
else
{
// InternalGetHostByName works with IP addresses (and avoids a reverse-lookup), but we need
// explicit handling in order to do the ArgumentException and guarantee the behavior.
addresses = InternalGetHostByName(hostNameOrAddress, true).AddressList;
}
if (NetEventSource.IsEnabled) NetEventSource.Exit(null, addresses);
return addresses;
}
public static IAsyncResult BeginGetHostEntry(string hostNameOrAddress, AsyncCallback requestCallback, object stateObject)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(null, hostNameOrAddress);
NameResolutionPal.EnsureSocketsAreInitialized();
IAsyncResult asyncResult = HostResolutionBeginHelper(hostNameOrAddress, false, true, true, requestCallback, stateObject);
if (NetEventSource.IsEnabled) NetEventSource.Exit(null, asyncResult);
return asyncResult;
} // BeginResolve
public static IAsyncResult BeginGetHostEntry(IPAddress address, AsyncCallback requestCallback, object stateObject)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(null, address);
NameResolutionPal.EnsureSocketsAreInitialized();
IAsyncResult asyncResult = HostResolutionBeginHelper(address, true, true, requestCallback, stateObject);
if (NetEventSource.IsEnabled) NetEventSource.Exit(null, asyncResult);
return asyncResult;
} // BeginResolve
public static IPHostEntry EndGetHostEntry(IAsyncResult asyncResult)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(null, asyncResult);
IPHostEntry ipHostEntry = HostResolutionEndHelper(asyncResult);
if (NetEventSource.IsEnabled) NetEventSource.Exit(null, ipHostEntry);
return ipHostEntry;
} // EndResolve()
public static IAsyncResult BeginGetHostAddresses(string hostNameOrAddress, AsyncCallback requestCallback, object state)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(null, hostNameOrAddress);
NameResolutionPal.EnsureSocketsAreInitialized();
IAsyncResult asyncResult = HostResolutionBeginHelper(hostNameOrAddress, true, true, true, requestCallback, state);
if (NetEventSource.IsEnabled) NetEventSource.Exit(null, asyncResult);
return asyncResult;
} // BeginResolve
public static IPAddress[] EndGetHostAddresses(IAsyncResult asyncResult)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(null, asyncResult);
IPHostEntry ipHostEntry = HostResolutionEndHelper(asyncResult);
if (NetEventSource.IsEnabled) NetEventSource.Exit(null, ipHostEntry);
return ipHostEntry.AddressList;
} // EndResolveToAddresses
[Obsolete("BeginResolve is obsoleted for this type, please use BeginGetHostEntry instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public static IAsyncResult BeginResolve(string hostName, AsyncCallback requestCallback, object stateObject)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(null, hostName);
NameResolutionPal.EnsureSocketsAreInitialized();
IAsyncResult asyncResult = HostResolutionBeginHelper(hostName, false, false, false, requestCallback, stateObject);
if (NetEventSource.IsEnabled) NetEventSource.Exit(null, asyncResult);
return asyncResult;
} // BeginResolve
[Obsolete("EndResolve is obsoleted for this type, please use EndGetHostEntry instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public static IPHostEntry EndResolve(IAsyncResult asyncResult)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(null, asyncResult);
IPHostEntry ipHostEntry;
try
{
ipHostEntry = HostResolutionEndHelper(asyncResult);
}
catch (SocketException ex)
{
IPAddress address = ((ResolveAsyncResult)asyncResult).address;
if (address == null)
throw; // BeginResolve was called with a HostName, not an IPAddress
if (NetEventSource.IsEnabled) NetEventSource.Error(null, ex);
ipHostEntry = NameResolutionUtilities.GetUnresolvedAnswer(address);
}
if (NetEventSource.IsEnabled) NetEventSource.Exit(null, ipHostEntry);
return ipHostEntry;
} // EndResolve()
//************* Task-based async public methods *************************
public static Task<IPAddress[]> GetHostAddressesAsync(string hostNameOrAddress)
{
NameResolutionPal.EnsureSocketsAreInitialized();
return Task<IPAddress[]>.Factory.FromAsync(
(arg, requestCallback, stateObject) => BeginGetHostAddresses(arg, requestCallback, stateObject),
asyncResult => EndGetHostAddresses(asyncResult),
hostNameOrAddress,
null);
}
public static Task<IPHostEntry> GetHostEntryAsync(IPAddress address)
{
NameResolutionPal.EnsureSocketsAreInitialized();
return Task<IPHostEntry>.Factory.FromAsync(
(arg, requestCallback, stateObject) => BeginGetHostEntry(arg, requestCallback, stateObject),
asyncResult => EndGetHostEntry(asyncResult),
address,
null);
}
public static Task<IPHostEntry> GetHostEntryAsync(string hostNameOrAddress)
{
NameResolutionPal.EnsureSocketsAreInitialized();
return Task<IPHostEntry>.Factory.FromAsync(
(arg, requestCallback, stateObject) => BeginGetHostEntry(arg, requestCallback, stateObject),
asyncResult => EndGetHostEntry(asyncResult),
hostNameOrAddress,
null);
}
}
}
| |
namespace PokerTell.Repository.Tests.Database
{
using System.Collections.Generic;
using Infrastructure.Events;
using Infrastructure.Interfaces.DatabaseSetup;
using Infrastructure.Interfaces.PokerHand;
using Infrastructure.Interfaces.Repository;
using Interfaces;
using Machine.Specifications;
using Microsoft.Practices.Composite.Events;
using Microsoft.Practices.Composite.Presentation.Events;
using Moq;
using PokerTell.Repository.Database;
using Tools.Interfaces;
using UnitTests.Fakes;
using It=Machine.Specifications.It;
// Resharper disable InconsistentNaming
public abstract class DatabaseImporterSpecs
{
static IEventAggregator _eventAggregator;
static Mock<IPokerTrackerHandHistoryRetriever> _pokerTrackerHandHistoryRetriever_Mock;
static Mock<IPokerOfficeHandHistoryRetriever> _pokerOfficeHandHistoryRetriever_Mock;
static Mock<IPokerTellHandHistoryRetriever> _pokerTellHandHistoryRetriever_Mock;
static Mock<IRepository> _repository_Mock;
static Mock<IDataProvider> _dataProvider_Mock;
static BackgroundWorkerMock _backgroundWorker_Mock;
static DatabaseImporterSut _sut;
Establish specContext = () => {
_eventAggregator = new EventAggregator();
_backgroundWorker_Mock = new BackgroundWorkerMock();
_repository_Mock = new Mock<IRepository>();
_pokerTrackerHandHistoryRetriever_Mock = new Mock<IPokerTrackerHandHistoryRetriever>();
_pokerTrackerHandHistoryRetriever_Mock
.Setup(hr => hr.Using(Moq.It.IsAny<IDataProvider>()))
.Returns(_pokerTrackerHandHistoryRetriever_Mock.Object);
_pokerOfficeHandHistoryRetriever_Mock = new Mock<IPokerOfficeHandHistoryRetriever>();
_pokerOfficeHandHistoryRetriever_Mock
.Setup(hr => hr.Using(Moq.It.IsAny<IDataProvider>()))
.Returns(_pokerOfficeHandHistoryRetriever_Mock.Object);
_pokerTellHandHistoryRetriever_Mock = new Mock<IPokerTellHandHistoryRetriever>();
_pokerTellHandHistoryRetriever_Mock
.Setup(hr => hr.Using(Moq.It.IsAny<IDataProvider>()))
.Returns(_pokerTellHandHistoryRetriever_Mock.Object);
_sut = new DatabaseImporterSut(_eventAggregator,
_backgroundWorker_Mock,
_repository_Mock.Object,
_pokerTellHandHistoryRetriever_Mock.Object,
_pokerOfficeHandHistoryRetriever_Mock.Object,
_pokerTrackerHandHistoryRetriever_Mock.Object);
_dataProvider_Mock = new Mock<IDataProvider>();
};
[Subject(typeof(DatabaseImporter), "ImportFrom")]
public class when_told_to_import_from_a_PokerOffice_database_given_a_connected_dataprovider : DatabaseImporterSpecs
{
const string databaseName = "someName";
const PokerStatisticsApplications application = PokerStatisticsApplications.PokerOffice;
Because of = () => _sut.ImportFrom(application, databaseName, _dataProvider_Mock.Object);
It should_be_busy = () => _sut.IsBusy.ShouldBeTrue();
It should_set_the_database_name_to_the_given_database = () => _sut.DatabaseName.ShouldEqual(databaseName);
It should_tell_the_PokerOffice_retriever_to_use_the_DataProvider
= () => _pokerOfficeHandHistoryRetriever_Mock.Verify(hr => hr.Using(_dataProvider_Mock.Object));
It should_import_handhistories_using_the_PokerOffice_retriever
= () => _sut.RetrieverWithWhichHandHistoriesWereImported.ShouldEqual(_pokerOfficeHandHistoryRetriever_Mock.Object);
}
[Subject(typeof(DatabaseImporter), "ImportFrom")]
public class when_told_to_import_from_a_PokerTracker_database_given_a_connected_dataprovider : DatabaseImporterSpecs
{
const string databaseName = "someName";
const PokerStatisticsApplications application = PokerStatisticsApplications.PokerTracker;
Because of = () => _sut.ImportFrom(application, databaseName, _dataProvider_Mock.Object);
It should_be_busy = () => _sut.IsBusy.ShouldBeTrue();
It should_set_the_database_name_to_the_given_database = () => _sut.DatabaseName.ShouldEqual(databaseName);
It should_tell_the_PokerTracker_retriever_to_use_the_DataProvider
= () => _pokerTrackerHandHistoryRetriever_Mock.Verify(hr => hr.Using(_dataProvider_Mock.Object));
It should_import_handhistories_using_the_PokerTracker_retriever
= () => _sut.RetrieverWithWhichHandHistoriesWereImported.ShouldEqual(_pokerTrackerHandHistoryRetriever_Mock.Object);
}
[Subject(typeof(DatabaseImporter), "ImportFrom")]
public class when_told_to_import_from_a_PokerTell_database_given_a_connected_dataprovider : DatabaseImporterSpecs
{
const string databaseName = "someName";
const PokerStatisticsApplications application = PokerStatisticsApplications.PokerTell;
Because of = () => _sut.ImportFrom(application, databaseName, _dataProvider_Mock.Object);
It should_be_busy = () => _sut.IsBusy.ShouldBeTrue();
It should_set_the_database_name_to_the_given_database = () => _sut.DatabaseName.ShouldEqual(databaseName);
It should_tell_the_PokerTell_retriever_to_use_the_DataProvider
= () => _pokerTellHandHistoryRetriever_Mock.Verify(hr => hr.Using(_dataProvider_Mock.Object));
It should_import_handhistories_using_the_PokerTell_retriever
= () => _sut.RetrieverWithWhichHandHistoriesWereImported.ShouldEqual(_pokerTellHandHistoryRetriever_Mock.Object);
}
[Subject(typeof(DatabaseImporter), "PrepareToImportHandHistories")]
public class when_told_to_prepare_to_import_handhistories_using_a_given_hand_history_retriever : DatabaseImporterSpecs
{
const int handHistoriesCount = 1;
static int percentageForWhichProgressWasReported;
static Mock<IHandHistoryRetriever> handHistoryRetriever_Mock;
Establish context = () => {
handHistoryRetriever_Mock = new Mock<IHandHistoryRetriever>();
handHistoryRetriever_Mock
.SetupGet(hr => hr.HandHistoriesCount)
.Returns(handHistoriesCount);
_eventAggregator
.GetEvent<ProgressUpdateEvent>()
.Subscribe(args => percentageForWhichProgressWasReported = args.PercentCompleted);
};
Because of = () => _sut.Invoke_PrepareToImportHandHistoriesUsing(handHistoryRetriever_Mock.Object);
It should_become_busy = () => _sut.IsBusy.ShouldBeTrue();
It should_set_the_number_of_hands_to_import_to_the_hand_histories_count_of_the_retrieve
= () => _sut.NumberOfHandsToImport.ShouldEqual(handHistoriesCount);
It should_report_zero_progress_to_show_the_progress_bar = () => percentageForWhichProgressWasReported.ShouldEqual(0);
}
[Subject(typeof(DatabaseImporter), "ImportNextBatchOfHandHistories")]
public class when_told_to_import_next_batch_of_total_of_10_hand_histories_from_a_given_hand_history_retriever_which_returns_2_assuming_that_both_are_successfully_converted_and_2_were_attempted_to_import_previously_and_batchsize_is_3
: DatabaseImporterSpecs
{
const string firstRetrievedHandhistory = "firstHandHistory";
const string secondRetrievedHandhistory = "secondHandHistory";
static int percentageForWhichProgressWasReported;
const int batchSize = 3;
const int numberOfHandsAttemptedToImportSoFar = 2;
const int numberOfHandsSuccessfullyImportedSoFar = 1;
const int handHistoriesCount = 10;
static Mock<IHandHistoryRetriever> handHistoryRetriever_Mock;
static IEnumerable<string> retrievedHandHistories;
static IEnumerable<IConvertedPokerHand> retrievedConvertedHands;
static IList<int> percentagesForWhichProgressWasReported;
Establish context = () => {
_eventAggregator
.GetEvent<ProgressUpdateEvent>()
.Subscribe(args => percentageForWhichProgressWasReported = args.PercentCompleted);
retrievedHandHistories = new[] { firstRetrievedHandhistory, secondRetrievedHandhistory };
handHistoryRetriever_Mock = new Mock<IHandHistoryRetriever>();
handHistoryRetriever_Mock
.Setup(hr => hr.GetNext(batchSize))
.Returns(retrievedHandHistories);
handHistoryRetriever_Mock
.SetupGet(hr => hr.HandHistoriesCount)
.Returns(handHistoriesCount);
retrievedConvertedHands = new[] { new Mock<IConvertedPokerHand>().Object, new Mock<IConvertedPokerHand>().Object };
_repository_Mock
.Setup(r => r.RetrieveHandsFromString(Moq.It.IsAny<string>()))
.Returns(retrievedConvertedHands);
percentagesForWhichProgressWasReported = new List<int>();
_eventAggregator
.GetEvent<ProgressUpdateEvent>()
.Subscribe(args => percentagesForWhichProgressWasReported.Add(args.PercentCompleted));
_sut.BatchSize = batchSize;
_sut.NumberOfHandsToImport = handHistoriesCount;
_sut.NumberOfHandsAttemptedToImport = numberOfHandsAttemptedToImportSoFar;
_sut.NumberOfHandsSuccessfullyImported = numberOfHandsSuccessfullyImportedSoFar;
};
Because of = () => _sut.Invoke_ImportNextBatchOfHandHistoriesUsing(handHistoryRetriever_Mock.Object);
It should_tell_the_retriever_to_get_the_next_batch_of_hand_histories
= () => handHistoryRetriever_Mock.Verify(hr => hr.GetNext(batchSize));
It should_tell_the_Repository_to_parse_the_combined_hand_histories_returned_by_the_retriever
= () => _repository_Mock.Verify(r => r.RetrieveHandsFromString(Moq.It.Is<string>(
str => str.Contains(firstRetrievedHandhistory) && str.Contains(secondRetrievedHandhistory))));
It should_tell_the_Repository_to_insert_the_converted_hands_it_returned_when_it_parsed_the_hand_histories
= () => _repository_Mock.Verify(r => r.InsertHands(retrievedConvertedHands));
It should_add_the_batchSize_to_the_NumberOfHandsAttemptedToImport
= () => _sut.NumberOfHandsAttemptedToImport.ShouldEqual(numberOfHandsAttemptedToImportSoFar + batchSize);
It should_add_2_to_the_NumberOfHandsSuccessfullyImported
= () => _sut.NumberOfHandsSuccessfullyImported.ShouldEqual(numberOfHandsSuccessfullyImportedSoFar + 2);
It should_report_progress_of_50_percent_to_hide_progressbar = () => percentageForWhichProgressWasReported.ShouldEqual(50);
}
[Subject(typeof(DatabaseImporter), "FinishedImporting")]
public class when_it_finishes_importing_hand_histories : DatabaseImporterSpecs
{
static int percentageForWhichProgressWasReported;
static string userMessageAboutImportedHands;
const int numberOfHandsSuccessfullyImported = 1;
const string databaseName = "some database";
Establish context = () => {
_eventAggregator
.GetEvent<ProgressUpdateEvent>()
.Subscribe(args => percentageForWhichProgressWasReported = args.PercentCompleted);
_eventAggregator
.GetEvent<UserMessageEvent>()
.Subscribe(args => userMessageAboutImportedHands = args.UserMessage,
ThreadOption.PublisherThread,
false,
args => args.MessageType == UserMessageTypes.Info);
_sut
.Set_IsBusy(true)
.NumberOfHandsSuccessfullyImported = numberOfHandsSuccessfullyImported;
_sut.DatabaseName = databaseName;
};
Because of = () => _sut.Invoke_FinishedImportingHandHistories();
It should_become_not_busy = () => _sut.IsBusy.ShouldBeFalse();
It should_report_progress_of_100_percent_to_hide_progressbar = () => percentageForWhichProgressWasReported.ShouldEqual(100);
It should_let_the_user_know_how_many_hands_it_successfully_imported
= () => userMessageAboutImportedHands.ShouldContain(numberOfHandsSuccessfullyImported + " hands");
It should_let_the_user_know_what_database_it_imported_the_hands_from
= () => userMessageAboutImportedHands.ShouldContain(databaseName);
}
[Subject(typeof(DatabaseImporter), "IsBusy changed")]
public class when_the_busy_status_changed : DatabaseImporterSpecs
{
static bool isBusyChangedWasRaised;
static bool isBusyChangedWasRaisedWith;
const bool newBusyState = true;
Establish context = () => _sut.IsBusyChanged += arg => {
isBusyChangedWasRaised = true;
isBusyChangedWasRaisedWith = arg;
};
Because of = () => _sut.Set_IsBusy(newBusyState);
It should_let_me_know = () => isBusyChangedWasRaised.ShouldBeTrue();
It should_pass_the_new_busy_state = () => isBusyChangedWasRaisedWith.ShouldEqual(newBusyState);
}
}
public class DatabaseImporterSut : DatabaseImporter
{
public IHandHistoryRetriever RetrieverWithWhichHandHistoriesWereImported;
public int NumberOfHandsToImport
{
get { return _numberOfHandsToImport; }
set { _numberOfHandsToImport = value; }
}
public int NumberOfHandsSuccessfullyImported
{
get { return _numberOfHandsSuccessfullyImported; }
set { _numberOfHandsSuccessfullyImported = value; }
}
public string DatabaseName
{
get { return _databaseName; }
set { _databaseName = value; }
}
public int NumberOfHandsAttemptedToImport
{
get { return _numberOfHandsAttemptedToImport; }
set { _numberOfHandsAttemptedToImport = value; }
}
public DatabaseImporterSut Set_IsBusy(bool isBusy)
{
IsBusy = true;
return this;
}
public DatabaseImporterSut(IEventAggregator eventAggregator, IBackgroundWorker backgroundWorker, IRepository repository, IPokerTellHandHistoryRetriever pokerTellHandHistoryRetriever, IPokerOfficeHandHistoryRetriever pokerOfficeHandHistoryRetriever, IPokerTrackerHandHistoryRetriever pokerTrackerHandHistoryRetriever)
: base(eventAggregator, backgroundWorker, repository, pokerTellHandHistoryRetriever, pokerOfficeHandHistoryRetriever, pokerTrackerHandHistoryRetriever)
{
}
public void Invoke_ImportHandHistoriesUsing(IHandHistoryRetriever handHistoryRetriever)
{
ImportHandHistoriesUsing(handHistoryRetriever);
}
public void Invoke_PrepareToImportHandHistoriesUsing(IHandHistoryRetriever handHistoryRetriever)
{
PrepareToImportHandHistoriesUsing(handHistoryRetriever);
}
public void Invoke_ImportNextBatchOfHandHistoriesUsing(IHandHistoryRetriever handHistoryRetriever)
{
ImportNextBatchOfHandHistoriesUsing(handHistoryRetriever);
}
public void Invoke_FinishedImportingHandHistories()
{
FinishedImportingHandHistories();
}
protected override void ImportHandHistoriesUsing(IHandHistoryRetriever handHistoryRetriever)
{
// Don't call base here since it will end up in a while loop which will never end since our HandHistory retriever mock will never be done.
RetrieverWithWhichHandHistoriesWereImported = handHistoryRetriever;
}
}
}
| |
// 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!
namespace Google.Cloud.Dataproc.V1.Snippets
{
using Google.Api.Gax;
using Google.LongRunning;
using Google.Protobuf.WellKnownTypes;
using System;
using System.Linq;
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class AllGeneratedClusterControllerClientSnippets
{
/// <summary>Snippet for CreateCluster</summary>
public void CreateClusterRequestObject()
{
// Snippet: CreateCluster(CreateClusterRequest, CallSettings)
// Create client
ClusterControllerClient clusterControllerClient = ClusterControllerClient.Create();
// Initialize request argument(s)
CreateClusterRequest request = new CreateClusterRequest
{
ProjectId = "",
Cluster = new Cluster(),
Region = "",
RequestId = "",
ActionOnFailedPrimaryWorkers = FailureAction.Unspecified,
};
// Make the request
Operation<Cluster, ClusterOperationMetadata> response = clusterControllerClient.CreateCluster(request);
// Poll until the returned long-running operation is complete
Operation<Cluster, ClusterOperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Cluster 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<Cluster, ClusterOperationMetadata> retrievedResponse = clusterControllerClient.PollOnceCreateCluster(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Cluster retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateClusterAsync</summary>
public async Task CreateClusterRequestObjectAsync()
{
// Snippet: CreateClusterAsync(CreateClusterRequest, CallSettings)
// Additional: CreateClusterAsync(CreateClusterRequest, CancellationToken)
// Create client
ClusterControllerClient clusterControllerClient = await ClusterControllerClient.CreateAsync();
// Initialize request argument(s)
CreateClusterRequest request = new CreateClusterRequest
{
ProjectId = "",
Cluster = new Cluster(),
Region = "",
RequestId = "",
ActionOnFailedPrimaryWorkers = FailureAction.Unspecified,
};
// Make the request
Operation<Cluster, ClusterOperationMetadata> response = await clusterControllerClient.CreateClusterAsync(request);
// Poll until the returned long-running operation is complete
Operation<Cluster, ClusterOperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Cluster 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<Cluster, ClusterOperationMetadata> retrievedResponse = await clusterControllerClient.PollOnceCreateClusterAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Cluster retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateCluster</summary>
public void CreateCluster()
{
// Snippet: CreateCluster(string, string, Cluster, CallSettings)
// Create client
ClusterControllerClient clusterControllerClient = ClusterControllerClient.Create();
// Initialize request argument(s)
string projectId = "";
string region = "";
Cluster cluster = new Cluster();
// Make the request
Operation<Cluster, ClusterOperationMetadata> response = clusterControllerClient.CreateCluster(projectId, region, cluster);
// Poll until the returned long-running operation is complete
Operation<Cluster, ClusterOperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Cluster 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<Cluster, ClusterOperationMetadata> retrievedResponse = clusterControllerClient.PollOnceCreateCluster(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Cluster retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateClusterAsync</summary>
public async Task CreateClusterAsync()
{
// Snippet: CreateClusterAsync(string, string, Cluster, CallSettings)
// Additional: CreateClusterAsync(string, string, Cluster, CancellationToken)
// Create client
ClusterControllerClient clusterControllerClient = await ClusterControllerClient.CreateAsync();
// Initialize request argument(s)
string projectId = "";
string region = "";
Cluster cluster = new Cluster();
// Make the request
Operation<Cluster, ClusterOperationMetadata> response = await clusterControllerClient.CreateClusterAsync(projectId, region, cluster);
// Poll until the returned long-running operation is complete
Operation<Cluster, ClusterOperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Cluster 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<Cluster, ClusterOperationMetadata> retrievedResponse = await clusterControllerClient.PollOnceCreateClusterAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Cluster retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateCluster</summary>
public void UpdateClusterRequestObject()
{
// Snippet: UpdateCluster(UpdateClusterRequest, CallSettings)
// Create client
ClusterControllerClient clusterControllerClient = ClusterControllerClient.Create();
// Initialize request argument(s)
UpdateClusterRequest request = new UpdateClusterRequest
{
ProjectId = "",
ClusterName = "",
Cluster = new Cluster(),
UpdateMask = new FieldMask(),
Region = "",
GracefulDecommissionTimeout = new Duration(),
RequestId = "",
};
// Make the request
Operation<Cluster, ClusterOperationMetadata> response = clusterControllerClient.UpdateCluster(request);
// Poll until the returned long-running operation is complete
Operation<Cluster, ClusterOperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Cluster 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<Cluster, ClusterOperationMetadata> retrievedResponse = clusterControllerClient.PollOnceUpdateCluster(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Cluster retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateClusterAsync</summary>
public async Task UpdateClusterRequestObjectAsync()
{
// Snippet: UpdateClusterAsync(UpdateClusterRequest, CallSettings)
// Additional: UpdateClusterAsync(UpdateClusterRequest, CancellationToken)
// Create client
ClusterControllerClient clusterControllerClient = await ClusterControllerClient.CreateAsync();
// Initialize request argument(s)
UpdateClusterRequest request = new UpdateClusterRequest
{
ProjectId = "",
ClusterName = "",
Cluster = new Cluster(),
UpdateMask = new FieldMask(),
Region = "",
GracefulDecommissionTimeout = new Duration(),
RequestId = "",
};
// Make the request
Operation<Cluster, ClusterOperationMetadata> response = await clusterControllerClient.UpdateClusterAsync(request);
// Poll until the returned long-running operation is complete
Operation<Cluster, ClusterOperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Cluster 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<Cluster, ClusterOperationMetadata> retrievedResponse = await clusterControllerClient.PollOnceUpdateClusterAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Cluster retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateCluster</summary>
public void UpdateCluster()
{
// Snippet: UpdateCluster(string, string, string, Cluster, FieldMask, CallSettings)
// Create client
ClusterControllerClient clusterControllerClient = ClusterControllerClient.Create();
// Initialize request argument(s)
string projectId = "";
string region = "";
string clusterName = "";
Cluster cluster = new Cluster();
FieldMask updateMask = new FieldMask();
// Make the request
Operation<Cluster, ClusterOperationMetadata> response = clusterControllerClient.UpdateCluster(projectId, region, clusterName, cluster, updateMask);
// Poll until the returned long-running operation is complete
Operation<Cluster, ClusterOperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Cluster 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<Cluster, ClusterOperationMetadata> retrievedResponse = clusterControllerClient.PollOnceUpdateCluster(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Cluster retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateClusterAsync</summary>
public async Task UpdateClusterAsync()
{
// Snippet: UpdateClusterAsync(string, string, string, Cluster, FieldMask, CallSettings)
// Additional: UpdateClusterAsync(string, string, string, Cluster, FieldMask, CancellationToken)
// Create client
ClusterControllerClient clusterControllerClient = await ClusterControllerClient.CreateAsync();
// Initialize request argument(s)
string projectId = "";
string region = "";
string clusterName = "";
Cluster cluster = new Cluster();
FieldMask updateMask = new FieldMask();
// Make the request
Operation<Cluster, ClusterOperationMetadata> response = await clusterControllerClient.UpdateClusterAsync(projectId, region, clusterName, cluster, updateMask);
// Poll until the returned long-running operation is complete
Operation<Cluster, ClusterOperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Cluster 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<Cluster, ClusterOperationMetadata> retrievedResponse = await clusterControllerClient.PollOnceUpdateClusterAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Cluster retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for StopCluster</summary>
public void StopClusterRequestObject()
{
// Snippet: StopCluster(StopClusterRequest, CallSettings)
// Create client
ClusterControllerClient clusterControllerClient = ClusterControllerClient.Create();
// Initialize request argument(s)
StopClusterRequest request = new StopClusterRequest
{
ProjectId = "",
Region = "",
ClusterName = "",
ClusterUuid = "",
RequestId = "",
};
// Make the request
Operation<Cluster, ClusterOperationMetadata> response = clusterControllerClient.StopCluster(request);
// Poll until the returned long-running operation is complete
Operation<Cluster, ClusterOperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Cluster 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<Cluster, ClusterOperationMetadata> retrievedResponse = clusterControllerClient.PollOnceStopCluster(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Cluster retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for StopClusterAsync</summary>
public async Task StopClusterRequestObjectAsync()
{
// Snippet: StopClusterAsync(StopClusterRequest, CallSettings)
// Additional: StopClusterAsync(StopClusterRequest, CancellationToken)
// Create client
ClusterControllerClient clusterControllerClient = await ClusterControllerClient.CreateAsync();
// Initialize request argument(s)
StopClusterRequest request = new StopClusterRequest
{
ProjectId = "",
Region = "",
ClusterName = "",
ClusterUuid = "",
RequestId = "",
};
// Make the request
Operation<Cluster, ClusterOperationMetadata> response = await clusterControllerClient.StopClusterAsync(request);
// Poll until the returned long-running operation is complete
Operation<Cluster, ClusterOperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Cluster 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<Cluster, ClusterOperationMetadata> retrievedResponse = await clusterControllerClient.PollOnceStopClusterAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Cluster retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for StartCluster</summary>
public void StartClusterRequestObject()
{
// Snippet: StartCluster(StartClusterRequest, CallSettings)
// Create client
ClusterControllerClient clusterControllerClient = ClusterControllerClient.Create();
// Initialize request argument(s)
StartClusterRequest request = new StartClusterRequest
{
ProjectId = "",
Region = "",
ClusterName = "",
ClusterUuid = "",
RequestId = "",
};
// Make the request
Operation<Cluster, ClusterOperationMetadata> response = clusterControllerClient.StartCluster(request);
// Poll until the returned long-running operation is complete
Operation<Cluster, ClusterOperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Cluster 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<Cluster, ClusterOperationMetadata> retrievedResponse = clusterControllerClient.PollOnceStartCluster(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Cluster retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for StartClusterAsync</summary>
public async Task StartClusterRequestObjectAsync()
{
// Snippet: StartClusterAsync(StartClusterRequest, CallSettings)
// Additional: StartClusterAsync(StartClusterRequest, CancellationToken)
// Create client
ClusterControllerClient clusterControllerClient = await ClusterControllerClient.CreateAsync();
// Initialize request argument(s)
StartClusterRequest request = new StartClusterRequest
{
ProjectId = "",
Region = "",
ClusterName = "",
ClusterUuid = "",
RequestId = "",
};
// Make the request
Operation<Cluster, ClusterOperationMetadata> response = await clusterControllerClient.StartClusterAsync(request);
// Poll until the returned long-running operation is complete
Operation<Cluster, ClusterOperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Cluster 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<Cluster, ClusterOperationMetadata> retrievedResponse = await clusterControllerClient.PollOnceStartClusterAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Cluster retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteCluster</summary>
public void DeleteClusterRequestObject()
{
// Snippet: DeleteCluster(DeleteClusterRequest, CallSettings)
// Create client
ClusterControllerClient clusterControllerClient = ClusterControllerClient.Create();
// Initialize request argument(s)
DeleteClusterRequest request = new DeleteClusterRequest
{
ProjectId = "",
ClusterName = "",
Region = "",
ClusterUuid = "",
RequestId = "",
};
// Make the request
Operation<Empty, ClusterOperationMetadata> response = clusterControllerClient.DeleteCluster(request);
// Poll until the returned long-running operation is complete
Operation<Empty, ClusterOperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Empty 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<Empty, ClusterOperationMetadata> retrievedResponse = clusterControllerClient.PollOnceDeleteCluster(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteClusterAsync</summary>
public async Task DeleteClusterRequestObjectAsync()
{
// Snippet: DeleteClusterAsync(DeleteClusterRequest, CallSettings)
// Additional: DeleteClusterAsync(DeleteClusterRequest, CancellationToken)
// Create client
ClusterControllerClient clusterControllerClient = await ClusterControllerClient.CreateAsync();
// Initialize request argument(s)
DeleteClusterRequest request = new DeleteClusterRequest
{
ProjectId = "",
ClusterName = "",
Region = "",
ClusterUuid = "",
RequestId = "",
};
// Make the request
Operation<Empty, ClusterOperationMetadata> response = await clusterControllerClient.DeleteClusterAsync(request);
// Poll until the returned long-running operation is complete
Operation<Empty, ClusterOperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Empty 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<Empty, ClusterOperationMetadata> retrievedResponse = await clusterControllerClient.PollOnceDeleteClusterAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteCluster</summary>
public void DeleteCluster()
{
// Snippet: DeleteCluster(string, string, string, CallSettings)
// Create client
ClusterControllerClient clusterControllerClient = ClusterControllerClient.Create();
// Initialize request argument(s)
string projectId = "";
string region = "";
string clusterName = "";
// Make the request
Operation<Empty, ClusterOperationMetadata> response = clusterControllerClient.DeleteCluster(projectId, region, clusterName);
// Poll until the returned long-running operation is complete
Operation<Empty, ClusterOperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Empty 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<Empty, ClusterOperationMetadata> retrievedResponse = clusterControllerClient.PollOnceDeleteCluster(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteClusterAsync</summary>
public async Task DeleteClusterAsync()
{
// Snippet: DeleteClusterAsync(string, string, string, CallSettings)
// Additional: DeleteClusterAsync(string, string, string, CancellationToken)
// Create client
ClusterControllerClient clusterControllerClient = await ClusterControllerClient.CreateAsync();
// Initialize request argument(s)
string projectId = "";
string region = "";
string clusterName = "";
// Make the request
Operation<Empty, ClusterOperationMetadata> response = await clusterControllerClient.DeleteClusterAsync(projectId, region, clusterName);
// Poll until the returned long-running operation is complete
Operation<Empty, ClusterOperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Empty 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<Empty, ClusterOperationMetadata> retrievedResponse = await clusterControllerClient.PollOnceDeleteClusterAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for GetCluster</summary>
public void GetClusterRequestObject()
{
// Snippet: GetCluster(GetClusterRequest, CallSettings)
// Create client
ClusterControllerClient clusterControllerClient = ClusterControllerClient.Create();
// Initialize request argument(s)
GetClusterRequest request = new GetClusterRequest
{
ProjectId = "",
ClusterName = "",
Region = "",
};
// Make the request
Cluster response = clusterControllerClient.GetCluster(request);
// End snippet
}
/// <summary>Snippet for GetClusterAsync</summary>
public async Task GetClusterRequestObjectAsync()
{
// Snippet: GetClusterAsync(GetClusterRequest, CallSettings)
// Additional: GetClusterAsync(GetClusterRequest, CancellationToken)
// Create client
ClusterControllerClient clusterControllerClient = await ClusterControllerClient.CreateAsync();
// Initialize request argument(s)
GetClusterRequest request = new GetClusterRequest
{
ProjectId = "",
ClusterName = "",
Region = "",
};
// Make the request
Cluster response = await clusterControllerClient.GetClusterAsync(request);
// End snippet
}
/// <summary>Snippet for GetCluster</summary>
public void GetCluster()
{
// Snippet: GetCluster(string, string, string, CallSettings)
// Create client
ClusterControllerClient clusterControllerClient = ClusterControllerClient.Create();
// Initialize request argument(s)
string projectId = "";
string region = "";
string clusterName = "";
// Make the request
Cluster response = clusterControllerClient.GetCluster(projectId, region, clusterName);
// End snippet
}
/// <summary>Snippet for GetClusterAsync</summary>
public async Task GetClusterAsync()
{
// Snippet: GetClusterAsync(string, string, string, CallSettings)
// Additional: GetClusterAsync(string, string, string, CancellationToken)
// Create client
ClusterControllerClient clusterControllerClient = await ClusterControllerClient.CreateAsync();
// Initialize request argument(s)
string projectId = "";
string region = "";
string clusterName = "";
// Make the request
Cluster response = await clusterControllerClient.GetClusterAsync(projectId, region, clusterName);
// End snippet
}
/// <summary>Snippet for ListClusters</summary>
public void ListClustersRequestObject()
{
// Snippet: ListClusters(ListClustersRequest, CallSettings)
// Create client
ClusterControllerClient clusterControllerClient = ClusterControllerClient.Create();
// Initialize request argument(s)
ListClustersRequest request = new ListClustersRequest
{
ProjectId = "",
Region = "",
Filter = "",
};
// Make the request
PagedEnumerable<ListClustersResponse, Cluster> response = clusterControllerClient.ListClusters(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (Cluster 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 (ListClustersResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Cluster 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<Cluster> 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 (Cluster 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 ListClustersAsync</summary>
public async Task ListClustersRequestObjectAsync()
{
// Snippet: ListClustersAsync(ListClustersRequest, CallSettings)
// Create client
ClusterControllerClient clusterControllerClient = await ClusterControllerClient.CreateAsync();
// Initialize request argument(s)
ListClustersRequest request = new ListClustersRequest
{
ProjectId = "",
Region = "",
Filter = "",
};
// Make the request
PagedAsyncEnumerable<ListClustersResponse, Cluster> response = clusterControllerClient.ListClustersAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Cluster 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((ListClustersResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Cluster 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<Cluster> 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 (Cluster 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 ListClusters</summary>
public void ListClusters1()
{
// Snippet: ListClusters(string, string, string, int?, CallSettings)
// Create client
ClusterControllerClient clusterControllerClient = ClusterControllerClient.Create();
// Initialize request argument(s)
string projectId = "";
string region = "";
// Make the request
PagedEnumerable<ListClustersResponse, Cluster> response = clusterControllerClient.ListClusters(projectId, region);
// Iterate over all response items, lazily performing RPCs as required
foreach (Cluster 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 (ListClustersResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Cluster 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<Cluster> 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 (Cluster 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 ListClustersAsync</summary>
public async Task ListClusters1Async()
{
// Snippet: ListClustersAsync(string, string, string, int?, CallSettings)
// Create client
ClusterControllerClient clusterControllerClient = await ClusterControllerClient.CreateAsync();
// Initialize request argument(s)
string projectId = "";
string region = "";
// Make the request
PagedAsyncEnumerable<ListClustersResponse, Cluster> response = clusterControllerClient.ListClustersAsync(projectId, region);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Cluster 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((ListClustersResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Cluster 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<Cluster> 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 (Cluster 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 ListClusters</summary>
public void ListClusters2()
{
// Snippet: ListClusters(string, string, string, string, int?, CallSettings)
// Create client
ClusterControllerClient clusterControllerClient = ClusterControllerClient.Create();
// Initialize request argument(s)
string projectId = "";
string region = "";
string filter = "";
// Make the request
PagedEnumerable<ListClustersResponse, Cluster> response = clusterControllerClient.ListClusters(projectId, region, filter: filter);
// Iterate over all response items, lazily performing RPCs as required
foreach (Cluster 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 (ListClustersResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Cluster 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<Cluster> 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 (Cluster 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 ListClustersAsync</summary>
public async Task ListClusters2Async()
{
// Snippet: ListClustersAsync(string, string, string, string, int?, CallSettings)
// Create client
ClusterControllerClient clusterControllerClient = await ClusterControllerClient.CreateAsync();
// Initialize request argument(s)
string projectId = "";
string region = "";
string filter = "";
// Make the request
PagedAsyncEnumerable<ListClustersResponse, Cluster> response = clusterControllerClient.ListClustersAsync(projectId, region, filter: filter);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Cluster 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((ListClustersResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Cluster 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<Cluster> 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 (Cluster 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 DiagnoseCluster</summary>
public void DiagnoseClusterRequestObject()
{
// Snippet: DiagnoseCluster(DiagnoseClusterRequest, CallSettings)
// Create client
ClusterControllerClient clusterControllerClient = ClusterControllerClient.Create();
// Initialize request argument(s)
DiagnoseClusterRequest request = new DiagnoseClusterRequest
{
ProjectId = "",
ClusterName = "",
Region = "",
};
// Make the request
Operation<DiagnoseClusterResults, ClusterOperationMetadata> response = clusterControllerClient.DiagnoseCluster(request);
// Poll until the returned long-running operation is complete
Operation<DiagnoseClusterResults, ClusterOperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
DiagnoseClusterResults 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<DiagnoseClusterResults, ClusterOperationMetadata> retrievedResponse = clusterControllerClient.PollOnceDiagnoseCluster(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
DiagnoseClusterResults retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DiagnoseClusterAsync</summary>
public async Task DiagnoseClusterRequestObjectAsync()
{
// Snippet: DiagnoseClusterAsync(DiagnoseClusterRequest, CallSettings)
// Additional: DiagnoseClusterAsync(DiagnoseClusterRequest, CancellationToken)
// Create client
ClusterControllerClient clusterControllerClient = await ClusterControllerClient.CreateAsync();
// Initialize request argument(s)
DiagnoseClusterRequest request = new DiagnoseClusterRequest
{
ProjectId = "",
ClusterName = "",
Region = "",
};
// Make the request
Operation<DiagnoseClusterResults, ClusterOperationMetadata> response = await clusterControllerClient.DiagnoseClusterAsync(request);
// Poll until the returned long-running operation is complete
Operation<DiagnoseClusterResults, ClusterOperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
DiagnoseClusterResults 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<DiagnoseClusterResults, ClusterOperationMetadata> retrievedResponse = await clusterControllerClient.PollOnceDiagnoseClusterAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
DiagnoseClusterResults retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DiagnoseCluster</summary>
public void DiagnoseCluster()
{
// Snippet: DiagnoseCluster(string, string, string, CallSettings)
// Create client
ClusterControllerClient clusterControllerClient = ClusterControllerClient.Create();
// Initialize request argument(s)
string projectId = "";
string region = "";
string clusterName = "";
// Make the request
Operation<DiagnoseClusterResults, ClusterOperationMetadata> response = clusterControllerClient.DiagnoseCluster(projectId, region, clusterName);
// Poll until the returned long-running operation is complete
Operation<DiagnoseClusterResults, ClusterOperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
DiagnoseClusterResults 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<DiagnoseClusterResults, ClusterOperationMetadata> retrievedResponse = clusterControllerClient.PollOnceDiagnoseCluster(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
DiagnoseClusterResults retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DiagnoseClusterAsync</summary>
public async Task DiagnoseClusterAsync()
{
// Snippet: DiagnoseClusterAsync(string, string, string, CallSettings)
// Additional: DiagnoseClusterAsync(string, string, string, CancellationToken)
// Create client
ClusterControllerClient clusterControllerClient = await ClusterControllerClient.CreateAsync();
// Initialize request argument(s)
string projectId = "";
string region = "";
string clusterName = "";
// Make the request
Operation<DiagnoseClusterResults, ClusterOperationMetadata> response = await clusterControllerClient.DiagnoseClusterAsync(projectId, region, clusterName);
// Poll until the returned long-running operation is complete
Operation<DiagnoseClusterResults, ClusterOperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
DiagnoseClusterResults 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<DiagnoseClusterResults, ClusterOperationMetadata> retrievedResponse = await clusterControllerClient.PollOnceDiagnoseClusterAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
DiagnoseClusterResults retrievedResult = retrievedResponse.Result;
}
// End snippet
}
}
}
| |
/************************************************************************************
Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved.
Licensed under the Oculus VR Rift SDK License Version 3.3 (the "License");
you may not use the Oculus VR Rift SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
http://www.oculus.com/licenses/LICENSE-3.3
Unless required by applicable law or agreed to in writing, the Oculus VR SDK
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************************/
#if !UNITY_5_3_OR_NEWER
#error Oculus Utilities require Unity 5.3 or higher.
#endif
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using UnityEngine;
using VR = UnityEngine.VR;
/// <summary>
/// Configuration data for Oculus virtual reality.
/// </summary>
public class OVRManager : MonoBehaviour
{
public enum TrackingOrigin
{
EyeLevel = OVRPlugin.TrackingOrigin.EyeLevel,
FloorLevel = OVRPlugin.TrackingOrigin.FloorLevel,
}
public enum EyeTextureFormat
{
Default = OVRPlugin.EyeTextureFormat.Default,
R16G16B16A16_FP = OVRPlugin.EyeTextureFormat.R16G16B16A16_FP,
R11G11B10_FP = OVRPlugin.EyeTextureFormat.R11G11B10_FP,
}
/// <summary>
/// Gets the singleton instance.
/// </summary>
public static OVRManager instance { get; private set; }
/// <summary>
/// Gets a reference to the active display.
/// </summary>
public static OVRDisplay display { get; private set; }
/// <summary>
/// Gets a reference to the active sensor.
/// </summary>
public static OVRTracker tracker { get; private set; }
/// <summary>
/// Gets a reference to the active boundary system.
/// </summary>
public static OVRBoundary boundary { get; private set; }
private static OVRProfile _profile;
/// <summary>
/// Gets the current profile, which contains information about the user's settings and body dimensions.
/// </summary>
public static OVRProfile profile
{
get {
if (_profile == null)
_profile = new OVRProfile();
return _profile;
}
}
private bool _isPaused;
private IEnumerable<Camera> disabledCameras;
float prevTimeScale;
private bool paused
{
get { return _isPaused; }
set {
if (value == _isPaused)
return;
// Sample code to handle VR Focus
// if (value)
// {
// prevTimeScale = Time.timeScale;
// Time.timeScale = 0.01f;
// disabledCameras = GameObject.FindObjectsOfType<Camera>().Where(c => c.isActiveAndEnabled);
// foreach (var cam in disabledCameras)
// cam.enabled = false;
// }
// else
// {
// Time.timeScale = prevTimeScale;
// if (disabledCameras != null) {
// foreach (var cam in disabledCameras)
// cam.enabled = true;
// }
// disabledCameras = null;
// }
_isPaused = value;
}
}
/// <summary>
/// Occurs when an HMD attached.
/// </summary>
public static event Action HMDAcquired;
/// <summary>
/// Occurs when an HMD detached.
/// </summary>
public static event Action HMDLost;
/// <summary>
/// Occurs when an HMD is put on the user's head.
/// </summary>
public static event Action HMDMounted;
/// <summary>
/// Occurs when an HMD is taken off the user's head.
/// </summary>
public static event Action HMDUnmounted;
/// <summary>
/// Occurs when VR Focus is acquired.
/// </summary>
public static event Action VrFocusAcquired;
/// <summary>
/// Occurs when VR Focus is lost.
/// </summary>
public static event Action VrFocusLost;
/// <summary>
/// Occurs when the active Audio Out device has changed and a restart is needed.
/// </summary>
public static event Action AudioOutChanged;
/// <summary>
/// Occurs when the active Audio In device has changed and a restart is needed.
/// </summary>
public static event Action AudioInChanged;
/// <summary>
/// Occurs when the sensor gained tracking.
/// </summary>
public static event Action TrackingAcquired;
/// <summary>
/// Occurs when the sensor lost tracking.
/// </summary>
public static event Action TrackingLost;
/// <summary>
/// Occurs when Health & Safety Warning is dismissed.
/// </summary>
//Disable the warning about it being unused. It's deprecated.
#pragma warning disable 0067
[Obsolete]
public static event Action HSWDismissed;
#pragma warning restore
private static bool _isHmdPresentCached = false;
private static bool _isHmdPresent = false;
private static bool _wasHmdPresent = false;
/// <summary>
/// If true, a head-mounted display is connected and present.
/// </summary>
public static bool isHmdPresent
{
get {
if (!_isHmdPresentCached)
{
_isHmdPresentCached = true;
_isHmdPresent = OVRPlugin.hmdPresent;
}
return _isHmdPresent;
}
private set {
_isHmdPresentCached = true;
_isHmdPresent = value;
}
}
/// <summary>
/// Gets the audio output device identifier.
/// </summary>
/// <description>
/// On Windows, this is a string containing the GUID of the IMMDevice for the Windows audio endpoint to use.
/// </description>
public static string audioOutId
{
get { return OVRPlugin.audioOutId; }
}
/// <summary>
/// Gets the audio input device identifier.
/// </summary>
/// <description>
/// On Windows, this is a string containing the GUID of the IMMDevice for the Windows audio endpoint to use.
/// </description>
public static string audioInId
{
get { return OVRPlugin.audioInId; }
}
private static bool _hasVrFocusCached = false;
private static bool _hasVrFocus = false;
private static bool _hadVrFocus = false;
/// <summary>
/// If true, the app has VR Focus.
/// </summary>
public static bool hasVrFocus
{
get {
if (!_hasVrFocusCached)
{
_hasVrFocusCached = true;
_hasVrFocus = OVRPlugin.hasVrFocus;
}
return _hasVrFocus;
}
private set {
_hasVrFocusCached = true;
_hasVrFocus = value;
}
}
/// <summary>
/// If true, then the Oculus health and safety warning (HSW) is currently visible.
/// </summary>
[Obsolete]
public static bool isHSWDisplayed { get { return false; } }
/// <summary>
/// If the HSW has been visible for the necessary amount of time, this will make it disappear.
/// </summary>
[Obsolete]
public static void DismissHSWDisplay() {}
/// <summary>
/// If true, chromatic de-aberration will be applied, improving the image at the cost of texture bandwidth.
/// </summary>
public bool chromatic
{
get {
if (!isHmdPresent)
return false;
return OVRPlugin.chromatic;
}
set {
if (!isHmdPresent)
return;
OVRPlugin.chromatic = value;
}
}
/// <summary>
/// If true, both eyes will see the same image, rendered from the center eye pose, saving performance.
/// </summary>
public bool monoscopic
{
get {
if (!isHmdPresent)
return true;
return OVRPlugin.monoscopic;
}
set {
if (!isHmdPresent)
return;
OVRPlugin.monoscopic = value;
}
}
/// <summary>
/// If true, distortion rendering work is submitted a quarter-frame early to avoid pipeline stalls and increase CPU-GPU parallelism.
/// </summary>
public bool queueAhead = true;
/// <summary>
/// If true, Unity will use the optimal antialiasing level for quality/performance on the current hardware.
/// </summary>
public bool useRecommendedMSAALevel = false;
/// <summary>
/// If true, dynamic resolution will be enabled
/// </summary>
public bool enableAdaptiveResolution = false;
/// <summary>
/// Max RenderScale the app can reach under adaptive resolution mode ( enableAdaptiveResolution = ture );
/// </summary>
[RangeAttribute(0.5f, 2.0f)]
public float maxRenderScale = 1.0f;
/// <summary>
/// Min RenderScale the app can reach under adaptive resolution mode ( enableAdaptiveResolution = ture );
/// </summary>
[RangeAttribute(0.5f, 2.0f)]
public float minRenderScale = 0.7f;
/// <summary>
/// The number of expected display frames per rendered frame.
/// </summary>
public int vsyncCount
{
get {
if (!isHmdPresent)
return 1;
return OVRPlugin.vsyncCount;
}
set {
if (!isHmdPresent)
return;
OVRPlugin.vsyncCount = value;
}
}
/// <summary>
/// Gets the current battery level.
/// </summary>
/// <returns><c>battery level in the range [0.0,1.0]</c>
/// <param name="batteryLevel">Battery level.</param>
public static float batteryLevel
{
get {
if (!isHmdPresent)
return 1f;
return OVRPlugin.batteryLevel;
}
}
/// <summary>
/// Gets the current battery temperature.
/// </summary>
/// <returns><c>battery temperature in Celsius</c>
/// <param name="batteryTemperature">Battery temperature.</param>
public static float batteryTemperature
{
get {
if (!isHmdPresent)
return 0f;
return OVRPlugin.batteryTemperature;
}
}
/// <summary>
/// Gets the current battery status.
/// </summary>
/// <returns><c>battery status</c>
/// <param name="batteryStatus">Battery status.</param>
public static int batteryStatus
{
get {
if (!isHmdPresent)
return -1;
return (int)OVRPlugin.batteryStatus;
}
}
/// <summary>
/// Gets the current volume level.
/// </summary>
/// <returns><c>volume level in the range [0,1].</c>
public static float volumeLevel
{
get {
if (!isHmdPresent)
return 0f;
return OVRPlugin.systemVolume;
}
}
/// <summary>
/// Gets or sets the current CPU performance level (0-2). Lower performance levels save more power.
/// </summary>
public static int cpuLevel
{
get {
if (!isHmdPresent)
return 2;
return OVRPlugin.cpuLevel;
}
set {
if (!isHmdPresent)
return;
OVRPlugin.cpuLevel = value;
}
}
/// <summary>
/// Gets or sets the current GPU performance level (0-2). Lower performance levels save more power.
/// </summary>
public static int gpuLevel
{
get {
if (!isHmdPresent)
return 2;
return OVRPlugin.gpuLevel;
}
set {
if (!isHmdPresent)
return;
OVRPlugin.gpuLevel = value;
}
}
/// <summary>
/// If true, the CPU and GPU are currently throttled to save power and/or reduce the temperature.
/// </summary>
public static bool isPowerSavingActive
{
get {
if (!isHmdPresent)
return false;
return OVRPlugin.powerSaving;
}
}
/// <summary>
/// Gets or sets the eye texture format.
/// This feature is only for UNITY_5_6_OR_NEWER
/// </summary>
public static EyeTextureFormat eyeTextureFormat
{
get
{
return (OVRManager.EyeTextureFormat)OVRPlugin.GetDesiredEyeTextureFormat();
}
set
{
OVRPlugin.SetDesiredEyeTextureFormat((OVRPlugin.EyeTextureFormat)value);
}
}
[SerializeField]
private OVRManager.TrackingOrigin _trackingOriginType = OVRManager.TrackingOrigin.EyeLevel;
/// <summary>
/// Defines the current tracking origin type.
/// </summary>
public OVRManager.TrackingOrigin trackingOriginType
{
get {
if (!isHmdPresent)
return _trackingOriginType;
return (OVRManager.TrackingOrigin)OVRPlugin.GetTrackingOriginType();
}
set {
if (!isHmdPresent)
return;
if (OVRPlugin.SetTrackingOriginType((OVRPlugin.TrackingOrigin)value))
{
// Keep the field exposed in the Unity Editor synchronized with any changes.
_trackingOriginType = value;
}
}
}
/// <summary>
/// If true, head tracking will affect the position of each OVRCameraRig's cameras.
/// </summary>
public bool usePositionTracking = true;
/// <summary>
/// If true, the distance between the user's eyes will affect the position of each OVRCameraRig's cameras.
/// </summary>
public bool useIPDInPositionTracking = true;
/// <summary>
/// If true, each scene load will cause the head pose to reset.
/// </summary>
public bool resetTrackerOnLoad = false;
/// <summary>
/// True if the current platform supports virtual reality.
/// </summary>
public bool isSupportedPlatform { get; private set; }
private static bool _isUserPresentCached = false;
private static bool _isUserPresent = false;
private static bool _wasUserPresent = false;
/// <summary>
/// True if the user is currently wearing the display.
/// </summary>
public bool isUserPresent
{
get {
if (!_isUserPresentCached)
{
_isUserPresentCached = true;
_isUserPresent = OVRPlugin.userPresent;
}
return _isUserPresent;
}
private set {
_isUserPresentCached = true;
_isUserPresent = value;
}
}
private static bool prevAudioOutIdIsCached = false;
private static bool prevAudioInIdIsCached = false;
private static string prevAudioOutId = string.Empty;
private static string prevAudioInId = string.Empty;
private static bool wasPositionTracked = false;
#region Unity Messages
private void Awake()
{
// Only allow one instance at runtime.
if (instance != null)
{
enabled = false;
DestroyImmediate(this);
return;
}
instance = this;
Debug.Log("Unity v" + Application.unityVersion + ", " +
"Oculus Utilities v" + OVRPlugin.wrapperVersion + ", " +
"OVRPlugin v" + OVRPlugin.version + ", " +
"SDK v" + OVRPlugin.nativeSDKVersion + ".");
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
var supportedTypes = new UnityEngine.Rendering.GraphicsDeviceType[] {
UnityEngine.Rendering.GraphicsDeviceType.Direct3D11,
UnityEngine.Rendering.GraphicsDeviceType.Direct3D12,
};
if (!supportedTypes.Contains(SystemInfo.graphicsDeviceType))
Debug.LogWarning("VR rendering requires one of the following device types: (" + string.Join(", ", supportedTypes.Select(t=>t.ToString()).ToArray()) + "). Your graphics device: " + SystemInfo.graphicsDeviceType);
#endif
// Detect whether this platform is a supported platform
RuntimePlatform currPlatform = Application.platform;
isSupportedPlatform |= currPlatform == RuntimePlatform.Android;
//isSupportedPlatform |= currPlatform == RuntimePlatform.LinuxPlayer;
isSupportedPlatform |= currPlatform == RuntimePlatform.OSXEditor;
isSupportedPlatform |= currPlatform == RuntimePlatform.OSXPlayer;
isSupportedPlatform |= currPlatform == RuntimePlatform.WindowsEditor;
isSupportedPlatform |= currPlatform == RuntimePlatform.WindowsPlayer;
if (!isSupportedPlatform)
{
Debug.LogWarning("This platform is unsupported");
return;
}
#if UNITY_ANDROID && !UNITY_EDITOR
// We want to set up our touchpad messaging system
OVRTouchpad.Create();
// Turn off chromatic aberration by default to save texture bandwidth.
chromatic = false;
#endif
if (display == null)
display = new OVRDisplay();
if (tracker == null)
tracker = new OVRTracker();
if (boundary == null)
boundary = new OVRBoundary();
if (resetTrackerOnLoad)
display.RecenterPose();
// Disable the occlusion mesh by default until open issues with the preview window are resolved.
OVRPlugin.occlusionMesh = false;
}
private void Update()
{
#if !UNITY_EDITOR
paused = !OVRPlugin.hasVrFocus;
#endif
if (OVRPlugin.shouldQuit)
Application.Quit();
if (OVRPlugin.shouldRecenter)
OVRManager.display.RecenterPose();
if (trackingOriginType != _trackingOriginType)
trackingOriginType = _trackingOriginType;
tracker.isEnabled = usePositionTracking;
OVRPlugin.useIPDInPositionTracking = useIPDInPositionTracking;
// Dispatch HMD events.
isHmdPresent = OVRPlugin.hmdPresent;
if (useRecommendedMSAALevel && QualitySettings.antiAliasing != display.recommendedMSAALevel)
{
Debug.Log("The current MSAA level is " + QualitySettings.antiAliasing +
", but the recommended MSAA level is " + display.recommendedMSAALevel +
". Switching to the recommended level.");
QualitySettings.antiAliasing = display.recommendedMSAALevel;
}
if (_wasHmdPresent && !isHmdPresent)
{
try
{
if (HMDLost != null)
HMDLost();
}
catch (Exception e)
{
Debug.LogError("Caught Exception: " + e);
}
}
if (!_wasHmdPresent && isHmdPresent)
{
try
{
if (HMDAcquired != null)
HMDAcquired();
}
catch (Exception e)
{
Debug.LogError("Caught Exception: " + e);
}
}
_wasHmdPresent = isHmdPresent;
// Dispatch HMD mounted events.
isUserPresent = OVRPlugin.userPresent;
if (_wasUserPresent && !isUserPresent)
{
try
{
if (HMDUnmounted != null)
HMDUnmounted();
}
catch (Exception e)
{
Debug.LogError("Caught Exception: " + e);
}
}
if (!_wasUserPresent && isUserPresent)
{
try
{
if (HMDMounted != null)
HMDMounted();
}
catch (Exception e)
{
Debug.LogError("Caught Exception: " + e);
}
}
_wasUserPresent = isUserPresent;
// Dispatch VR Focus events.
hasVrFocus = OVRPlugin.hasVrFocus;
if (_hadVrFocus && !hasVrFocus)
{
try
{
if (VrFocusLost != null)
VrFocusLost();
}
catch (Exception e)
{
Debug.LogError("Caught Exception: " + e);
}
}
if (!_hadVrFocus && hasVrFocus)
{
try
{
if (VrFocusAcquired != null)
VrFocusAcquired();
}
catch (Exception e)
{
Debug.LogError("Caught Exception: " + e);
}
}
_hadVrFocus = hasVrFocus;
// Changing effective rendering resolution dynamically according performance
#if (UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN) && UNITY_5 && !(UNITY_5_0 || UNITY_5_1 || UNITY_5_2 || UNITY_5_3)
if (enableAdaptiveResolution)
{
if (VR.VRSettings.renderScale < maxRenderScale)
{
// Allocate renderScale to max to avoid re-allocation
VR.VRSettings.renderScale = maxRenderScale;
}
else
{
// Adjusting maxRenderScale in case app started with a larger renderScale value
maxRenderScale = Mathf.Max(maxRenderScale, VR.VRSettings.renderScale);
}
float minViewportScale = minRenderScale / VR.VRSettings.renderScale;
float recommendedViewportScale = OVRPlugin.GetEyeRecommendedResolutionScale() / VR.VRSettings.renderScale;
recommendedViewportScale = Mathf.Clamp(recommendedViewportScale, minViewportScale, 1.0f);
VR.VRSettings.renderViewportScale = recommendedViewportScale;
}
#endif
// Dispatch Audio Device events.
string audioOutId = OVRPlugin.audioOutId;
if (!prevAudioOutIdIsCached)
{
prevAudioOutId = audioOutId;
prevAudioOutIdIsCached = true;
}
else if (audioOutId != prevAudioOutId)
{
try
{
if (AudioOutChanged != null)
AudioOutChanged();
}
catch (Exception e)
{
Debug.LogError("Caught Exception: " + e);
}
prevAudioOutId = audioOutId;
}
string audioInId = OVRPlugin.audioInId;
if (!prevAudioInIdIsCached)
{
prevAudioInId = audioInId;
prevAudioInIdIsCached = true;
}
else if (audioInId != prevAudioInId)
{
try
{
if (AudioInChanged != null)
AudioInChanged();
}
catch (Exception e)
{
Debug.LogError("Caught Exception: " + e);
}
prevAudioInId = audioInId;
}
// Dispatch tracking events.
if (wasPositionTracked && !tracker.isPositionTracked)
{
try
{
if (TrackingLost != null)
TrackingLost();
}
catch (Exception e)
{
Debug.LogError("Caught Exception: " + e);
}
}
if (!wasPositionTracked && tracker.isPositionTracked)
{
try
{
if (TrackingAcquired != null)
TrackingAcquired();
}
catch (Exception e)
{
Debug.LogError("Caught Exception: " + e);
}
}
wasPositionTracked = tracker.isPositionTracked;
display.Update();
OVRInput.Update();
}
private void LateUpdate()
{
OVRHaptics.Process();
}
private void FixedUpdate()
{
OVRInput.FixedUpdate();
}
/// <summary>
/// Leaves the application/game and returns to the launcher/dashboard
/// </summary>
public void ReturnToLauncher()
{
// show the platform UI quit prompt
OVRManager.PlatformUIConfirmQuit();
}
#endregion
public static void PlatformUIConfirmQuit()
{
if (!isHmdPresent)
return;
OVRPlugin.ShowUI(OVRPlugin.PlatformUI.ConfirmQuit);
}
public static void PlatformUIGlobalMenu()
{
if (!isHmdPresent)
return;
OVRPlugin.ShowUI(OVRPlugin.PlatformUI.GlobalMenu);
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
This file is part of the fyiReporting RDL project.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
For additional information, email [email protected] or visit
the website www.fyiReporting.com.
*/
using System;
using System.Xml;
using System.Data;
using System.Collections;
namespace fyiReporting.Data
{
/// <summary>
/// LogCommand allows specifying the command for the web log.
/// </summary>
public class GedcomCommand : IDbCommand
{
GedcomConnection _lc; // connection we're running under
string _cmd; // command to execute
// parsed constituents of the command
string _Url; // url of the file
DataParameterCollection _Parameters = new DataParameterCollection();
public GedcomCommand(GedcomConnection conn)
{
_lc = conn;
}
internal string Url
{
get
{
// Check to see if "Url" or "@Url" is a parameter
IDbDataParameter dp= _Parameters["Url"] as IDbDataParameter;
if (dp == null)
dp= _Parameters["@Url"] as IDbDataParameter;
// Then check to see if the Url value is a parameter?
if (dp == null)
dp = _Parameters[_Url] as IDbDataParameter;
if (dp != null)
return dp.Value != null? dp.Value.ToString(): _Url; // don't pass null; pass existing value
return _Url; // the value must be a constant
}
set {_Url = value;}
}
#region IDbCommand Members
public void Cancel()
{
throw new NotImplementedException("Cancel not implemented");
}
public void Prepare()
{
return; // Prepare is a noop
}
public System.Data.CommandType CommandType
{
get
{
throw new NotImplementedException("CommandType not implemented");
}
set
{
throw new NotImplementedException("CommandType not implemented");
}
}
public IDataReader ExecuteReader(System.Data.CommandBehavior behavior)
{
if (!(behavior == CommandBehavior.SingleResult ||
behavior == CommandBehavior.SchemaOnly))
throw new ArgumentException("ExecuteReader supports SingleResult and SchemaOnly only.");
return new GedcomDataReader(behavior, _lc, this);
}
IDataReader System.Data.IDbCommand.ExecuteReader()
{
return ExecuteReader(System.Data.CommandBehavior.SingleResult);
}
public object ExecuteScalar()
{
throw new NotImplementedException("ExecuteScalar not implemented");
}
public int ExecuteNonQuery()
{
throw new NotImplementedException("ExecuteNonQuery not implemented");
}
public int CommandTimeout
{
get
{
return 0;
}
set
{
throw new NotImplementedException("CommandTimeout not implemented");
}
}
public IDbDataParameter CreateParameter()
{
return new GedcomDataParameter();
}
public IDbConnection Connection
{
get
{
return this._lc;
}
set
{
throw new NotImplementedException("Setting Connection not implemented");
}
}
public System.Data.UpdateRowSource UpdatedRowSource
{
get
{
throw new NotImplementedException("UpdatedRowSource not implemented");
}
set
{
throw new NotImplementedException("UpdatedRowSource not implemented");
}
}
public string CommandText
{
get
{
return this._cmd;
}
set
{
// Parse the command string for keyword value pairs separated by ';'
string[] args = value.Split(';');
string url=null;
foreach(string arg in args)
{
string[] param = arg.Trim().Split('=');
if (param == null || param.Length != 2)
continue;
string key = param[0].Trim().ToLower();
string val = param[1];
switch (key)
{
case "url":
case "file":
url = val;
break;
default:
throw new ArgumentException(string.Format("{0} is an unknown parameter key", param[0]));
}
}
// User must specify both the url and the RowsXPath
if (url == null)
throw new ArgumentException("CommandText requires a 'Url=' parameter.");
_cmd = value;
_Url = url;
}
}
public IDataParameterCollection Parameters
{
get
{
return _Parameters;
}
}
public IDbTransaction Transaction
{
get
{
throw new NotImplementedException("Transaction not implemented");
}
set
{
throw new NotImplementedException("Transaction not implemented");
}
}
#endregion
#region IDisposable Members
public void Dispose()
{
// nothing to dispose of
}
#endregion
}
}
| |
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Orleans.Runtime;
namespace Orleans
{
internal static class OrleansTaskExtentions
{
internal static readonly Task<object> CanceledTask = TaskFromCanceled<object>();
internal static readonly Task<object> CompletedTask = Task.FromResult(default(object));
/// <summary>
/// Returns a <see cref="Task{Object}"/> for the provided <see cref="Task"/>.
/// </summary>
/// <param name="task">The task.</param>
public static Task<object> ToUntypedTask(this Task task)
{
switch (task.Status)
{
case TaskStatus.RanToCompletion:
return CompletedTask;
case TaskStatus.Faulted:
return TaskFromFaulted(task);
case TaskStatus.Canceled:
return CanceledTask;
default:
return ConvertAsync(task);
}
async Task<object> ConvertAsync(Task asyncTask)
{
await asyncTask;
return null;
}
}
/// <summary>
/// Returns a <see cref="Task{Object}"/> for the provided <see cref="Task{T}"/>.
/// </summary>
/// <typeparam name="T">The underlying type of <paramref name="task"/>.</typeparam>
/// <param name="task">The task.</param>
public static Task<object> ToUntypedTask<T>(this Task<T> task)
{
if (typeof(T) == typeof(object))
return task as Task<object>;
switch (task.Status)
{
case TaskStatus.RanToCompletion:
return Task.FromResult((object)GetResult(task));
case TaskStatus.Faulted:
return TaskFromFaulted(task);
case TaskStatus.Canceled:
return CanceledTask;
default:
return ConvertAsync(task);
}
async Task<object> ConvertAsync(Task<T> asyncTask)
{
return await asyncTask;
}
}
/// <summary>
/// Returns a <see cref="Task{Object}"/> for the provided <see cref="Task{T}"/>.
/// </summary>
/// <typeparam name="T">The underlying type of <paramref name="task"/>.</typeparam>
/// <param name="task">The task.</param>
internal static Task<T> ToTypedTask<T>(this Task<object> task)
{
if (typeof(T) == typeof(object))
return task as Task<T>;
switch (task.Status)
{
case TaskStatus.RanToCompletion:
return Task.FromResult((T)GetResult(task));
case TaskStatus.Faulted:
return TaskFromFaulted<T>(task);
case TaskStatus.Canceled:
return TaskFromCanceled<T>();
default:
return ConvertAsync(task);
}
async Task<T> ConvertAsync(Task<object> asyncTask)
{
return (T)await asyncTask;
}
}
/// <summary>
/// Returns a <see cref="Task{Object}"/> for the provided <see cref="Task{Object}"/>.
/// </summary>
/// <param name="task">The task.</param>
public static Task<object> ToUntypedTask(this Task<object> task)
{
return task;
}
private static Task<object> TaskFromFaulted(Task task)
{
var completion = new TaskCompletionSource<object>();
completion.SetException(task.Exception.InnerExceptions);
return completion.Task;
}
private static Task<T> TaskFromFaulted<T>(Task task)
{
var completion = new TaskCompletionSource<T>();
completion.SetException(task.Exception.InnerExceptions);
return completion.Task;
}
private static Task<T> TaskFromCanceled<T>()
{
var completion = new TaskCompletionSource<T>();
completion.SetCanceled();
return completion.Task;
}
public static async Task LogException(this Task task, ILogger logger, ErrorCode errorCode, string message)
{
try
{
await task;
}
catch (Exception exc)
{
var ignored = task.Exception; // Observe exception
logger.Error(errorCode, message, exc);
throw;
}
}
// Executes an async function such as Exception is never thrown but rather always returned as a broken task.
public static async Task SafeExecute(Func<Task> action)
{
await action();
}
public static async Task ExecuteAndIgnoreException(Func<Task> action)
{
try
{
await action();
}
catch (Exception)
{
// dont re-throw, just eat it.
}
}
internal static String ToString(this Task t)
{
return t == null ? "null" : string.Format("[Id={0}, Status={1}]", t.Id, Enum.GetName(typeof(TaskStatus), t.Status));
}
internal static String ToString<T>(this Task<T> t)
{
return t == null ? "null" : string.Format("[Id={0}, Status={1}]", t.Id, Enum.GetName(typeof(TaskStatus), t.Status));
}
internal static void WaitWithThrow(this Task task, TimeSpan timeout)
{
if (!task.Wait(timeout))
{
throw new TimeoutException($"Task.WaitWithThrow has timed out after {timeout}.");
}
}
internal static T WaitForResultWithThrow<T>(this Task<T> task, TimeSpan timeout)
{
if (!task.Wait(timeout))
{
throw new TimeoutException($"Task<T>.WaitForResultWithThrow has timed out after {timeout}.");
}
return task.Result;
}
/// <summary>
/// This will apply a timeout delay to the task, allowing us to exit early
/// </summary>
/// <param name="taskToComplete">The task we will timeout after timeSpan</param>
/// <param name="timeout">Amount of time to wait before timing out</param>
/// <param name="exceptionMessage">Text to put into the timeout exception message</param>
/// <exception cref="TimeoutException">If we time out we will get this exception</exception>
/// <returns>The completed task</returns>
public static async Task WithTimeout(this Task taskToComplete, TimeSpan timeout, string exceptionMessage = null)
{
if (taskToComplete.IsCompleted)
{
await taskToComplete;
return;
}
var timeoutCancellationTokenSource = new CancellationTokenSource();
var completedTask = await Task.WhenAny(taskToComplete, Task.Delay(timeout, timeoutCancellationTokenSource.Token));
// We got done before the timeout, or were able to complete before this code ran, return the result
if (taskToComplete == completedTask)
{
timeoutCancellationTokenSource.Cancel();
// Await this so as to propagate the exception correctly
await taskToComplete;
return;
}
// We did not complete before the timeout, we fire and forget to ensure we observe any exceptions that may occur
taskToComplete.Ignore();
var errorMessage = exceptionMessage ?? $"WithTimeout has timed out after {timeout}";
throw new TimeoutException(errorMessage);
}
/// <summary>
/// This will apply a timeout delay to the task, allowing us to exit early
/// </summary>
/// <param name="taskToComplete">The task we will timeout after timeSpan</param>
/// <param name="timeSpan">Amount of time to wait before timing out</param>
/// <param name="exceptionMessage">Text to put into the timeout exception message</param>
/// <exception cref="TimeoutException">If we time out we will get this exception</exception>
/// <exception cref="TimeoutException">If we time out we will get this exception</exception>
/// <returns>The value of the completed task</returns>
public static async Task<T> WithTimeout<T>(this Task<T> taskToComplete, TimeSpan timeSpan, string exceptionMessage = null)
{
if (taskToComplete.IsCompleted)
{
return await taskToComplete;
}
var timeoutCancellationTokenSource = new CancellationTokenSource();
var completedTask = await Task.WhenAny(taskToComplete, Task.Delay(timeSpan, timeoutCancellationTokenSource.Token));
// We got done before the timeout, or were able to complete before this code ran, return the result
if (taskToComplete == completedTask)
{
timeoutCancellationTokenSource.Cancel();
// Await this so as to propagate the exception correctly
return await taskToComplete;
}
// We did not complete before the timeout, we fire and forget to ensure we observe any exceptions that may occur
taskToComplete.Ignore();
var errorMessage = exceptionMessage ?? $"WithTimeout has timed out after {timeSpan}";
throw new TimeoutException(errorMessage);
}
/// <summary>
/// For making an uncancellable task cancellable, by ignoring its result.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="taskToComplete">The task to wait for unless cancelled</param>
/// <param name="cancellationToken">A cancellation token for cancelling the wait</param>
/// <returns></returns>
internal static Task<T> WithCancellation<T>(this Task<T> taskToComplete, CancellationToken cancellationToken)
{
if (taskToComplete.IsCompleted || !cancellationToken.CanBeCanceled)
{
return taskToComplete;
}
else if (cancellationToken.IsCancellationRequested)
{
return TaskFromCanceled<T>();
}
else
{
return MakeCancellable(taskToComplete, cancellationToken);
}
}
private static async Task<T> MakeCancellable<T>(Task<T> task, CancellationToken cancellationToken)
{
var tcs = new TaskCompletionSource<T>();
using (cancellationToken.Register(() =>
tcs.TrySetCanceled(cancellationToken), useSynchronizationContext: false))
{
var firstToComplete = await Task.WhenAny(task, tcs.Task).ConfigureAwait(false);
if (firstToComplete != task)
{
task.Ignore();
}
return await firstToComplete.ConfigureAwait(false);
}
}
internal static Task WrapInTask(Action action)
{
try
{
action();
return Task.CompletedTask;
}
catch (Exception exc)
{
return Task.FromException<object>(exc);
}
}
internal static Task<T> ConvertTaskViaTcs<T>(Task<T> task)
{
if (task == null) return Task.FromResult(default(T));
var resolver = new TaskCompletionSource<T>();
if (task.Status == TaskStatus.RanToCompletion)
{
resolver.TrySetResult(task.Result);
}
else if (task.IsFaulted)
{
resolver.TrySetException(task.Exception.InnerExceptions);
}
else if (task.IsCanceled)
{
resolver.TrySetException(new TaskCanceledException(task));
}
else
{
if (task.Status == TaskStatus.Created) task.Start();
task.ContinueWith(t =>
{
if (t.IsFaulted)
{
resolver.TrySetException(t.Exception.InnerExceptions);
}
else if (t.IsCanceled)
{
resolver.TrySetException(new TaskCanceledException(t));
}
else
{
resolver.TrySetResult(t.GetResult());
}
});
}
return resolver.Task;
}
//The rationale for GetAwaiter().GetResult() instead of .Result
//is presented at https://github.com/aspnet/Security/issues/59.
internal static T GetResult<T>(this Task<T> task)
{
return task.GetAwaiter().GetResult();
}
internal static void GetResult(this Task task)
{
task.GetAwaiter().GetResult();
}
}
}
namespace Orleans
{
/// <summary>
/// A special void 'Done' Task that is already in the RunToCompletion state.
/// Equivalent to Task.FromResult(1).
/// </summary>
public static class TaskDone
{
/// <summary>
/// A special 'Done' Task that is already in the RunToCompletion state
/// </summary>
[Obsolete("Use Task.CompletedTask")]
public static Task Done => Task.CompletedTask;
}
}
| |
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.IO;
using System.Text;
using System.Diagnostics.CodeAnalysis;
using System.Collections.Generic;
// To simplify the process of finding the toolbox bitmap resource:
// #1 Create an internal class called "resfinder" outside of the root namespace.
// #2 Use "resfinder" in the toolbox bitmap attribute instead of the control name.
// #3 use the "<default namespace>.<resourcename>" string to locate the resource.
// See: http://www.bobpowell.net/toolboxbitmap.htm
internal class resfinder
{
}
namespace WeifenLuo.WinFormsUI.Docking
{
[SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters", MessageId = "0#")]
public delegate IDockContent DeserializeDockContent(string persistString);
[LocalizedDescription("DockPanel_Description")]
[Designer("System.Windows.Forms.Design.ControlDesigner, System.Design")]
[ToolboxBitmap(typeof(resfinder), "WeifenLuo.WinFormsUI.Docking.DockPanel.bmp")]
[DefaultProperty("DocumentStyle")]
[DefaultEvent("ActiveContentChanged")]
public partial class DockPanel : Panel
{
private readonly FocusManagerImpl m_focusManager;
private readonly DockPanelExtender m_extender;
private readonly DockPaneCollection m_panes;
private readonly FloatWindowCollection m_floatWindows;
private AutoHideWindowControl m_autoHideWindow;
private DockWindowCollection m_dockWindows;
private readonly DockContent m_dummyContent;
private readonly Control m_dummyControl;
public DockPanel()
{
ShowAutoHideContentOnHover = true;
m_focusManager = new FocusManagerImpl(this);
m_extender = new DockPanelExtender(this);
m_panes = new DockPaneCollection();
m_floatWindows = new FloatWindowCollection();
SuspendLayout();
m_autoHideWindow = Extender.AutoHideWindowFactory.CreateAutoHideWindow(this);
m_autoHideWindow.Visible = false;
m_autoHideWindow.ActiveContentChanged += m_autoHideWindow_ActiveContentChanged;
SetAutoHideWindowParent();
m_dummyControl = new DummyControl();
m_dummyControl.Bounds = new Rectangle(0, 0, 1, 1);
Controls.Add(m_dummyControl);
LoadDockWindows();
m_dummyContent = new DockContent();
ResumeLayout();
}
private Color m_BackColor;
/// <summary>
/// Determines the color with which the client rectangle will be drawn.
/// If this property is used instead of the BackColor it will not have any influence on the borders to the surrounding controls (DockPane).
/// The BackColor property changes the borders of surrounding controls (DockPane).
/// Alternatively both properties may be used (BackColor to draw and define the color of the borders and DockBackColor to define the color of the client rectangle).
/// For Backgroundimages: Set your prefered Image, then set the DockBackColor and the BackColor to the same Color (Control)
/// </summary>
[Description("Determines the color with which the client rectangle will be drawn.\r\n" +
"If this property is used instead of the BackColor it will not have any influence on the borders to the surrounding controls (DockPane).\r\n" +
"The BackColor property changes the borders of surrounding controls (DockPane).\r\n" +
"Alternatively both properties may be used (BackColor to draw and define the color of the borders and DockBackColor to define the color of the client rectangle).\r\n" +
"For Backgroundimages: Set your prefered Image, then set the DockBackColor and the BackColor to the same Color (Control).")]
public Color DockBackColor
{
get
{
return !m_BackColor.IsEmpty ? m_BackColor : base.BackColor;
}
set
{
if (m_BackColor != value)
{
m_BackColor = value;
this.Refresh();
}
}
}
private bool ShouldSerializeDockBackColor()
{
return !m_BackColor.IsEmpty;
}
private void ResetDockBackColor()
{
DockBackColor = Color.Empty;
}
private AutoHideStripBase m_autoHideStripControl = null;
internal AutoHideStripBase AutoHideStripControl
{
get
{
if (m_autoHideStripControl == null)
{
m_autoHideStripControl = AutoHideStripFactory.CreateAutoHideStrip(this);
Controls.Add(m_autoHideStripControl);
}
return m_autoHideStripControl;
}
}
internal void ResetAutoHideStripControl()
{
if (m_autoHideStripControl != null)
m_autoHideStripControl.Dispose();
m_autoHideStripControl = null;
}
private void MdiClientHandleAssigned(object sender, EventArgs e)
{
SetMdiClient();
PerformLayout();
}
private void MdiClient_Layout(object sender, LayoutEventArgs e)
{
if (DocumentStyle != DocumentStyle.DockingMdi)
return;
foreach (DockPane pane in Panes)
if (pane.DockState == DockState.Document)
pane.SetContentBounds();
InvalidateWindowRegion();
}
private bool m_disposed = false;
protected override void Dispose(bool disposing)
{
if (!m_disposed && disposing)
{
m_focusManager.Dispose();
if (m_mdiClientController != null)
{
m_mdiClientController.HandleAssigned -= new EventHandler(MdiClientHandleAssigned);
m_mdiClientController.MdiChildActivate -= new EventHandler(ParentFormMdiChildActivate);
m_mdiClientController.Layout -= new LayoutEventHandler(MdiClient_Layout);
m_mdiClientController.Dispose();
}
FloatWindows.Dispose();
Panes.Dispose();
DummyContent.Dispose();
m_disposed = true;
}
base.Dispose(disposing);
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public IDockContent ActiveAutoHideContent
{
get { return AutoHideWindow.ActiveContent; }
set { AutoHideWindow.ActiveContent = value; }
}
private bool m_allowEndUserDocking = !Win32Helper.IsRunningOnMono;
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockPanel_AllowEndUserDocking_Description")]
[DefaultValue(true)]
public bool AllowEndUserDocking
{
get
{
if (Win32Helper.IsRunningOnMono && m_allowEndUserDocking)
m_allowEndUserDocking = false;
return m_allowEndUserDocking;
}
set
{
if (Win32Helper.IsRunningOnMono && value)
throw new InvalidOperationException("AllowEndUserDocking can only be false if running on Mono");
m_allowEndUserDocking = value;
}
}
private bool m_allowEndUserNestedDocking = !Win32Helper.IsRunningOnMono;
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockPanel_AllowEndUserNestedDocking_Description")]
[DefaultValue(true)]
public bool AllowEndUserNestedDocking
{
get
{
if (Win32Helper.IsRunningOnMono && m_allowEndUserDocking)
m_allowEndUserDocking = false;
return m_allowEndUserNestedDocking;
}
set
{
if (Win32Helper.IsRunningOnMono && value)
throw new InvalidOperationException("AllowEndUserNestedDocking can only be false if running on Mono");
m_allowEndUserNestedDocking = value;
}
}
private DockContentCollection m_contents = new DockContentCollection();
[Browsable(false)]
public DockContentCollection Contents
{
get { return m_contents; }
}
internal DockContent DummyContent
{
get { return m_dummyContent; }
}
private bool m_rightToLeftLayout = false;
[DefaultValue(false)]
[LocalizedCategory("Appearance")]
[LocalizedDescription("DockPanel_RightToLeftLayout_Description")]
public bool RightToLeftLayout
{
get { return m_rightToLeftLayout; }
set
{
if (m_rightToLeftLayout == value)
return;
m_rightToLeftLayout = value;
foreach (FloatWindow floatWindow in FloatWindows)
floatWindow.RightToLeftLayout = value;
}
}
protected override void OnRightToLeftChanged(EventArgs e)
{
base.OnRightToLeftChanged(e);
foreach (FloatWindow floatWindow in FloatWindows)
{
if (floatWindow.RightToLeft != RightToLeft)
floatWindow.RightToLeft = RightToLeft;
}
}
private bool m_showDocumentIcon = false;
[DefaultValue(false)]
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockPanel_ShowDocumentIcon_Description")]
public bool ShowDocumentIcon
{
get { return m_showDocumentIcon; }
set
{
if (m_showDocumentIcon == value)
return;
m_showDocumentIcon = value;
Refresh();
}
}
private DocumentTabStripLocation m_documentTabStripLocation = DocumentTabStripLocation.Top;
[DefaultValue(DocumentTabStripLocation.Top)]
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockPanel_DocumentTabStripLocation")]
public DocumentTabStripLocation DocumentTabStripLocation
{
get { return m_documentTabStripLocation; }
set { m_documentTabStripLocation = value; }
}
[Browsable(false)]
public DockPanelExtender Extender
{
get { return m_extender; }
}
[Browsable(false)]
public DockPanelExtender.IDockPaneFactory DockPaneFactory
{
get { return Extender.DockPaneFactory; }
}
[Browsable(false)]
public DockPanelExtender.IFloatWindowFactory FloatWindowFactory
{
get { return Extender.FloatWindowFactory; }
}
[Browsable(false)]
public DockPanelExtender.IDockWindowFactory DockWindowFactory
{
get { return Extender.DockWindowFactory; }
}
internal DockPanelExtender.IDockPaneCaptionFactory DockPaneCaptionFactory
{
get { return Extender.DockPaneCaptionFactory; }
}
internal DockPanelExtender.IDockPaneStripFactory DockPaneStripFactory
{
get { return Extender.DockPaneStripFactory; }
}
internal DockPanelExtender.IAutoHideStripFactory AutoHideStripFactory
{
get { return Extender.AutoHideStripFactory; }
}
[Browsable(false)]
public DockPaneCollection Panes
{
get { return m_panes; }
}
internal Rectangle DockArea
{
get
{
return new Rectangle(DockPadding.Left, DockPadding.Top,
ClientRectangle.Width - DockPadding.Left - DockPadding.Right,
ClientRectangle.Height - DockPadding.Top - DockPadding.Bottom);
}
}
private double m_dockBottomPortion = 0.25;
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockPanel_DockBottomPortion_Description")]
[DefaultValue(0.25)]
public double DockBottomPortion
{
get { return m_dockBottomPortion; }
set
{
if (value <= 0)
throw new ArgumentOutOfRangeException("value");
if (value == m_dockBottomPortion)
return;
m_dockBottomPortion = value;
if (m_dockBottomPortion < 1 && m_dockTopPortion < 1)
{
if (m_dockTopPortion + m_dockBottomPortion > 1)
m_dockTopPortion = 1 - m_dockBottomPortion;
}
PerformLayout();
}
}
private double m_dockLeftPortion = 0.25;
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockPanel_DockLeftPortion_Description")]
[DefaultValue(0.25)]
public double DockLeftPortion
{
get { return m_dockLeftPortion; }
set
{
if (value <= 0)
throw new ArgumentOutOfRangeException("value");
if (value == m_dockLeftPortion)
return;
m_dockLeftPortion = value;
if (m_dockLeftPortion < 1 && m_dockRightPortion < 1)
{
if (m_dockLeftPortion + m_dockRightPortion > 1)
m_dockRightPortion = 1 - m_dockLeftPortion;
}
PerformLayout();
}
}
private double m_dockRightPortion = 0.25;
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockPanel_DockRightPortion_Description")]
[DefaultValue(0.25)]
public double DockRightPortion
{
get { return m_dockRightPortion; }
set
{
if (value <= 0)
throw new ArgumentOutOfRangeException("value");
if (value == m_dockRightPortion)
return;
m_dockRightPortion = value;
if (m_dockLeftPortion < 1 && m_dockRightPortion < 1)
{
if (m_dockLeftPortion + m_dockRightPortion > 1)
m_dockLeftPortion = 1 - m_dockRightPortion;
}
PerformLayout();
}
}
private double m_dockTopPortion = 0.25;
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockPanel_DockTopPortion_Description")]
[DefaultValue(0.25)]
public double DockTopPortion
{
get { return m_dockTopPortion; }
set
{
if (value <= 0)
throw new ArgumentOutOfRangeException("value");
if (value == m_dockTopPortion)
return;
m_dockTopPortion = value;
if (m_dockTopPortion < 1 && m_dockBottomPortion < 1)
{
if (m_dockTopPortion + m_dockBottomPortion > 1)
m_dockBottomPortion = 1 - m_dockTopPortion;
}
PerformLayout();
}
}
[Browsable(false)]
public DockWindowCollection DockWindows
{
get { return m_dockWindows; }
}
public void UpdateDockWindowZOrder(DockStyle dockStyle, bool fullPanelEdge)
{
if (dockStyle == DockStyle.Left)
{
if (fullPanelEdge)
DockWindows[DockState.DockLeft].SendToBack();
else
DockWindows[DockState.DockLeft].BringToFront();
}
else if (dockStyle == DockStyle.Right)
{
if (fullPanelEdge)
DockWindows[DockState.DockRight].SendToBack();
else
DockWindows[DockState.DockRight].BringToFront();
}
else if (dockStyle == DockStyle.Top)
{
if (fullPanelEdge)
DockWindows[DockState.DockTop].SendToBack();
else
DockWindows[DockState.DockTop].BringToFront();
}
else if (dockStyle == DockStyle.Bottom)
{
if (fullPanelEdge)
DockWindows[DockState.DockBottom].SendToBack();
else
DockWindows[DockState.DockBottom].BringToFront();
}
}
[Browsable(false)]
public int DocumentsCount
{
get
{
int count = 0;
foreach (IDockContent content in Documents)
count++;
return count;
}
}
public IDockContent[] DocumentsToArray()
{
int count = DocumentsCount;
IDockContent[] documents = new IDockContent[count];
int i = 0;
foreach (IDockContent content in Documents)
{
documents[i] = content;
i++;
}
return documents;
}
[Browsable(false)]
public IEnumerable<IDockContent> Documents
{
get
{
foreach (IDockContent content in Contents)
{
if (content.DockHandler.DockState == DockState.Document)
yield return content;
}
}
}
private Control DummyControl
{
get { return m_dummyControl; }
}
[Browsable(false)]
public FloatWindowCollection FloatWindows
{
get { return m_floatWindows; }
}
private Size m_defaultFloatWindowSize = new Size(300, 300);
[Category("Layout")]
[LocalizedDescription("DockPanel_DefaultFloatWindowSize_Description")]
public Size DefaultFloatWindowSize
{
get { return m_defaultFloatWindowSize; }
set { m_defaultFloatWindowSize = value; }
}
private bool ShouldSerializeDefaultFloatWindowSize()
{
return DefaultFloatWindowSize != new Size(300, 300);
}
private void ResetDefaultFloatWindowSize()
{
DefaultFloatWindowSize = new Size(300, 300);
}
private DocumentStyle m_documentStyle = DocumentStyle.DockingMdi;
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockPanel_DocumentStyle_Description")]
[DefaultValue(DocumentStyle.DockingMdi)]
public DocumentStyle DocumentStyle
{
get { return m_documentStyle; }
set
{
if (value == m_documentStyle)
return;
if (!Enum.IsDefined(typeof(DocumentStyle), value))
throw new InvalidEnumArgumentException();
if (value == DocumentStyle.SystemMdi && DockWindows[DockState.Document].VisibleNestedPanes.Count > 0)
throw new InvalidEnumArgumentException();
m_documentStyle = value;
SuspendLayout(true);
SetAutoHideWindowParent();
SetMdiClient();
InvalidateWindowRegion();
foreach (IDockContent content in Contents)
{
if (content.DockHandler.DockState == DockState.Document)
content.DockHandler.SetPaneAndVisible(content.DockHandler.Pane);
}
PerformMdiClientLayout();
ResumeLayout(true, true);
}
}
private bool _supprtDeeplyNestedContent = false;
[LocalizedCategory("Category_Performance")]
[LocalizedDescription("DockPanel_SupportDeeplyNestedContent_Description")]
[DefaultValue(false)]
public bool SupportDeeplyNestedContent
{
get { return _supprtDeeplyNestedContent; }
set { _supprtDeeplyNestedContent = value; }
}
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockPanel_ShowAutoHideContentOnHover_Description")]
[DefaultValue(true)]
public bool ShowAutoHideContentOnHover { get; set; }
public int GetDockWindowSize(DockState dockState)
{
if (dockState == DockState.DockLeft || dockState == DockState.DockRight)
{
int width = ClientRectangle.Width - DockPadding.Left - DockPadding.Right;
int dockLeftSize = m_dockLeftPortion >= 1 ? (int)m_dockLeftPortion : (int)(width * m_dockLeftPortion);
int dockRightSize = m_dockRightPortion >= 1 ? (int)m_dockRightPortion : (int)(width * m_dockRightPortion);
if (dockLeftSize < MeasurePane.MinSize)
dockLeftSize = MeasurePane.MinSize;
if (dockRightSize < MeasurePane.MinSize)
dockRightSize = MeasurePane.MinSize;
if (dockLeftSize + dockRightSize > width - MeasurePane.MinSize)
{
int adjust = (dockLeftSize + dockRightSize) - (width - MeasurePane.MinSize);
dockLeftSize -= adjust / 2;
dockRightSize -= adjust / 2;
}
return dockState == DockState.DockLeft ? dockLeftSize : dockRightSize;
}
else if (dockState == DockState.DockTop || dockState == DockState.DockBottom)
{
int height = ClientRectangle.Height - DockPadding.Top - DockPadding.Bottom;
int dockTopSize = m_dockTopPortion >= 1 ? (int)m_dockTopPortion : (int)(height * m_dockTopPortion);
int dockBottomSize = m_dockBottomPortion >= 1 ? (int)m_dockBottomPortion : (int)(height * m_dockBottomPortion);
if (dockTopSize < MeasurePane.MinSize)
dockTopSize = MeasurePane.MinSize;
if (dockBottomSize < MeasurePane.MinSize)
dockBottomSize = MeasurePane.MinSize;
if (dockTopSize + dockBottomSize > height - MeasurePane.MinSize)
{
int adjust = (dockTopSize + dockBottomSize) - (height - MeasurePane.MinSize);
dockTopSize -= adjust / 2;
dockBottomSize -= adjust / 2;
}
return dockState == DockState.DockTop ? dockTopSize : dockBottomSize;
}
else
return 0;
}
protected override void OnLayout(LayoutEventArgs levent)
{
SuspendLayout(true);
AutoHideStripControl.Bounds = ClientRectangle;
CalculateDockPadding();
DockWindows[DockState.DockLeft].Width = GetDockWindowSize(DockState.DockLeft);
DockWindows[DockState.DockRight].Width = GetDockWindowSize(DockState.DockRight);
DockWindows[DockState.DockTop].Height = GetDockWindowSize(DockState.DockTop);
DockWindows[DockState.DockBottom].Height = GetDockWindowSize(DockState.DockBottom);
AutoHideWindow.Bounds = GetAutoHideWindowBounds(AutoHideWindowRectangle);
DockWindows[DockState.Document].BringToFront();
AutoHideWindow.BringToFront();
base.OnLayout(levent);
if (DocumentStyle == DocumentStyle.SystemMdi && MdiClientExists)
{
SetMdiClientBounds(SystemMdiClientBounds);
InvalidateWindowRegion();
}
else if (DocumentStyle == DocumentStyle.DockingMdi)
InvalidateWindowRegion();
ResumeLayout(true, true);
}
internal Rectangle GetTabStripRectangle(DockState dockState)
{
return AutoHideStripControl.GetTabStripRectangle(dockState);
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
if (DockBackColor == BackColor) return;
Graphics g = e.Graphics;
SolidBrush bgBrush = new SolidBrush(DockBackColor);
g.FillRectangle(bgBrush, ClientRectangle);
}
internal void AddContent(IDockContent content)
{
if (content == null)
throw(new ArgumentNullException());
if (!Contents.Contains(content))
{
Contents.Add(content);
OnContentAdded(new DockContentEventArgs(content));
}
}
internal void AddPane(DockPane pane)
{
if (Panes.Contains(pane))
return;
Panes.Add(pane);
}
internal void AddFloatWindow(FloatWindow floatWindow)
{
if (FloatWindows.Contains(floatWindow))
return;
FloatWindows.Add(floatWindow);
}
private void CalculateDockPadding()
{
DockPadding.All = 0;
int height = AutoHideStripControl.MeasureHeight();
if (AutoHideStripControl.GetNumberOfPanes(DockState.DockLeftAutoHide) > 0)
DockPadding.Left = height;
if (AutoHideStripControl.GetNumberOfPanes(DockState.DockRightAutoHide) > 0)
DockPadding.Right = height;
if (AutoHideStripControl.GetNumberOfPanes(DockState.DockTopAutoHide) > 0)
DockPadding.Top = height;
if (AutoHideStripControl.GetNumberOfPanes(DockState.DockBottomAutoHide) > 0)
DockPadding.Bottom = height;
}
internal void RemoveContent(IDockContent content)
{
if (content == null)
throw(new ArgumentNullException());
if (Contents.Contains(content))
{
Contents.Remove(content);
OnContentRemoved(new DockContentEventArgs(content));
}
}
internal void RemovePane(DockPane pane)
{
if (!Panes.Contains(pane))
return;
Panes.Remove(pane);
}
internal void RemoveFloatWindow(FloatWindow floatWindow)
{
if (!FloatWindows.Contains(floatWindow))
return;
FloatWindows.Remove(floatWindow);
if (FloatWindows.Count != 0)
return;
if (ParentForm == null)
return;
ParentForm.Focus();
}
public void SetPaneIndex(DockPane pane, int index)
{
int oldIndex = Panes.IndexOf(pane);
if (oldIndex == -1)
throw(new ArgumentException(Strings.DockPanel_SetPaneIndex_InvalidPane));
if (index < 0 || index > Panes.Count - 1)
if (index != -1)
throw(new ArgumentOutOfRangeException(Strings.DockPanel_SetPaneIndex_InvalidIndex));
if (oldIndex == index)
return;
if (oldIndex == Panes.Count - 1 && index == -1)
return;
Panes.Remove(pane);
if (index == -1)
Panes.Add(pane);
else if (oldIndex < index)
Panes.AddAt(pane, index - 1);
else
Panes.AddAt(pane, index);
}
public void SuspendLayout(bool allWindows)
{
FocusManager.SuspendFocusTracking();
SuspendLayout();
if (allWindows)
SuspendMdiClientLayout();
}
public void ResumeLayout(bool performLayout, bool allWindows)
{
FocusManager.ResumeFocusTracking();
ResumeLayout(performLayout);
if (allWindows)
ResumeMdiClientLayout(performLayout);
}
internal Form ParentForm
{
get
{
if (!IsParentFormValid())
throw new InvalidOperationException(Strings.DockPanel_ParentForm_Invalid);
return GetMdiClientController().ParentForm;
}
}
private bool IsParentFormValid()
{
if (DocumentStyle == DocumentStyle.DockingSdi || DocumentStyle == DocumentStyle.DockingWindow)
return true;
if (!MdiClientExists)
GetMdiClientController().RenewMdiClient();
return (MdiClientExists);
}
protected override void OnParentChanged(EventArgs e)
{
SetAutoHideWindowParent();
GetMdiClientController().ParentForm = (this.Parent as Form);
base.OnParentChanged (e);
}
private void SetAutoHideWindowParent()
{
Control parent;
if (DocumentStyle == DocumentStyle.DockingMdi ||
DocumentStyle == DocumentStyle.SystemMdi)
parent = this.Parent;
else
parent = this;
if (AutoHideWindow.Parent != parent)
{
AutoHideWindow.Parent = parent;
AutoHideWindow.BringToFront();
}
}
protected override void OnVisibleChanged(EventArgs e)
{
base.OnVisibleChanged (e);
if (Visible)
SetMdiClient();
}
private Rectangle SystemMdiClientBounds
{
get
{
if (!IsParentFormValid() || !Visible)
return Rectangle.Empty;
Rectangle rect = ParentForm.RectangleToClient(RectangleToScreen(DocumentWindowBounds));
return rect;
}
}
internal Rectangle DocumentWindowBounds
{
get
{
Rectangle rectDocumentBounds = DisplayRectangle;
if (DockWindows[DockState.DockLeft].Visible)
{
rectDocumentBounds.X += DockWindows[DockState.DockLeft].Width;
rectDocumentBounds.Width -= DockWindows[DockState.DockLeft].Width;
}
if (DockWindows[DockState.DockRight].Visible)
rectDocumentBounds.Width -= DockWindows[DockState.DockRight].Width;
if (DockWindows[DockState.DockTop].Visible)
{
rectDocumentBounds.Y += DockWindows[DockState.DockTop].Height;
rectDocumentBounds.Height -= DockWindows[DockState.DockTop].Height;
}
if (DockWindows[DockState.DockBottom].Visible)
rectDocumentBounds.Height -= DockWindows[DockState.DockBottom].Height;
return rectDocumentBounds;
}
}
private PaintEventHandler m_dummyControlPaintEventHandler = null;
private void InvalidateWindowRegion()
{
if (DesignMode)
return;
if (m_dummyControlPaintEventHandler == null)
m_dummyControlPaintEventHandler = new PaintEventHandler(DummyControl_Paint);
DummyControl.Paint += m_dummyControlPaintEventHandler;
DummyControl.Invalidate();
}
void DummyControl_Paint(object sender, PaintEventArgs e)
{
DummyControl.Paint -= m_dummyControlPaintEventHandler;
UpdateWindowRegion();
}
private void UpdateWindowRegion()
{
if (this.DocumentStyle == DocumentStyle.DockingMdi)
UpdateWindowRegion_ClipContent();
else if (this.DocumentStyle == DocumentStyle.DockingSdi ||
this.DocumentStyle == DocumentStyle.DockingWindow)
UpdateWindowRegion_FullDocumentArea();
else if (this.DocumentStyle == DocumentStyle.SystemMdi)
UpdateWindowRegion_EmptyDocumentArea();
}
private void UpdateWindowRegion_FullDocumentArea()
{
SetRegion(null);
}
private void UpdateWindowRegion_EmptyDocumentArea()
{
Rectangle rect = DocumentWindowBounds;
SetRegion(new Rectangle[] { rect });
}
private void UpdateWindowRegion_ClipContent()
{
int count = 0;
foreach (DockPane pane in this.Panes)
{
if (!pane.Visible || pane.DockState != DockState.Document)
continue;
count ++;
}
if (count == 0)
{
SetRegion(null);
return;
}
Rectangle[] rects = new Rectangle[count];
int i = 0;
foreach (DockPane pane in this.Panes)
{
if (!pane.Visible || pane.DockState != DockState.Document)
continue;
rects[i] = RectangleToClient(pane.RectangleToScreen(pane.ContentRectangle));
i++;
}
SetRegion(rects);
}
private Rectangle[] m_clipRects = null;
private void SetRegion(Rectangle[] clipRects)
{
if (!IsClipRectsChanged(clipRects))
return;
m_clipRects = clipRects;
if (m_clipRects == null || m_clipRects.GetLength(0) == 0)
Region = null;
else
{
Region region = new Region(new Rectangle(0, 0, this.Width, this.Height));
foreach (Rectangle rect in m_clipRects)
region.Exclude(rect);
if (Region != null)
{
Region.Dispose();
}
Region = region;
}
}
private bool IsClipRectsChanged(Rectangle[] clipRects)
{
if (clipRects == null && m_clipRects == null)
return false;
else if ((clipRects == null) != (m_clipRects == null))
return true;
foreach (Rectangle rect in clipRects)
{
bool matched = false;
foreach (Rectangle rect2 in m_clipRects)
{
if (rect == rect2)
{
matched = true;
break;
}
}
if (!matched)
return true;
}
foreach (Rectangle rect2 in m_clipRects)
{
bool matched = false;
foreach (Rectangle rect in clipRects)
{
if (rect == rect2)
{
matched = true;
break;
}
}
if (!matched)
return true;
}
return false;
}
private static readonly object ActiveAutoHideContentChangedEvent = new object();
[LocalizedCategory("Category_DockingNotification")]
[LocalizedDescription("DockPanel_ActiveAutoHideContentChanged_Description")]
public event EventHandler ActiveAutoHideContentChanged
{
add { Events.AddHandler(ActiveAutoHideContentChangedEvent, value); }
remove { Events.RemoveHandler(ActiveAutoHideContentChangedEvent, value); }
}
protected virtual void OnActiveAutoHideContentChanged(EventArgs e)
{
EventHandler handler = (EventHandler)Events[ActiveAutoHideContentChangedEvent];
if (handler != null)
handler(this, e);
}
private void m_autoHideWindow_ActiveContentChanged(object sender, EventArgs e)
{
OnActiveAutoHideContentChanged(e);
}
private static readonly object ContentAddedEvent = new object();
[LocalizedCategory("Category_DockingNotification")]
[LocalizedDescription("DockPanel_ContentAdded_Description")]
public event EventHandler<DockContentEventArgs> ContentAdded
{
add { Events.AddHandler(ContentAddedEvent, value); }
remove { Events.RemoveHandler(ContentAddedEvent, value); }
}
protected virtual void OnContentAdded(DockContentEventArgs e)
{
EventHandler<DockContentEventArgs> handler = (EventHandler<DockContentEventArgs>)Events[ContentAddedEvent];
if (handler != null)
handler(this, e);
}
private static readonly object ContentRemovedEvent = new object();
[LocalizedCategory("Category_DockingNotification")]
[LocalizedDescription("DockPanel_ContentRemoved_Description")]
public event EventHandler<DockContentEventArgs> ContentRemoved
{
add { Events.AddHandler(ContentRemovedEvent, value); }
remove { Events.RemoveHandler(ContentRemovedEvent, value); }
}
protected virtual void OnContentRemoved(DockContentEventArgs e)
{
EventHandler<DockContentEventArgs> handler = (EventHandler<DockContentEventArgs>)Events[ContentRemovedEvent];
if (handler != null)
handler(this, e);
}
internal void ReloadDockWindows()
{
var old = m_dockWindows;
LoadDockWindows();
foreach (var dockWindow in old)
{
Controls.Remove(dockWindow);
dockWindow.Dispose();
}
}
internal void LoadDockWindows()
{
m_dockWindows = new DockWindowCollection(this);
foreach (var dockWindow in DockWindows)
{
Controls.Add(dockWindow);
}
}
public void ResetAutoHideStripWindow()
{
var old = m_autoHideWindow;
m_autoHideWindow = Extender.AutoHideWindowFactory.CreateAutoHideWindow(this);
m_autoHideWindow.Visible = false;
SetAutoHideWindowParent();
old.Visible = false;
old.Parent = null;
old.Dispose();
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System.Reflection;
using System.Collections;
public class UFTAtlasMigrateWindow : EditorWindow {
public UFTAtlasMetadata atlasMetadataFrom;
public UFTAtlasMetadata atlasMetadataTo;
private static string EDITORPREFS_ATLASMIGRATION_FROM="uftAtlasEditor.atlasFrom";
private static string EDITORPREFS_ATLASMIGRATION_TO="uftAtlasEditor.atlasTo";
private static string EDITORPREFS_ATLASMIGRATION_UPDATE_MATERIAL="uftAtlasEditor.updateMaterial";
private Vector2 scrollPosition;
private bool updateMaterial;
Dictionary<int,bool> checkedObjectsHash;
Dictionary<int,bool> checkedMaterialsHash;
List<UFTMaterialWitTextureProps> materials;
bool DEFAULT_CHECKED_OBJECT_VALUE=true;
bool DEFAULT_CHECKED_MATERIAL_PROPERTY_VALUE=true;
Dictionary<System.Type,List<UFTObjectOnScene>> objectList;
private static string HELP_STRING = "atlas metadatas must be different and point to the objects." +
"\nAll objects which use source metatadata will be updated" +
"\nIf this objects will has entryMetadata this links will be changed according to path";
[MenuItem ("Window/UFT Atlas Migration")]
static void CreateWindow () {
UFTAtlasMigrateWindow window=(UFTAtlasMigrateWindow) EditorWindow.GetWindow(typeof(UFTAtlasMigrateWindow));
window.initialize();
}
void initialize(){
string atlasFrom=EditorPrefs.GetString(EDITORPREFS_ATLASMIGRATION_FROM,null);
if (atlasFrom != null){
atlasMetadataFrom = (UFTAtlasMetadata) AssetDatabase.LoadAssetAtPath(atlasFrom,typeof(UFTAtlasMetadata));
if (atlasMetadataFrom !=null){
updateObjectList();
updateMaterialTextureList();
}
}
string atlasTo=EditorPrefs.GetString(EDITORPREFS_ATLASMIGRATION_TO,null);
if (atlasFrom != null)
atlasMetadataTo = (UFTAtlasMetadata) AssetDatabase.LoadAssetAtPath(atlasTo,typeof(UFTAtlasMetadata));
updateMaterial = EditorPrefs.GetBool(EDITORPREFS_ATLASMIGRATION_UPDATE_MATERIAL,false);
}
void OnWizardCreate(){
UFTAtlasUtil.migrateAtlasMatchEntriesByName(atlasMetadataFrom,atlasMetadataTo);
EditorPrefs.SetString(EDITORPREFS_ATLASMIGRATION_TO,AssetDatabase.GetAssetPath(atlasMetadataTo));
Debug.Log("done");
}
void OnGUI(){
EditorGUILayout.LabelField(HELP_STRING,GUI.skin.GetStyle( "Box" ) );
UFTAtlasMetadata newMeta=(UFTAtlasMetadata) EditorGUILayout.ObjectField("source atlas",atlasMetadataFrom,typeof(UFTAtlasMetadata),false);
if (newMeta != atlasMetadataFrom ){
atlasMetadataFrom= newMeta;
EditorPrefs.SetString(EDITORPREFS_ATLASMIGRATION_FROM,AssetDatabase.GetAssetPath(atlasMetadataFrom));
updateMaterialTextureList();
}
UFTAtlasMetadata newMetaTo=(UFTAtlasMetadata) EditorGUILayout.ObjectField("source atlas",atlasMetadataTo,typeof(UFTAtlasMetadata),false);
if (newMetaTo != atlasMetadataTo ){
atlasMetadataTo= newMetaTo;
EditorPrefs.SetString(EDITORPREFS_ATLASMIGRATION_TO,AssetDatabase.GetAssetPath(atlasMetadataTo));
if (isAllMetadataObjectsValid ()){
updateObjectList();
}
}
if (isAllMetadataObjectsValid()){
displayUpdateLinksToTextureMaterial();
displayObjectListIfExist();
if (GUILayout.Button("migrate!"))
migrate();
}
}
bool isAllMetadataObjectsValid ()
{
return atlasMetadataFrom!=null && atlasMetadataTo !=null && atlasMetadataFrom != atlasMetadataTo;
}
void updateMaterialTextureList ()
{
materials=UFTMaterialUtil.getMaterialListByTexture(atlasMetadataFrom.texture);
checkedMaterialsHash = new Dictionary<int, bool>();
}
void displayUpdateLinksToTextureMaterial ()
{
bool newUpdMaterialValue= EditorGUILayout.Toggle("update texture materials",updateMaterial);
if (newUpdMaterialValue != updateMaterial){
updateMaterial=newUpdMaterialValue;
EditorPrefs.SetBool (EDITORPREFS_ATLASMIGRATION_UPDATE_MATERIAL,updateMaterial);
}
if (updateMaterial && materials!=null ){
if (materials.Count == 0){
EditorGUILayout.LabelField("non of material use " + atlasMetadataTo.name + " atlas texture");
} else {
EditorGUILayout.LabelField("Materials ["+materials.Count+"] :");
foreach(UFTMaterialWitTextureProps mat in materials){
EditorGUILayout.Separator();
EditorGUILayout.BeginHorizontal();
if (GUILayout.Button(""+mat.material.name,GUILayout.Width(250),GUILayout.Width(250)))
Selection.activeObject = mat.material;
EditorGUILayout.Separator();
foreach (string propName in mat.textureProperties) {
bool newValue=EditorGUILayout.Toggle(""+propName, isPropertyMaterialChecked(mat, propName),GUILayout.Width(200));
if (newValue!=isPropertyMaterialChecked(mat,propName)){
setPropertyMaterialChecked(mat,propName,newValue);
}
}
GUILayout.FlexibleSpace();
EditorGUILayout.EndVertical();
EditorGUILayout.Separator();
}
}
}
}
void migrateMaterial()
{
foreach(UFTMaterialWitTextureProps mat in materials){
foreach (string propName in mat.textureProperties) {
if (isPropertyMaterialChecked(mat,propName)){
mat.material.SetTexture(propName,atlasMetadataTo.texture);
}
}
}
}
void setPropertyMaterialChecked(UFTMaterialWitTextureProps mat, string propName, bool val){
int hash=getCominedMaterialPropertyHash(mat,propName);
checkedMaterialsHash[hash]=val;
}
bool isPropertyMaterialChecked (UFTMaterialWitTextureProps mat, string propName)
{
int hash=getCominedMaterialPropertyHash(mat,propName);
if (checkedMaterialsHash.ContainsKey(hash)){
return checkedMaterialsHash[hash];
} else {
checkedMaterialsHash.Add(hash,DEFAULT_CHECKED_MATERIAL_PROPERTY_VALUE);
return DEFAULT_CHECKED_MATERIAL_PROPERTY_VALUE;
}
}
private int getCominedMaterialPropertyHash(UFTMaterialWitTextureProps mat, string propName){
return (mat.GetHashCode() +"]["+propName.GetHashCode()).GetHashCode();
}
void displayObjectListIfExist ()
{
if (objectList !=null && objectList.Count > 0){
scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition);
foreach (System.Type objectType in objectList.Keys) {
EditorGUILayout.LabelField(objectType.ToString()+":");
printHeader();
EditorGUILayout.Separator();
List<UFTObjectOnScene> objects=objectList[objectType];
foreach (UFTObjectOnScene obj in objects){
EditorGUILayout.BeginHorizontal();
EditorGUILayout.Separator();
if (GUILayout.Button(""+obj.component.name,GUILayout.Width(250)))
Selection.activeObject = obj.component.gameObject;
//GUILayout.FlexibleSpace();
EditorGUILayout.BeginVertical();
foreach (FieldInfo field in obj.propertyList) {
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField(field.Name,GUILayout.Width(200));
bool val= EditorGUILayout.Toggle(getNameFromFieldInfo(field, obj.component) ,isFieldChecked(field,obj.component),GUILayout.Width(200));
if (val !=isFieldChecked(field,obj.component))
setFieldChecked(field,obj.component,val);
EditorGUILayout.LabelField(field.FieldType.ToString());
GUILayout.FlexibleSpace();
EditorGUILayout.EndHorizontal();
}
EditorGUILayout.EndVertical();
EditorGUILayout.EndHorizontal();
EditorGUILayout.Separator();
}
}
EditorGUILayout.EndScrollView();
showSelectUnselectAllButtons();
}
}
void migrate ()
{
Dictionary<string,UFTAtlasEntryMetadata> targetAtlasByMetaDictionary=getAtlasByMetaDictionary(atlasMetadataTo);
foreach(KeyValuePair<System.Type,List<UFTObjectOnScene>> keyValue in objectList){
foreach(UFTObjectOnScene obj in keyValue.Value){
Component component=obj.component;
foreach(FieldInfo fieldInfo in obj.propertyList){
if (isFieldChecked(fieldInfo,component)){
setNewFieldValue(fieldInfo,component,ref targetAtlasByMetaDictionary);
}
}
if (component is UFTOnAtlasMigrateInt)
((UFTOnAtlasMigrateInt)component).onAtlasMigrate();
}
}
if (updateMaterial)
migrateMaterial();
}
void setNewFieldValue (FieldInfo fieldInfo, Component component, ref Dictionary<string, UFTAtlasEntryMetadata> targetAtlasByMetaDictionary)
{
if ( fieldInfo.FieldType == typeof(UFTAtlasMetadata)){
fieldInfo.SetValue(component,atlasMetadataTo);
//result=((UFTAtlasMetadata)fieldInfo.GetValue(go)).atlasName;
} else if ( fieldInfo.FieldType == typeof(UFTAtlasEntryMetadata)){
UFTAtlasEntryMetadata oldEntryMeta= (UFTAtlasEntryMetadata)fieldInfo.GetValue(component);
string path=oldEntryMeta.assetPath;
fieldInfo.SetValue(component,targetAtlasByMetaDictionary[path]);
} else {
throw new System.Exception("unsuported FieldInfo type exception fieldType="+fieldInfo.FieldType);
}
}
private Dictionary<string, UFTAtlasEntryMetadata> getAtlasByMetaDictionary (UFTAtlasMetadata atlasMetadataTo)
{
Dictionary<string, UFTAtlasEntryMetadata> result= new Dictionary<string, UFTAtlasEntryMetadata>();
foreach(UFTAtlasEntryMetadata entry in atlasMetadataTo.entries){
result.Add(entry.assetPath,entry);
}
return result;
}
void showSelectUnselectAllButtons ()
{
EditorGUILayout.BeginHorizontal();
if (GUILayout.Button("unselect all"))
changeValueForAllObjectsTo(false);
if (GUILayout.Button("select all"))
changeValueForAllObjectsTo(true);
EditorGUILayout.EndHorizontal();
}
void changeValueForAllObjectsTo (bool val)
{
Dictionary<int,bool> newDict=new Dictionary<int, bool>();
foreach(int key in checkedObjectsHash.Keys){
newDict.Add(key,val);
}
checkedObjectsHash=newDict;
}
void setFieldChecked(FieldInfo field, Component component, bool val){
int hash=getCombinedFieldHash(field,component);
checkedObjectsHash[hash]=val;
}
bool isFieldChecked (FieldInfo field, Component component)
{
int hash=getCombinedFieldHash(field,component);
if (checkedObjectsHash.ContainsKey (hash)){
return (bool)checkedObjectsHash[hash];
} else {
checkedObjectsHash.Add(hash,DEFAULT_CHECKED_OBJECT_VALUE);
return DEFAULT_CHECKED_OBJECT_VALUE;
}
}
private int getCombinedFieldHash(FieldInfo field, Component component){
return (field.GetHashCode() +"]["+component.GetHashCode()).GetHashCode();
}
private void printHeader(){
EditorGUILayout.BeginHorizontal();
EditorGUILayout.Separator();
EditorGUILayout.LabelField("Object Name",GUILayout.Width(250));
EditorGUILayout.LabelField("Property Name",GUILayout.Width(200));
EditorGUILayout.LabelField("Property Value",GUILayout.Width(200));
EditorGUILayout.LabelField("Property Type");
GUILayout.FlexibleSpace();
EditorGUILayout.EndHorizontal();
}
private string getNameFromFieldInfo(FieldInfo fi, Component go){
string result="";
if ( fi.FieldType == typeof(UFTAtlasMetadata)){
result=((UFTAtlasMetadata)fi.GetValue(go)).atlasName;
} else if ( fi.FieldType == typeof(UFTAtlasEntryMetadata)){
result=((UFTAtlasEntryMetadata)fi.GetValue(go)).name;
} else {
throw new System.Exception("unsuported FieldInfo type exception ="+fi.FieldType);
}
return result;
}
void updateObjectList ()
{
if (objectList == null)
objectList = new Dictionary<System.Type, List<UFTObjectOnScene>>();
objectList = UFTAtlasUtil.getObjectOnSceneByAtlas(atlasMetadataFrom,typeof(UFTAtlasEntryMetadata));
checkedObjectsHash = new Dictionary<int, bool>();
}
}
| |
namespace Rafty.UnitTests
{
using Infrastructure;
using Microsoft.Extensions.Logging;
using Moq;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Concensus.Messages;
using Concensus.Node;
using Concensus.Peers;
using Rafty.Concensus;
using Rafty.Concensus.States;
using Rafty.FiniteStateMachine;
using Rafty.Log;
using Shouldly;
using Xunit;
using static Rafty.Infrastructure.Wait;
public class LeaderTests
{
private readonly IFiniteStateMachine _fsm;
private readonly INode _node;
private readonly string _id;
private CurrentState _currentState;
private List<IPeer> _peers;
private readonly ILog _log;
private readonly IRandomDelay _delay;
private InMemorySettings _settings;
private readonly IRules _rules;
private readonly Mock<ILoggerFactory> _loggerFactory;
private Mock<ILogger> _logger;
public LeaderTests()
{
_logger = new Mock<ILogger>();
_loggerFactory = new Mock<ILoggerFactory>();
_loggerFactory.Setup(x => x.CreateLogger(It.IsAny<string>())).Returns(_logger.Object);
_rules = new Rules(_loggerFactory.Object, new NodeId(default(string)));
_settings = new InMemorySettingsBuilder().Build();
_delay = new RandomDelay();
_log = new InMemoryLog();
_peers = new List<IPeer>();
_fsm = new InMemoryStateMachine();
_id = Guid.NewGuid().ToString();
_currentState = new CurrentState(_id, 0, default(string), 0, 0, default(string));
_node = new NothingNode();
}
[Fact()]
public void ShouldSendEmptyAppendEntriesRpcOnElection()
{
_peers = new List<IPeer>();
for (var i = 0; i < 4; i++)
{
_peers.Add(new FakePeer(true));
}
_currentState = new CurrentState(_id, 0, default(string), 0, 0, default(string));
var leader = new Leader(_currentState, _fsm, s => _peers, _log, _node, _settings, _rules, _loggerFactory.Object);
bool TestPeers(List<IPeer> peers)
{
var passed = 0;
peers.ForEach(x =>
{
var peer = (FakePeer)x;
if (peer.AppendEntriesResponses.Count >= 1)
{
passed++;
}
});
return passed == peers.Count;
}
var result = WaitFor(1000).Until(() => TestPeers(_peers));
result.ShouldBeTrue();
}
[Fact]
public async Task ShouldAppendCommandToLocalLog()
{
_peers = new List<IPeer>();
for (var i = 0; i < 4; i++)
{
var peer = new RemoteControledPeer();
peer.SetAppendEntriesResponse(new AppendEntriesResponse(1, true));
_peers.Add(peer);
}
var log = new InMemoryLog();
_currentState = new CurrentState(_id, 0, default(string), 0, 0, default(string));
var leader = new Leader(_currentState, _fsm, (s) => _peers, log, _node, _settings, _rules, _loggerFactory.Object);
await leader.Accept(new FakeCommand());
log.ExposedForTesting.Count.ShouldBe(1);
bool PeersReceiveCorrectAppendEntries(List<IPeer> peers)
{
var passed = 0;
peers.ForEach(p =>
{
var rc = (RemoteControledPeer)p;
if (rc.AppendEntriesResponsesWithLogEntries == 1)
{
passed++;
}
});
return passed == peers.Count;
}
var result = WaitFor(1000).Until(() => PeersReceiveCorrectAppendEntries(_peers));
result.ShouldBeTrue();
bool FirstTest(List<PeerState> peerState)
{
var passed = 0;
peerState.ForEach(pS =>
{
if (pS.MatchIndex.IndexOfHighestKnownReplicatedLog == 1)
{
passed++;
}
if (pS.NextIndex.NextLogIndexToSendToPeer == 2)
{
passed++;
}
});
return passed == peerState.Count * 2;
}
result = WaitFor(1000).Until(() => FirstTest(leader.PeerStates));
result.ShouldBeTrue();
}
[Fact]
public async Task ShouldApplyCommandToStateMachine()
{
_peers = new List<IPeer>();
for (var i = 0; i < 4; i++)
{
var peer = new RemoteControledPeer();
peer.SetAppendEntriesResponse(new AppendEntriesResponse(1, true));
_peers.Add(peer);
}
var log = new InMemoryLog();
_currentState = new CurrentState(_id, 0, default(string), 0, 0, default(string));
var leader = new Leader(_currentState, _fsm, (s) => _peers, log, _node, _settings, _rules, _loggerFactory.Object);
var response = await leader.Accept<FakeCommand>(new FakeCommand());
log.ExposedForTesting.Count.ShouldBe(1);
var fsm = (InMemoryStateMachine)_fsm;
fsm.HandledLogEntries.ShouldBe(1);
response.ShouldBeOfType<OkResponse<FakeCommand>>();
}
[Fact]
public async Task ShouldHandleCommandIfNoPeers()
{
_peers = new List<IPeer>();
var log = new InMemoryLog();
_currentState = new CurrentState(_id, 0, default(string), 0, 0, default(string));
var leader = new Leader(_currentState, _fsm, (s) => _peers, log, _node, _settings, _rules, _loggerFactory.Object);
var response = await leader.Accept<FakeCommand>(new FakeCommand());
log.ExposedForTesting.Count.ShouldBe(1);
var fsm = (InMemoryStateMachine)_fsm;
fsm.HandledLogEntries.ShouldBe(1);
response.ShouldBeOfType<OkResponse<FakeCommand>>();
}
[Fact]
public void ShouldInitialiseNextIndex()
{
_peers = new List<IPeer>();
for (var i = 0; i < 4; i++)
{
_peers.Add(new FakePeer(true));
}
_currentState = new CurrentState(_id, 0, default(string), 0, 0, default(string));
var leader = new Leader(_currentState, _fsm, (s) => _peers, _log, _node, _settings, _rules, _loggerFactory.Object);
leader.PeerStates.ForEach(pS =>
{
pS.NextIndex.NextLogIndexToSendToPeer.ShouldBe(1);
});
}
[Fact]
public void ShouldInitialiseMatchIndex()
{
_peers = new List<IPeer>();
for (var i = 0; i < 4; i++)
{
_peers.Add(new FakePeer(true));
}
_currentState = new CurrentState(_id, 0, default(string), 0, 0, default(string));
var leader = new Leader(_currentState,_fsm, (s) => _peers, _log, _node, _settings, _rules, _loggerFactory.Object);
leader.PeerStates.ForEach(pS =>
{
pS.MatchIndex.IndexOfHighestKnownReplicatedLog.ShouldBe(0);
});
}
[Fact]
public void ShouldInitialiseNextAndMatchIndexWhenNewPeerJoins()
{
_peers = new List<IPeer>();
for (var i = 0; i < 1; i++)
{
_peers.Add(new FakePeer(Guid.NewGuid().ToString()));
}
_currentState = new CurrentState(_id, 0, default(string), 0, 0, default(string));
var leader = new Leader(_currentState,_fsm, (s) => _peers, _log, _node, _settings, _rules, _loggerFactory.Object);
leader.PeerStates.Count.ShouldBe(1);
leader.PeerStates.ForEach(pS =>
{
pS.NextIndex.NextLogIndexToSendToPeer.ShouldBe(1);
pS.MatchIndex.IndexOfHighestKnownReplicatedLog.ShouldBe(0);
});
for (var i = 0; i < 3; i++)
{
_peers.Add(new FakePeer(Guid.NewGuid().ToString()));
}
bool TestPeerStates()
{
var correctState = 0;
if(leader.PeerStates.Count != 4)
{
return false;
}
leader.PeerStates.ForEach(pS =>
{
if(leader.PeerStates.Count == 4 && pS.NextIndex.NextLogIndexToSendToPeer == 1 && pS.MatchIndex.IndexOfHighestKnownReplicatedLog == 0)
{
correctState++;
}
});
return correctState == leader.PeerStates.Count;
}
var result = WaitFor(1000).Until(() => TestPeerStates());
result.ShouldBeTrue();
}
[Fact]
public async Task ShouldSendAppendEntriesStartingAtNextIndex()
{
_peers = new List<IPeer>();
for (var i = 0; i < 4; i++)
{
_peers.Add(new FakePeer(true, true));
}
//add 3 logs
var logOne = new LogEntry(new FakeCommand("1"), typeof(string), 1);
await _log.Apply(logOne);
var logTwo = new LogEntry(new FakeCommand("2"), typeof(string), 1);
await _log.Apply(logTwo);
var logThree = new LogEntry(new FakeCommand("3"), typeof(string), 1);
await _log.Apply(logThree);
_currentState = new CurrentState(_id, 1, default(string), 2, 2, default(string));
var leader = new Leader(_currentState, _fsm, (s) => _peers, _log, _node, _settings, _rules, _loggerFactory.Object);
var logs = await _log.GetFrom(1);
logs.Count.ShouldBe(3);
}
[Fact]
public async Task ShouldUpdateMatchIndexAndNextIndexIfSuccessful()
{
_peers = new List<IPeer>();
for (var i = 0; i < 4; i++)
{
_peers.Add(new FakePeer(true, true, true));
}
//add 3 logs
_currentState = new CurrentState(_id, 1, default(string), 2, 2, default(string));
var logOne = new LogEntry(new FakeCommand("1"), typeof(string), 1);
await _log.Apply(logOne);
var logTwo = new LogEntry(new FakeCommand("2"), typeof(string), 1);
await _log.Apply(logTwo);
var logThree = new LogEntry(new FakeCommand("3"), typeof(string), 1);
await _log.Apply(logThree);
var leader = new Leader(_currentState, _fsm, (s) => _peers, _log, _node, _settings, _rules, _loggerFactory.Object);
bool FirstTest(List<PeerState> peerState)
{
var passed = 0;
peerState.ForEach(pS =>
{
if (pS.MatchIndex.IndexOfHighestKnownReplicatedLog == 3)
{
passed++;
}
if (pS.NextIndex.NextLogIndexToSendToPeer == 4)
{
passed++;
}
});
return passed == peerState.Count * 2;
}
var result = WaitFor(1000).Until(() => FirstTest(leader.PeerStates));
result.ShouldBeTrue();
}
[Fact]
public async Task ShouldDecrementNextIndexAndRetry()
{
//create peers that will initially return false when asked to append entries...
_peers = new List<IPeer>();
for (var i = 0; i < 4; i++)
{
var peer = new RemoteControledPeer();
peer.SetAppendEntriesResponse(new AppendEntriesResponse(1, false));
_peers.Add(peer);
}
_currentState = new CurrentState(_id, 1, default(string), 1, 1, default(string));
var leader = new Leader(_currentState, _fsm, (s) => _peers, _log, _node, _settings, _rules, _loggerFactory.Object);
//send first command, this wont get commited because the guys are replying false
var task = Task.Run(async () => await leader.Accept(new FakeCommand()));
bool FirstTest(List<PeerState> peerState)
{
var passed = 0;
peerState.ForEach(pS =>
{
if (pS.MatchIndex.IndexOfHighestKnownReplicatedLog == 0)
{
passed++;
}
if (pS.NextIndex.NextLogIndexToSendToPeer == 1)
{
passed++;
}
});
return passed == peerState.Count * 2;
}
var result = WaitFor(1000).Until(() => FirstTest(leader.PeerStates));
result.ShouldBeTrue();
//now the peers accept the append entries
foreach (var peer in _peers)
{
var rcPeer = (RemoteControledPeer)peer;
rcPeer.SetAppendEntriesResponse(new AppendEntriesResponse(1, true));
}
//wait on sending the command
task.Wait();
bool SecondTest(List<PeerState> peerState)
{
var passed = 0;
peerState.ForEach(pS =>
{
if (pS.MatchIndex.IndexOfHighestKnownReplicatedLog == 1)
{
passed++;
}
if (pS.NextIndex.NextLogIndexToSendToPeer == 2)
{
passed++;
}
});
return passed == peerState.Count * 2;
}
result = WaitFor(1000).Until(() => SecondTest(leader.PeerStates));
result.ShouldBeTrue();
//now the peers stop accepting append entries..
foreach (var peer in _peers)
{
var rcPeer = (RemoteControledPeer)peer;
rcPeer.SetAppendEntriesResponse(new AppendEntriesResponse(1, false));
}
//send another command, this wont get commited because the guys are replying false
task = Task.Run(async () => await leader.Accept(new FakeCommand()));
bool ThirdTest(List<PeerState> peerState)
{
var passed = 0;
peerState.ForEach(pS =>
{
if (pS.MatchIndex.IndexOfHighestKnownReplicatedLog == 1)
{
passed++;
}
if (pS.NextIndex.NextLogIndexToSendToPeer == 2)
{
passed++;
}
});
return passed == peerState.Count * 2;
}
result = WaitFor(1000).Until(() => ThirdTest(leader.PeerStates));
result.ShouldBeTrue();
//now the peers accept the append entries
foreach (var peer in _peers)
{
var rcPeer = (RemoteControledPeer)peer;
rcPeer.SetAppendEntriesResponse(new AppendEntriesResponse(1, true));
}
task.Wait();
bool FourthTest(List<PeerState> peerState)
{
var passed = 0;
peerState.ForEach(pS =>
{
if (pS.MatchIndex.IndexOfHighestKnownReplicatedLog == 2)
{
passed++;
}
if (pS.NextIndex.NextLogIndexToSendToPeer == 3)
{
passed++;
}
});
return passed == peerState.Count * 2;
}
result = WaitFor(1000).Until(() => FourthTest(leader.PeerStates));
result.ShouldBeTrue();
//send another command
await leader.Accept(new FakeCommand());
bool FirthTest(List<PeerState> peerState)
{
var passed = 0;
peerState.ForEach(pS =>
{
if (pS.MatchIndex.IndexOfHighestKnownReplicatedLog == 3)
{
passed++;
}
if (pS.NextIndex.NextLogIndexToSendToPeer == 4)
{
passed++;
}
});
return passed == peerState.Count * 2;
}
result = WaitFor(2000).Until(() => FirthTest(leader.PeerStates));
result.ShouldBeTrue();
}
[Fact]
public async Task ShouldSetCommitIndex()
{
_peers = new List<IPeer>();
for (var i = 0; i < 4; i++)
{
var peer = new RemoteControledPeer();
peer.SetAppendEntriesResponse(new AppendEntriesResponse(1, true));
_peers.Add(peer);
}
//add 3 logs
_currentState = new CurrentState(_id, 1, default(string), 0, 0, default(string));
var leader = new Leader(_currentState, _fsm, (s) => _peers, _log, _node, _settings, _rules, _loggerFactory.Object);
await leader.Accept(new FakeCommand());
await leader.Accept(new FakeCommand());
await leader.Accept(new FakeCommand());
bool PeersTest(List<PeerState> peerState)
{
var passed = 0;
peerState.ForEach(pS =>
{
if (pS.MatchIndex.IndexOfHighestKnownReplicatedLog == 3)
{
passed++;
}
if (pS.NextIndex.NextLogIndexToSendToPeer == 4)
{
passed++;
}
});
return passed == peerState.Count * 2;
}
var result = WaitFor(2000).Until(() => PeersTest(leader.PeerStates));
leader.CurrentState.CommitIndex.ShouldBe(3);
result.ShouldBeTrue();
}
[Fact]
public void ShouldBeAbleToHandleWhenLeaderHasNoLogsAndCandidatesReturnSuccess()
{
_peers = new List<IPeer>();
for (var i = 0; i < 4; i++)
{
_peers.Add(new FakePeer(true, true, true));
}
_currentState = new CurrentState(_id, 1, default(string), 0, 0, default(string));
var leader = new Leader(_currentState,_fsm, (s) => _peers, _log, _node, _settings, _rules, _loggerFactory.Object);
bool TestPeerStates(List<PeerState> peerState)
{
var passed = 0;
peerState.ForEach(pS =>
{
if (pS.MatchIndex.IndexOfHighestKnownReplicatedLog == 0)
{
passed++;
}
if (pS.NextIndex.NextLogIndexToSendToPeer == 1)
{
passed++;
}
});
return passed == peerState.Count * 2;
}
var result = WaitFor(1000).Until(() => TestPeerStates(leader.PeerStates));
result.ShouldBeTrue();
}
[Fact]
public async Task ShouldReplicateCommand()
{
_peers = new List<IPeer>();
for (var i = 0; i < 4; i++)
{
_peers.Add(new FakePeer(true, true, true));
}
_currentState = new CurrentState(_id, 1, default(string), 0, 0, default(string));
var leader = new Leader(_currentState,_fsm, (s) => _peers, _log, _node, _settings, _rules, _loggerFactory.Object);
var command = new FakeCommand();
var response = await leader.Accept(command);
response.ShouldBeOfType<OkResponse<FakeCommand>>();
bool TestPeerStates(List<PeerState> peerState)
{
var passed = 0;
peerState.ForEach(pS =>
{
if (pS.MatchIndex.IndexOfHighestKnownReplicatedLog == 1)
{
passed++;
}
if (pS.NextIndex.NextLogIndexToSendToPeer == 2)
{
passed++;
}
});
return passed == peerState.Count * 2;
}
var result = WaitFor(1000).Until(() => TestPeerStates(leader.PeerStates));
result.ShouldBeTrue();
}
[Fact]
public void ShouldBeAbleToHandleWhenLeaderHasNoLogsAndCandidatesReturnFail()
{
_peers = new List<IPeer>();
for (var i = 0; i < 4; i++)
{
_peers.Add(new FakePeer(true, true, true));
}
_currentState = new CurrentState(_id, 1, default(string), 0, 0, default(string));
var leader = new Leader(_currentState, _fsm, (s) => _peers, _log, _node, _settings, _rules, _loggerFactory.Object);
bool TestPeerStates(List<PeerState> peerState)
{
var passed = 0;
peerState.ForEach(pS =>
{
if (pS.MatchIndex.IndexOfHighestKnownReplicatedLog == 0)
{
passed++;
}
if (pS.NextIndex.NextLogIndexToSendToPeer == 1)
{
passed++;
}
});
return passed == peerState.Count * 2;
}
var result = WaitFor(1000).Until(() => TestPeerStates(leader.PeerStates));
result.ShouldBeTrue();
}
[Fact]
public async Task ShouldTimeoutAfterXSecondsIfCannotReplicateCommand()
{
_peers = new List<IPeer>();
for (var i = 0; i < 4; i++)
{
_peers.Add(new FakePeer(false, false, false));
}
_currentState = new CurrentState(_id, 1, default(string), 0, 0, default(string));
_settings = new InMemorySettingsBuilder().WithCommandTimeout(1).Build();
var leader = new Leader(_currentState,_fsm, (s) => _peers, _log, _node, _settings, _rules, _loggerFactory.Object);
var command = new FakeCommand();
var response = await leader.Accept(command);
var error = (ErrorResponse<FakeCommand>)response;
error.Error.ShouldBe("Unable to replicate command to peers due to timeout.");
bool TestPeerStates(List<PeerState> peerState)
{
var passed = 0;
peerState.ForEach(pS =>
{
if (pS.MatchIndex.IndexOfHighestKnownReplicatedLog == 0)
{
passed++;
}
if (pS.NextIndex.NextLogIndexToSendToPeer == 1)
{
passed++;
}
});
return passed == peerState.Count * 2;
}
var result = WaitFor(1000).Until(() => TestPeerStates(leader.PeerStates));
_log.Count().Result.ShouldBe(0);
result.ShouldBeTrue();
}
[Fact]
public async Task ShouldTimeoutAfterXSecondsIfCannotReplicateCommandAndRollbackIndexes()
{
_peers = new List<IPeer>();
for (var i = 0; i < 3; i++)
{
_peers.Add(new FakePeer(false, false, false));
}
_peers.Add(new FakePeer(true, true, true));
_currentState = new CurrentState(_id, 1, default(string), 0, 0, default(string));
_settings = new InMemorySettingsBuilder().WithCommandTimeout(1).Build();
var leader = new Leader(_currentState,_fsm, (s) => _peers, _log, _node, _settings, _rules, _loggerFactory.Object);
var command = new FakeCommand();
var response = await leader.Accept(command);
var error = (ErrorResponse<FakeCommand>)response;
error.Error.ShouldBe("Unable to replicate command to peers due to timeout.");
bool TestPeerStates(List<PeerState> peerState)
{
var passed = 0;
peerState.ForEach(pS =>
{
if (pS.MatchIndex.IndexOfHighestKnownReplicatedLog == 0)
{
passed++;
}
if (pS.NextIndex.NextLogIndexToSendToPeer == 1)
{
passed++;
}
});
return passed == peerState.Count * 2;
}
var result = WaitFor(1000).Until(() => TestPeerStates(leader.PeerStates));
_log.Count().Result.ShouldBe(0);
result.ShouldBeTrue();
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.ExtractMethod;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod
{
internal partial class CSharpMethodExtractor
{
private abstract partial class CSharpCodeGenerator : CodeGenerator<StatementSyntax, ExpressionSyntax, SyntaxNode>
{
private SyntaxToken _methodName;
public static Task<GeneratedCode> GenerateAsync(
InsertionPoint insertionPoint,
SelectionResult selectionResult,
AnalyzerResult analyzerResult,
CancellationToken cancellationToken)
{
var codeGenerator = Create(insertionPoint, selectionResult, analyzerResult);
return codeGenerator.GenerateAsync(cancellationToken);
}
private static CSharpCodeGenerator Create(
InsertionPoint insertionPoint,
SelectionResult selectionResult,
AnalyzerResult analyzerResult)
{
if (ExpressionCodeGenerator.IsExtractMethodOnExpression(selectionResult))
{
return new ExpressionCodeGenerator(insertionPoint, selectionResult, analyzerResult);
}
if (SingleStatementCodeGenerator.IsExtractMethodOnSingleStatement(selectionResult))
{
return new SingleStatementCodeGenerator(insertionPoint, selectionResult, analyzerResult);
}
if (MultipleStatementsCodeGenerator.IsExtractMethodOnMultipleStatements(selectionResult))
{
return new MultipleStatementsCodeGenerator(insertionPoint, selectionResult, analyzerResult);
}
return Contract.FailWithReturn<CSharpCodeGenerator>("Unknown selection");
}
protected CSharpCodeGenerator(
InsertionPoint insertionPoint,
SelectionResult selectionResult,
AnalyzerResult analyzerResult) :
base(insertionPoint, selectionResult, analyzerResult)
{
Contract.ThrowIfFalse(this.SemanticDocument == selectionResult.SemanticDocument);
var nameToken = CreateMethodName();
_methodName = nameToken.WithAdditionalAnnotations(this.MethodNameAnnotation);
}
private CSharpSelectionResult CSharpSelectionResult
{
get { return (CSharpSelectionResult)this.SelectionResult; }
}
protected override SyntaxNode GetPreviousMember(SemanticDocument document)
{
var node = this.InsertionPoint.With(document).GetContext();
return (node.Parent is GlobalStatementSyntax) ? node.Parent : node;
}
protected override OperationStatus<IMethodSymbol> GenerateMethodDefinition(CancellationToken cancellationToken)
{
var result = CreateMethodBody(cancellationToken);
var methodSymbol = CodeGenerationSymbolFactory.CreateMethodSymbol(
attributes: SpecializedCollections.EmptyList<AttributeData>(),
accessibility: Accessibility.Private,
modifiers: CreateMethodModifiers(),
returnType: this.AnalyzerResult.ReturnType,
explicitInterfaceSymbol: null,
name: _methodName.ToString(),
typeParameters: CreateMethodTypeParameters(cancellationToken),
parameters: CreateMethodParameters(),
statements: result.Data);
return result.With(
this.MethodDefinitionAnnotation.AddAnnotationToSymbol(
Formatter.Annotation.AddAnnotationToSymbol(methodSymbol)));
}
protected override async Task<SyntaxNode> GenerateBodyForCallSiteContainerAsync(CancellationToken cancellationToken)
{
var container = this.GetOutermostCallSiteContainerToProcess(cancellationToken);
var variableMapToRemove = CreateVariableDeclarationToRemoveMap(
this.AnalyzerResult.GetVariablesToMoveIntoMethodDefinition(cancellationToken), cancellationToken);
var firstStatementToRemove = GetFirstStatementOrInitializerSelectedAtCallSite();
var lastStatementToRemove = GetLastStatementOrInitializerSelectedAtCallSite();
Contract.ThrowIfFalse(firstStatementToRemove.Parent == lastStatementToRemove.Parent);
var statementsToInsert = await CreateStatementsOrInitializerToInsertAtCallSiteAsync(cancellationToken).ConfigureAwait(false);
var callSiteGenerator =
new CallSiteContainerRewriter(
container,
variableMapToRemove,
firstStatementToRemove,
lastStatementToRemove,
statementsToInsert);
return container.CopyAnnotationsTo(callSiteGenerator.Generate()).WithAdditionalAnnotations(Formatter.Annotation);
}
private async Task<IEnumerable<SyntaxNode>> CreateStatementsOrInitializerToInsertAtCallSiteAsync(CancellationToken cancellationToken)
{
var selectedNode = this.GetFirstStatementOrInitializerSelectedAtCallSite();
// field initializer, constructor initializer, expression bodied member case
if (selectedNode is ConstructorInitializerSyntax ||
selectedNode is FieldDeclarationSyntax ||
IsExpressionBodiedMember(selectedNode))
{
var statement = await GetStatementOrInitializerContainingInvocationToExtractedMethodAsync(this.CallSiteAnnotation, cancellationToken).ConfigureAwait(false);
return SpecializedCollections.SingletonEnumerable(statement);
}
// regular case
var semanticModel = this.SemanticDocument.SemanticModel;
var context = this.InsertionPoint.GetContext();
var postProcessor = new PostProcessor(semanticModel, context.SpanStart);
var statements = SpecializedCollections.EmptyEnumerable<StatementSyntax>();
statements = AddSplitOrMoveDeclarationOutStatementsToCallSite(statements, cancellationToken);
statements = postProcessor.MergeDeclarationStatements(statements);
statements = AddAssignmentStatementToCallSite(statements, cancellationToken);
statements = await AddInvocationAtCallSiteAsync(statements, cancellationToken).ConfigureAwait(false);
statements = AddReturnIfUnreachable(statements, cancellationToken);
return statements;
}
private bool IsExpressionBodiedMember(SyntaxNode node)
{
return node is MemberDeclarationSyntax && ((MemberDeclarationSyntax)node).GetExpressionBody() != null;
}
private SimpleNameSyntax CreateMethodNameForInvocation()
{
return this.AnalyzerResult.MethodTypeParametersInDeclaration.Count == 0
? (SimpleNameSyntax)SyntaxFactory.IdentifierName(_methodName)
: SyntaxFactory.GenericName(_methodName, SyntaxFactory.TypeArgumentList(CreateMethodCallTypeVariables()));
}
private SeparatedSyntaxList<TypeSyntax> CreateMethodCallTypeVariables()
{
Contract.ThrowIfTrue(this.AnalyzerResult.MethodTypeParametersInDeclaration.Count == 0);
// propagate any type variable used in extracted code
var typeVariables = new List<TypeSyntax>();
foreach (var methodTypeParameter in this.AnalyzerResult.MethodTypeParametersInDeclaration)
{
typeVariables.Add(SyntaxFactory.ParseTypeName(methodTypeParameter.Name));
}
return SyntaxFactory.SeparatedList(typeVariables);
}
protected SyntaxNode GetCallSiteContainerFromOutermostMoveInVariable(CancellationToken cancellationToken)
{
var outmostVariable = GetOutermostVariableToMoveIntoMethodDefinition(cancellationToken);
if (outmostVariable == null)
{
return null;
}
var idToken = outmostVariable.GetIdentifierTokenAtDeclaration(this.SemanticDocument);
var declStatement = idToken.GetAncestor<LocalDeclarationStatementSyntax>();
Contract.ThrowIfNull(declStatement);
Contract.ThrowIfFalse(declStatement.Parent.IsStatementContainerNode());
return declStatement.Parent;
}
private DeclarationModifiers CreateMethodModifiers()
{
var isUnsafe = this.CSharpSelectionResult.ShouldPutUnsafeModifier();
var isAsync = this.CSharpSelectionResult.ShouldPutAsyncModifier();
return new DeclarationModifiers(
isUnsafe: isUnsafe,
isAsync: isAsync,
isStatic: !this.AnalyzerResult.UseInstanceMember);
}
private static SyntaxKind GetParameterRefSyntaxKind(ParameterBehavior parameterBehavior)
{
return parameterBehavior == ParameterBehavior.Ref ?
SyntaxKind.RefKeyword :
parameterBehavior == ParameterBehavior.Out ?
SyntaxKind.OutKeyword : SyntaxKind.None;
}
private OperationStatus<List<SyntaxNode>> CreateMethodBody(CancellationToken cancellationToken)
{
var statements = GetInitialStatementsForMethodDefinitions();
statements = SplitOrMoveDeclarationIntoMethodDefinition(statements, cancellationToken);
statements = MoveDeclarationOutFromMethodDefinition(statements, cancellationToken);
statements = AppendReturnStatementIfNeeded(statements);
statements = CleanupCode(statements);
// set output so that we can use it in negative preview
var wrapped = WrapInCheckStatementIfNeeded(statements);
return CheckActiveStatements(statements).With(wrapped.ToList<SyntaxNode>());
}
private IEnumerable<StatementSyntax> WrapInCheckStatementIfNeeded(IEnumerable<StatementSyntax> statements)
{
var kind = this.CSharpSelectionResult.UnderCheckedStatementContext();
if (kind == SyntaxKind.None)
{
return statements;
}
if (statements.Skip(1).Any())
{
return SpecializedCollections.SingletonEnumerable<StatementSyntax>(SyntaxFactory.CheckedStatement(kind, SyntaxFactory.Block(statements)));
}
var block = statements.Single() as BlockSyntax;
if (block != null)
{
return SpecializedCollections.SingletonEnumerable<StatementSyntax>(SyntaxFactory.CheckedStatement(kind, block));
}
return SpecializedCollections.SingletonEnumerable<StatementSyntax>(SyntaxFactory.CheckedStatement(kind, SyntaxFactory.Block(statements)));
}
private IEnumerable<StatementSyntax> CleanupCode(IEnumerable<StatementSyntax> statements)
{
var semanticModel = this.SemanticDocument.SemanticModel;
var context = this.InsertionPoint.GetContext();
var postProcessor = new PostProcessor(semanticModel, context.SpanStart);
statements = postProcessor.RemoveRedundantBlock(statements);
statements = postProcessor.RemoveDeclarationAssignmentPattern(statements);
statements = postProcessor.RemoveInitializedDeclarationAndReturnPattern(statements);
return statements;
}
private OperationStatus CheckActiveStatements(IEnumerable<StatementSyntax> statements)
{
var count = statements.Count();
if (count == 0)
{
return OperationStatus.NoActiveStatement;
}
if (count == 1)
{
var returnStatement = statements.Single() as ReturnStatementSyntax;
if (returnStatement != null && returnStatement.Expression == null)
{
return OperationStatus.NoActiveStatement;
}
}
foreach (var statement in statements)
{
var declStatement = statement as LocalDeclarationStatementSyntax;
if (declStatement == null)
{
// found one
return OperationStatus.Succeeded;
}
foreach (var variable in declStatement.Declaration.Variables)
{
if (variable.Initializer != null)
{
// found one
return OperationStatus.Succeeded;
}
}
}
return OperationStatus.NoActiveStatement;
}
private IEnumerable<StatementSyntax> MoveDeclarationOutFromMethodDefinition(
IEnumerable<StatementSyntax> statements, CancellationToken cancellationToken)
{
var variableToRemoveMap = CreateVariableDeclarationToRemoveMap(
this.AnalyzerResult.GetVariablesToMoveOutToCallSiteOrDelete(cancellationToken), cancellationToken);
statements = statements.Select(s => FixDeclarationExpressionsAndDeclarationPatterns(s, variableToRemoveMap));
foreach (var statement in statements)
{
var declarationStatement = statement as LocalDeclarationStatementSyntax;
if (declarationStatement == null)
{
// if given statement is not decl statement.
yield return statement;
continue;
}
var expressionStatements = new List<StatementSyntax>();
var list = new List<VariableDeclaratorSyntax>();
var triviaList = new List<SyntaxTrivia>();
// When we modify the declaration to an initialization we have to preserve the leading trivia
var firstVariableToAttachTrivia = true;
// go through each var decls in decl statement, and create new assignment if
// variable is initialized at decl.
foreach (var variableDeclaration in declarationStatement.Declaration.Variables)
{
if (variableToRemoveMap.HasSyntaxAnnotation(variableDeclaration))
{
if (variableDeclaration.Initializer != null)
{
SyntaxToken identifier = ApplyTriviaFromDeclarationToAssignmentIdentifier(declarationStatement, firstVariableToAttachTrivia, variableDeclaration);
// move comments with the variable here
expressionStatements.Add(CreateAssignmentExpressionStatement(identifier, variableDeclaration.Initializer.Value));
}
else
{
// we don't remove trivia around tokens we remove
triviaList.AddRange(variableDeclaration.GetLeadingTrivia());
triviaList.AddRange(variableDeclaration.GetTrailingTrivia());
}
firstVariableToAttachTrivia = false;
continue;
}
// Prepend the trivia from the declarations without initialization to the next persisting variable declaration
if (triviaList.Count > 0)
{
list.Add(variableDeclaration.WithPrependedLeadingTrivia(triviaList));
triviaList.Clear();
firstVariableToAttachTrivia = false;
continue;
}
firstVariableToAttachTrivia = false;
list.Add(variableDeclaration);
}
if (list.Count == 0 && triviaList.Count > 0)
{
// well, there are trivia associated with the node.
// we can't just delete the node since then, we will lose
// the trivia. unfortunately, it is not easy to attach the trivia
// to next token. for now, create an empty statement and associate the
// trivia to the statement
// TODO : think about a way to trivia attached to next token
yield return SyntaxFactory.EmptyStatement(SyntaxFactory.Token(SyntaxFactory.TriviaList(triviaList), SyntaxKind.SemicolonToken, SyntaxTriviaList.Create(SyntaxFactory.ElasticMarker)));
triviaList.Clear();
}
// return survived var decls
if (list.Count > 0)
{
yield return SyntaxFactory.LocalDeclarationStatement(
declarationStatement.Modifiers,
SyntaxFactory.VariableDeclaration(
declarationStatement.Declaration.Type,
SyntaxFactory.SeparatedList(list)),
declarationStatement.SemicolonToken.WithPrependedLeadingTrivia(triviaList));
triviaList.Clear();
}
// return any expression statement if there was any
foreach (var expressionStatement in expressionStatements)
{
yield return expressionStatement;
}
}
}
/// <summary>
/// If the statement has an `out var` declaration expression for a variable which
/// needs to be removed, we need to turn it into a plain `out` parameter, so that
/// it doesn't declare a duplicate variable.
/// If the statement has a pattern declaration (such as `3 is int i`) for a variable
/// which needs to be removed, we will annotate it as a conflict, since we don't have
/// a better refactoring.
/// </summary>
private StatementSyntax FixDeclarationExpressionsAndDeclarationPatterns(StatementSyntax statement,
HashSet<SyntaxAnnotation> variablesToRemove)
{
var replacements = new Dictionary<SyntaxNode, SyntaxNode>();
var declarations = statement.DescendantNodes()
.Where(n => n.IsKind(SyntaxKind.DeclarationExpression, SyntaxKind.DeclarationPattern));
foreach (var node in declarations)
{
switch (node.Kind())
{
case SyntaxKind.DeclarationExpression:
{
var declaration = (DeclarationExpressionSyntax)node;
if (declaration.Designation.Kind() != SyntaxKind.SingleVariableDesignation)
{
break;
}
var designation = (SingleVariableDesignationSyntax)declaration.Designation;
var name = designation.Identifier.ValueText;
if (variablesToRemove.HasSyntaxAnnotation(designation))
{
var newLeadingTrivia = new SyntaxTriviaList();
newLeadingTrivia = newLeadingTrivia.AddRange(declaration.Type.GetLeadingTrivia());
newLeadingTrivia = newLeadingTrivia.AddRange(declaration.Type.GetTrailingTrivia());
newLeadingTrivia = newLeadingTrivia.AddRange(designation.GetLeadingTrivia());
replacements.Add(declaration, SyntaxFactory.IdentifierName(designation.Identifier)
.WithLeadingTrivia(newLeadingTrivia));
}
break;
}
case SyntaxKind.DeclarationPattern:
{
var pattern = (DeclarationPatternSyntax)node;
if (!variablesToRemove.HasSyntaxAnnotation(pattern))
{
break;
}
// We don't have a good refactoring for this, so we just annotate the conflict
// For instance, when a local declared by a pattern declaration (`3 is int i`) is
// used outside the block we're trying to extract.
var designation = pattern.Designation as SingleVariableDesignationSyntax;
if (designation == null)
{
break;
}
var identifier = designation.Identifier;
var annotation = ConflictAnnotation.Create(CSharpFeaturesResources.Conflict_s_detected);
var newIdentifier = identifier.WithAdditionalAnnotations(annotation);
var newDesignation = designation.WithIdentifier(newIdentifier);
replacements.Add(pattern, pattern.WithDesignation(newDesignation));
break;
}
}
}
return statement.ReplaceNodes(replacements.Keys, (orig, partiallyReplaced) => replacements[orig]);
}
private static SyntaxToken ApplyTriviaFromDeclarationToAssignmentIdentifier(LocalDeclarationStatementSyntax declarationStatement, bool firstVariableToAttachTrivia, VariableDeclaratorSyntax variable)
{
var identifier = variable.Identifier;
var typeSyntax = declarationStatement.Declaration.Type;
if (firstVariableToAttachTrivia && typeSyntax != null)
{
var identifierLeadingTrivia = new SyntaxTriviaList();
if (typeSyntax.HasLeadingTrivia)
{
identifierLeadingTrivia = identifierLeadingTrivia.AddRange(typeSyntax.GetLeadingTrivia());
}
identifierLeadingTrivia = identifierLeadingTrivia.AddRange(identifier.LeadingTrivia);
identifier = identifier.WithLeadingTrivia(identifierLeadingTrivia);
}
return identifier;
}
private static SyntaxToken GetIdentifierTokenAndTrivia(SyntaxToken identifier, TypeSyntax typeSyntax)
{
if (typeSyntax != null)
{
var identifierLeadingTrivia = new SyntaxTriviaList();
var identifierTrailingTrivia = new SyntaxTriviaList();
if (typeSyntax.HasLeadingTrivia)
{
identifierLeadingTrivia = identifierLeadingTrivia.AddRange(typeSyntax.GetLeadingTrivia());
}
if (typeSyntax.HasTrailingTrivia)
{
identifierLeadingTrivia = identifierLeadingTrivia.AddRange(typeSyntax.GetTrailingTrivia());
}
identifierLeadingTrivia = identifierLeadingTrivia.AddRange(identifier.LeadingTrivia);
identifierTrailingTrivia = identifierTrailingTrivia.AddRange(identifier.TrailingTrivia);
identifier = identifier.WithLeadingTrivia(identifierLeadingTrivia)
.WithTrailingTrivia(identifierTrailingTrivia);
}
return identifier;
}
private IEnumerable<StatementSyntax> SplitOrMoveDeclarationIntoMethodDefinition(
IEnumerable<StatementSyntax> statements,
CancellationToken cancellationToken)
{
var semanticModel = this.SemanticDocument.SemanticModel;
var context = this.InsertionPoint.GetContext();
var postProcessor = new PostProcessor(semanticModel, context.SpanStart);
var declStatements = CreateDeclarationStatements(AnalyzerResult.GetVariablesToSplitOrMoveIntoMethodDefinition(cancellationToken), cancellationToken);
declStatements = postProcessor.MergeDeclarationStatements(declStatements);
return declStatements.Concat(statements);
}
private ExpressionSyntax CreateAssignmentExpression(SyntaxToken identifier, ExpressionSyntax rvalue)
{
return SyntaxFactory.AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
SyntaxFactory.IdentifierName(identifier),
rvalue);
}
protected override bool LastStatementOrHasReturnStatementInReturnableConstruct()
{
var lastStatement = this.GetLastStatementOrInitializerSelectedAtCallSite();
var container = lastStatement.GetAncestorsOrThis<SyntaxNode>().FirstOrDefault(n => n.IsReturnableConstruct());
if (container == null)
{
// case such as field initializer
return false;
}
var blockBody = container.GetBlockBody();
if (blockBody == null)
{
// such as expression lambda. there is no statement
return false;
}
// check whether it is last statement except return statement
var statements = blockBody.Statements;
if (statements.Last() == lastStatement)
{
return true;
}
var index = statements.IndexOf((StatementSyntax)lastStatement);
return statements[index + 1].Kind() == SyntaxKind.ReturnStatement;
}
protected override SyntaxToken CreateIdentifier(string name)
{
return SyntaxFactory.Identifier(name);
}
protected override StatementSyntax CreateReturnStatement(string identifierName = null)
{
return string.IsNullOrEmpty(identifierName)
? SyntaxFactory.ReturnStatement()
: SyntaxFactory.ReturnStatement(SyntaxFactory.IdentifierName(identifierName));
}
protected override ExpressionSyntax CreateCallSignature()
{
var methodName = CreateMethodNameForInvocation().WithAdditionalAnnotations(Simplifier.Annotation);
var arguments = new List<ArgumentSyntax>();
foreach (var argument in this.AnalyzerResult.MethodParameters)
{
var modifier = GetParameterRefSyntaxKind(argument.ParameterModifier);
var refOrOut = modifier == SyntaxKind.None ? default(SyntaxToken) : SyntaxFactory.Token(modifier);
arguments.Add(SyntaxFactory.Argument(SyntaxFactory.IdentifierName(argument.Name)).WithRefOrOutKeyword(refOrOut));
}
var invocation = SyntaxFactory.InvocationExpression(methodName,
SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(arguments)));
var shouldPutAsyncModifier = this.CSharpSelectionResult.ShouldPutAsyncModifier();
if (!shouldPutAsyncModifier)
{
return invocation;
}
return SyntaxFactory.AwaitExpression(invocation);
}
protected override StatementSyntax CreateAssignmentExpressionStatement(SyntaxToken identifier, ExpressionSyntax rvalue)
{
return SyntaxFactory.ExpressionStatement(CreateAssignmentExpression(identifier, rvalue));
}
protected override StatementSyntax CreateDeclarationStatement(
VariableInfo variable,
ExpressionSyntax initialValue,
CancellationToken cancellationToken)
{
// Convert to 'var' if appropriate. Note: because we're extracting out
// to a method, the initialValue will be a method-call. Types are not
// apperant with method calls (i.e. as opposed to a 'new XXX()' expression,
// where the type is apperant).
var type = variable.GetVariableType(this.SemanticDocument);
var typeNode = initialValue == null
? type.GenerateTypeSyntax()
: type.GenerateTypeSyntaxOrVar(
this.SemanticDocument.Document.Project.Solution.Options,
typeIsApperant: false);
var equalsValueClause = initialValue == null ? null : SyntaxFactory.EqualsValueClause(value: initialValue);
return SyntaxFactory.LocalDeclarationStatement(
SyntaxFactory.VariableDeclaration(typeNode)
.AddVariables(SyntaxFactory.VariableDeclarator(SyntaxFactory.Identifier(variable.Name)).WithInitializer(equalsValueClause)));
}
protected override async Task<GeneratedCode> CreateGeneratedCodeAsync(OperationStatus status, SemanticDocument newDocument, CancellationToken cancellationToken)
{
if (status.Succeeded())
{
// in hybrid code cases such as extract method, formatter will have some difficulties on where it breaks lines in two.
// here, we explicitly insert newline at the end of "{" of auto generated method decl so that anchor knows how to find out
// indentation of inserted statements (from users code) with user code style preserved
var root = newDocument.Root;
var methodDefinition = root.GetAnnotatedNodes<MethodDeclarationSyntax>(this.MethodDefinitionAnnotation).First();
var newMethodDefinition = TweakNewLinesInMethod(methodDefinition);
newDocument = await newDocument.WithSyntaxRootAsync(
root.ReplaceNode(methodDefinition, newMethodDefinition), cancellationToken).ConfigureAwait(false);
}
return await base.CreateGeneratedCodeAsync(status, newDocument, cancellationToken).ConfigureAwait(false);
}
private static MethodDeclarationSyntax TweakNewLinesInMethod(MethodDeclarationSyntax methodDefinition)
{
if (methodDefinition.Body != null)
{
return methodDefinition.ReplaceToken(
methodDefinition.Body.OpenBraceToken,
methodDefinition.Body.OpenBraceToken.WithAppendedTrailingTrivia(
SpecializedCollections.SingletonEnumerable(SyntaxFactory.CarriageReturnLineFeed)));
}
else if (methodDefinition.ExpressionBody != null)
{
return methodDefinition.ReplaceToken(
methodDefinition.ExpressionBody.ArrowToken,
methodDefinition.ExpressionBody.ArrowToken.WithPrependedLeadingTrivia(
SpecializedCollections.SingletonEnumerable(SyntaxFactory.CarriageReturnLineFeed)));
}
else
{
return methodDefinition;
}
}
protected StatementSyntax GetStatementContainingInvocationToExtractedMethodWorker()
{
var callSignature = CreateCallSignature();
if (this.AnalyzerResult.HasReturnType)
{
Contract.ThrowIfTrue(this.AnalyzerResult.HasVariableToUseAsReturnValue);
return SyntaxFactory.ReturnStatement(callSignature);
}
return SyntaxFactory.ExpressionStatement(callSignature);
}
}
}
}
| |
/*
insert license info here
*/
using System;
using System.Collections;
namespace Business.Data.Laboratorio
{
/// <summary>
/// Generated by MyGeneration using the NHibernate Object Mapping template
/// </summary>
[Serializable]
public sealed class AgendaDia : Business.BaseDataAccess
{
#region Private Members
private bool m_isChanged;
private int m_idagendadia;
private Agenda m_idagenda;
private Efector m_idefector;
private int m_dia;
private int m_limiteturnos;
private string m_horadesde;
private string m_horahasta;
private int m_tipoturno;
private int m_frecuencia;
#endregion
#region Default ( Empty ) Class Constuctor
/// <summary>
/// default constructor
/// </summary>
public AgendaDia()
{
m_idagendadia = 0;
m_idagenda = new Agenda();
m_idefector = new Efector();
m_dia = 0;
m_limiteturnos = 0;
m_horadesde = String.Empty;
m_horahasta = String.Empty;
m_tipoturno = 0;
m_frecuencia = 0;
}
#endregion // End of Default ( Empty ) Class Constuctor
#region Required Fields Only Constructor
/// <summary>
/// required (not null) fields only constructor
/// </summary>
public AgendaDia(
Agenda idagenda,
Efector idefector,
int dia,
int limiteturnos,
string horadesde,
string horahasta)
: this()
{
m_idagenda = idagenda;
m_idefector = idefector;
m_dia = dia;
m_limiteturnos = limiteturnos;
m_horadesde = horadesde;
m_horahasta = horahasta;
}
#endregion // End Required Fields Only Constructor
#region Public Properties
/// <summary>
///
/// </summary>
public int IdAgendaDia
{
get { return m_idagendadia; }
set
{
m_isChanged |= ( m_idagendadia != value );
m_idagendadia = value;
}
}
/// <summary>
///
/// </summary>
public Agenda IdAgenda
{
get { return m_idagenda; }
set
{
m_isChanged |= ( m_idagenda != value );
m_idagenda = value;
}
}
/// <summary>
///
/// </summary>
public Efector IdEfector
{
get { return m_idefector; }
set
{
m_isChanged |= ( m_idefector != value );
m_idefector = value;
}
}
/// <summary>
///
/// </summary>
public int Dia
{
get { return m_dia; }
set
{
m_isChanged |= ( m_dia != value );
m_dia = value;
}
}
/// <summary>
///
/// </summary>
public int LimiteTurnos
{
get { return m_limiteturnos; }
set
{
m_isChanged |= ( m_limiteturnos != value );
m_limiteturnos = value;
}
}
public string HoraDesde
{
get { return m_horadesde; }
set
{
if (value == null)
throw new ArgumentOutOfRangeException("Null value not allowed for HoraDesde", value, "null");
if (value.Length > 5)
throw new ArgumentOutOfRangeException("Invalid value for HoraDesde", value, value.ToString());
m_isChanged |= (m_horadesde != value); m_horadesde = value;
}
}
public string HoraHasta
{
get { return m_horahasta; }
set
{
if (value == null)
throw new ArgumentOutOfRangeException("Null value not allowed for m_horahasta", value, "null");
if (value.Length > 5)
throw new ArgumentOutOfRangeException("Invalid value for m_horahasta", value, value.ToString());
m_isChanged |= (m_horahasta != value); m_horahasta = value;
}
}
public int TipoTurno
{
get { return m_tipoturno; }
set
{
m_isChanged |= (m_tipoturno != value);
m_tipoturno = value;
}
}
public int Frecuencia
{
get { return m_frecuencia; }
set
{
m_isChanged |= (m_frecuencia != value);
m_frecuencia = value;
}
}
/// <summary>
/// Returns whether or not the object has changed it's values.
/// </summary>
public bool IsChanged
{
get { return m_isChanged; }
}
#endregion
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/*
* This package is based on the work done by Keiron Liddle, Aftex Software
* <[email protected]> to whom the Ant project is very grateful for his
* great code.
*/
using java.io;
using java.lang;
using java.net;
using java.nio;
using java.text;
using java.util;
namespace RSUtilities.Compression.BZip2
{
/// <summary>
/// Base class for both the compress and decompress classes.
/// Holds common arrays, and static data.
/// <p>
/// This interface is public for historical purposes.
/// You should have no need to use it.
/// </p>
/// </summary>
public interface BZip2Constants
{
/// <summary>
/// This array really shouldn't be here.
/// Again, for historical purposes it is.
///
/// <p>FIXME: This array should be in a private or package private
/// location, since it could be modified by malicious code.</p>
/// </summary>
}
public static class BZip2Constants_Fields
{
public const int baseBlockSize = 100000;
public const int MAX_ALPHA_SIZE = 258;
public const int MAX_CODE_LEN = 23;
public const int RUNA = 0;
public const int RUNB = 1;
public const int N_GROUPS = 6;
public const int G_SIZE = 50;
public const int N_ITERS = 4;
public const int NUM_OVERSHOOT_BYTES = 20;
public static readonly int MAX_SELECTORS = (2 + (900000 / G_SIZE));
public static readonly int[] rNums = {
619,
720,
127,
481,
931,
816,
813,
233,
566,
247,
985,
724,
205,
454,
863,
491,
741,
242,
949,
214,
733,
859,
335,
708,
621,
574,
73,
654,
730,
472,
419,
436,
278,
496,
867,
210,
399,
680,
480,
51,
878,
465,
811,
169,
869,
675,
611,
697,
867,
561,
862,
687,
507,
283,
482,
129,
807,
591,
733,
623,
150,
238,
59,
379,
684,
877,
625,
169,
643,
105,
170,
607,
520,
932,
727,
476,
693,
425,
174,
647,
73,
122,
335,
530,
442,
853,
695,
249,
445,
515,
909,
545,
703,
919,
874,
474,
882,
500,
594,
612,
641,
801,
220,
162,
819,
984,
589,
513,
495,
799,
161,
604,
958,
533,
221,
400,
386,
867,
600,
782,
382,
596,
414,
171,
516,
375,
682,
485,
911,
276,
98,
553,
163,
354,
666,
933,
424,
341,
533,
870,
227,
730,
475,
186,
263,
647,
537,
686,
600,
224,
469,
68,
770,
919,
190,
373,
294,
822,
808,
206,
184,
943,
795,
384,
383,
461,
404,
758,
839,
887,
715,
67,
618,
276,
204,
918,
873,
777,
604,
560,
951,
160,
578,
722,
79,
804,
96,
409,
713,
940,
652,
934,
970,
447,
318,
353,
859,
672,
112,
785,
645,
863,
803,
350,
139,
93,
354,
99,
820,
908,
609,
772,
154,
274,
580,
184,
79,
626,
630,
742,
653,
282,
762,
623,
680,
81,
927,
626,
789,
125,
411,
521,
938,
300,
821,
78,
343,
175,
128,
250,
170,
774,
972,
275,
999,
639,
495,
78,
352,
126,
857,
956,
358,
619,
580,
124,
737,
594,
701,
612,
669,
112,
134,
694,
363,
992,
809,
743,
168,
974,
944,
375,
748,
52,
600,
747,
642,
182,
862,
81,
344,
805,
988,
739,
511,
655,
814,
334,
249,
515,
897,
955,
664,
981,
649,
113,
974,
459,
893,
228,
433,
837,
553,
268,
926,
240,
102,
654,
459,
51,
686,
754,
806,
760,
493,
403,
415,
394,
687,
700,
946,
670,
656,
610,
738,
392,
760,
799,
887,
653,
978,
321,
576,
617,
626,
502,
894,
679,
243,
440,
680,
879,
194,
572,
640,
724,
926,
56,
204,
700,
707,
151,
457,
449,
797,
195,
791,
558,
945,
679,
297,
59,
87,
824,
713,
663,
412,
693,
342,
606,
134,
108,
571,
364,
631,
212,
174,
643,
304,
329,
343,
97,
430,
751,
497,
314,
983,
374,
822,
928,
140,
206,
73,
263,
980,
736,
876,
478,
430,
305,
170,
514,
364,
692,
829,
82,
855,
953,
676,
246,
369,
970,
294,
750,
807,
827,
150,
790,
288,
923,
804,
378,
215,
828,
592,
281,
565,
555,
710,
82,
896,
831,
547,
261,
524,
462,
293,
465,
502,
56,
661,
821,
976,
991,
658,
869,
905,
758,
745,
193,
768,
550,
608,
933,
378,
286,
215,
979,
792,
961,
61,
688,
793,
644,
986,
403,
106,
366,
905,
644,
372,
567,
466,
434,
645,
210,
389,
550,
919,
135,
780,
773,
635,
389,
707,
100,
626,
958,
165,
504,
920,
176,
193,
713,
857,
265,
203,
50,
668,
108,
645,
990,
626,
197,
510,
357,
358,
850,
858,
364,
936,
638
};
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Nop.Core.Caching;
using Nop.Core.Data;
using Nop.Core.Domain.Common;
using Nop.Services.Events;
namespace Nop.Services.Common
{
/// <summary>
/// Address attribute service
/// </summary>
public partial class AddressAttributeService : IAddressAttributeService
{
#region Constants
/// <summary>
/// Key for caching
/// </summary>
private const string ADDRESSATTRIBUTES_ALL_KEY = "Nop.addressattribute.all";
/// <summary>
/// Key for caching
/// </summary>
/// <remarks>
/// {0} : address attribute ID
/// </remarks>
private const string ADDRESSATTRIBUTES_BY_ID_KEY = "Nop.addressattribute.id-{0}";
/// <summary>
/// Key for caching
/// </summary>
/// <remarks>
/// {0} : address attribute ID
/// </remarks>
private const string ADDRESSATTRIBUTEVALUES_ALL_KEY = "Nop.addressattributevalue.all-{0}";
/// <summary>
/// Key for caching
/// </summary>
/// <remarks>
/// {0} : address attribute value ID
/// </remarks>
private const string ADDRESSATTRIBUTEVALUES_BY_ID_KEY = "Nop.addressattributevalue.id-{0}";
/// <summary>
/// Key pattern to clear cache
/// </summary>
private const string ADDRESSATTRIBUTES_PATTERN_KEY = "Nop.addressattribute.";
/// <summary>
/// Key pattern to clear cache
/// </summary>
private const string ADDRESSATTRIBUTEVALUES_PATTERN_KEY = "Nop.addressattributevalue.";
#endregion
#region Fields
private readonly IRepository<AddressAttribute> _addressAttributeRepository;
private readonly IRepository<AddressAttributeValue> _addressAttributeValueRepository;
private readonly IEventPublisher _eventPublisher;
private readonly ICacheManager _cacheManager;
#endregion
#region Ctor
/// <summary>
/// Ctor
/// </summary>
/// <param name="cacheManager">Cache manager</param>
/// <param name="addressAttributeRepository">Address attribute repository</param>
/// <param name="addressAttributeValueRepository">Address attribute value repository</param>
/// <param name="eventPublisher">Event published</param>
public AddressAttributeService(ICacheManager cacheManager,
IRepository<AddressAttribute> addressAttributeRepository,
IRepository<AddressAttributeValue> addressAttributeValueRepository,
IEventPublisher eventPublisher)
{
this._cacheManager = cacheManager;
this._addressAttributeRepository = addressAttributeRepository;
this._addressAttributeValueRepository = addressAttributeValueRepository;
this._eventPublisher = eventPublisher;
}
#endregion
#region Methods
/// <summary>
/// Deletes an address attribute
/// </summary>
/// <param name="addressAttribute">Address attribute</param>
public virtual void DeleteAddressAttribute(AddressAttribute addressAttribute)
{
if (addressAttribute == null)
throw new ArgumentNullException("addressAttribute");
_addressAttributeRepository.Delete(addressAttribute);
_cacheManager.RemoveByPattern(ADDRESSATTRIBUTES_PATTERN_KEY);
_cacheManager.RemoveByPattern(ADDRESSATTRIBUTEVALUES_PATTERN_KEY);
//event notification
_eventPublisher.EntityDeleted(addressAttribute);
}
/// <summary>
/// Gets all address attributes
/// </summary>
/// <returns>Address attributes</returns>
public virtual IList<AddressAttribute> GetAllAddressAttributes()
{
string key = ADDRESSATTRIBUTES_ALL_KEY;
return _cacheManager.Get(key, () =>
{
var query = from aa in _addressAttributeRepository.Table
orderby aa.DisplayOrder, aa.Id
select aa;
return query.ToList();
});
}
/// <summary>
/// Gets an address attribute
/// </summary>
/// <param name="addressAttributeId">Address attribute identifier</param>
/// <returns>Address attribute</returns>
public virtual AddressAttribute GetAddressAttributeById(int addressAttributeId)
{
if (addressAttributeId == 0)
return null;
string key = string.Format(ADDRESSATTRIBUTES_BY_ID_KEY, addressAttributeId);
return _cacheManager.Get(key, () => _addressAttributeRepository.GetById(addressAttributeId));
}
/// <summary>
/// Inserts an address attribute
/// </summary>
/// <param name="addressAttribute">Address attribute</param>
public virtual void InsertAddressAttribute(AddressAttribute addressAttribute)
{
if (addressAttribute == null)
throw new ArgumentNullException("addressAttribute");
_addressAttributeRepository.Insert(addressAttribute);
_cacheManager.RemoveByPattern(ADDRESSATTRIBUTES_PATTERN_KEY);
_cacheManager.RemoveByPattern(ADDRESSATTRIBUTEVALUES_PATTERN_KEY);
//event notification
_eventPublisher.EntityInserted(addressAttribute);
}
/// <summary>
/// Updates the address attribute
/// </summary>
/// <param name="addressAttribute">Address attribute</param>
public virtual void UpdateAddressAttribute(AddressAttribute addressAttribute)
{
if (addressAttribute == null)
throw new ArgumentNullException("addressAttribute");
_addressAttributeRepository.Update(addressAttribute);
_cacheManager.RemoveByPattern(ADDRESSATTRIBUTES_PATTERN_KEY);
_cacheManager.RemoveByPattern(ADDRESSATTRIBUTEVALUES_PATTERN_KEY);
//event notification
_eventPublisher.EntityUpdated(addressAttribute);
}
/// <summary>
/// Deletes an address attribute value
/// </summary>
/// <param name="addressAttributeValue">Address attribute value</param>
public virtual void DeleteAddressAttributeValue(AddressAttributeValue addressAttributeValue)
{
if (addressAttributeValue == null)
throw new ArgumentNullException("addressAttributeValue");
_addressAttributeValueRepository.Delete(addressAttributeValue);
_cacheManager.RemoveByPattern(ADDRESSATTRIBUTES_PATTERN_KEY);
_cacheManager.RemoveByPattern(ADDRESSATTRIBUTEVALUES_PATTERN_KEY);
//event notification
_eventPublisher.EntityDeleted(addressAttributeValue);
}
/// <summary>
/// Gets address attribute values by address attribute identifier
/// </summary>
/// <param name="addressAttributeId">The address attribute identifier</param>
/// <returns>Address attribute values</returns>
public virtual IList<AddressAttributeValue> GetAddressAttributeValues(int addressAttributeId)
{
string key = string.Format(ADDRESSATTRIBUTEVALUES_ALL_KEY, addressAttributeId);
return _cacheManager.Get(key, () =>
{
var query = from aav in _addressAttributeValueRepository.Table
orderby aav.DisplayOrder, aav.Id
where aav.AddressAttributeId == addressAttributeId
select aav;
var addressAttributeValues = query.ToList();
return addressAttributeValues;
});
}
/// <summary>
/// Gets an address attribute value
/// </summary>
/// <param name="addressAttributeValueId">Address attribute value identifier</param>
/// <returns>Address attribute value</returns>
public virtual AddressAttributeValue GetAddressAttributeValueById(int addressAttributeValueId)
{
if (addressAttributeValueId == 0)
return null;
string key = string.Format(ADDRESSATTRIBUTEVALUES_BY_ID_KEY, addressAttributeValueId);
return _cacheManager.Get(key, () => _addressAttributeValueRepository.GetById(addressAttributeValueId));
}
/// <summary>
/// Inserts an address attribute value
/// </summary>
/// <param name="addressAttributeValue">Address attribute value</param>
public virtual void InsertAddressAttributeValue(AddressAttributeValue addressAttributeValue)
{
if (addressAttributeValue == null)
throw new ArgumentNullException("addressAttributeValue");
_addressAttributeValueRepository.Insert(addressAttributeValue);
_cacheManager.RemoveByPattern(ADDRESSATTRIBUTES_PATTERN_KEY);
_cacheManager.RemoveByPattern(ADDRESSATTRIBUTEVALUES_PATTERN_KEY);
//event notification
_eventPublisher.EntityInserted(addressAttributeValue);
}
/// <summary>
/// Updates the address attribute value
/// </summary>
/// <param name="addressAttributeValue">Address attribute value</param>
public virtual void UpdateAddressAttributeValue(AddressAttributeValue addressAttributeValue)
{
if (addressAttributeValue == null)
throw new ArgumentNullException("addressAttributeValue");
_addressAttributeValueRepository.Update(addressAttributeValue);
_cacheManager.RemoveByPattern(ADDRESSATTRIBUTES_PATTERN_KEY);
_cacheManager.RemoveByPattern(ADDRESSATTRIBUTEVALUES_PATTERN_KEY);
//event notification
_eventPublisher.EntityUpdated(addressAttributeValue);
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
using System;
using System.Reflection;
using System.Collections.Generic;
#pragma warning disable 0067
namespace System.Reflection.Tests
{
public class EventInfoMethodTests
{
// Verify AddEventHandler and RemoveEventHandler for EventInfo
[Fact]
public void VerifyAddRemoveEventHandler1()
{
EventInfo ei = GetEventInfo(typeof(BaseClass), "EventPublic");
Assert.NotNull(ei);
EventHandler myhandler = new EventHandler(MyEventHandler);
BaseClass obj = new BaseClass();
ei.AddEventHandler(obj, myhandler);
//Try to remove event Handler and Verify that no exception is thrown.
ei.RemoveEventHandler(obj, myhandler);
}
// Verify AddEventHandler and RemoveEventHandler for EventInfo
[Fact]
public void VerifyAddRemoveEventHandler2()
{
EventInfo ei = GetEventInfo(typeof(BaseClass), "EventPublicStatic");
Assert.NotNull(ei);
EventHandler myhandler = new EventHandler(MyEventHandler);
ei.AddEventHandler(null, myhandler);
//Try to remove event Handler and Verify that no exception is thrown.
ei.RemoveEventHandler(null, myhandler);
}
// Verify AddEventHandler and RemoveEventHandler for EventInfo
[Fact]
public void VerifyAddRemoveEventHandler3()
{
EventInfo ei = GetEventInfo(typeof(BaseClass), "EventPublicVirtual");
Assert.NotNull(ei);
EventHandler myhandler = new EventHandler(MyEventHandler);
BaseClass obj = new BaseClass();
ei.AddEventHandler(obj, myhandler);
//Try to remove event Handler and Verify that no exception is thrown.
ei.RemoveEventHandler(obj, myhandler);
}
// Verify AddEventHandler and RemoveEventHandler for EventInfo
[Fact]
public void VerifyAddRemoveEventHandler4()
{
EventInfo ei = GetEventInfo(typeof(SubClass), "EventPublicNew");
Assert.NotNull(ei);
EventHandler myhandler = new EventHandler(MyEventHandler);
SubClass obj = new SubClass();
ei.AddEventHandler(obj, myhandler);
//Try to remove event Handler and Verify that no exception is thrown.
ei.RemoveEventHandler(obj, myhandler);
}
// Verify AddEventHandler and RemoveEventHandler for EventInfo
[Fact]
public void VerifyAddRemoveEventHandler5()
{
EventInfo ei = GetEventInfo(typeof(SubClass), "EventPublic");
Assert.NotNull(ei);
EventHandler myhandler = new EventHandler(MyEventHandler);
SubClass obj = new SubClass();
ei.AddEventHandler(obj, myhandler);
//Try to remove event Handler and Verify that no exception is thrown.
ei.RemoveEventHandler(obj, myhandler);
}
//Negative Tests
// Target null for AddEventHandler
[Fact]
public void VerifyAddRemoveEventHandler6()
{
EventInfo ei = GetEventInfo(typeof(BaseClass), "EventPublic");
Assert.NotNull(ei);
EventHandler myhandler = new EventHandler(MyEventHandler);
BaseClass obj = new BaseClass();
//Target is null and event is not static
// Win8P throws generic Exception
Assert.ThrowsAny<Exception>(() => ei.AddEventHandler(null, myhandler));
}
// Target null for RemoveEventHandler
[Fact]
public void VerifyAddRemoveEventHandler7()
{
EventInfo ei = GetEventInfo(typeof(BaseClass), "EventPublic");
Assert.NotNull(ei);
EventHandler myhandler = new EventHandler(MyEventHandler);
BaseClass obj = new BaseClass();
ei.AddEventHandler(obj, myhandler);
//Target is null and event is not static
// Win8P throws generic Exception
Assert.ThrowsAny<Exception>(() => ei.RemoveEventHandler(null, myhandler));
}
// EventHandler null for AddEventHandler
[Fact]
public void VerifyAddRemoveEventHandler8()
{
EventInfo ei = GetEventInfo(typeof(BaseClass), "EventPublic");
Assert.NotNull(ei);
EventHandler myhandler = new EventHandler(MyEventHandler);
BaseClass obj = new BaseClass();
SomeDelegate d1 = new SomeDelegate(SomeHandler);
//Handler is not correct.
Assert.Throws<ArgumentException>(() =>
{
ei.AddEventHandler(obj, d1);
});
}
// EventHandler null for RemoveEventHandler
[Fact]
public void VerifyAddRemoveEventHandler9()
{
EventInfo ei = GetEventInfo(typeof(BaseClass), "EventPublic");
Assert.NotNull(ei);
EventHandler myhandler = new EventHandler(MyEventHandler);
BaseClass obj = new BaseClass();
ei.AddEventHandler(obj, myhandler);
SomeDelegate d1 = new SomeDelegate(SomeHandler);
//Handler is not correct.
// Win8P throws generic Exception
Assert.Throws<ArgumentException>(() =>
{
ei.RemoveEventHandler(obj, d1);
});
}
// Wrong Target for AddEventHandler
[Fact]
public void VerifyAddRemoveEventHandler10()
{
EventInfo ei = GetEventInfo(typeof(BaseClass), "EventPublic");
Assert.NotNull(ei);
EventHandler myhandler = new EventHandler(MyEventHandler);
String obj = "hello";
//Target is wrong.
// Win8P throws generic Exception
Assert.ThrowsAny<Exception>(() => ei.AddEventHandler(obj, myhandler));
}
// Target null for RemoveEventHandler
[Fact]
public void VerifyAddRemoveEventHandler11()
{
EventInfo ei = GetEventInfo(typeof(BaseClass), "EventPublic");
Assert.NotNull(ei);
EventHandler myhandler = new EventHandler(MyEventHandler);
BaseClass obj = new BaseClass();
ei.AddEventHandler(obj, myhandler);
//Target is wrong.
// Win8P throws generic Exception
Assert.ThrowsAny<Exception>(() => ei.RemoveEventHandler((Object)"hello", myhandler));
}
// Test for Equals Method
[Fact]
public void VerifyEqualsMethod1()
{
EventInfo ei1 = GetEventInfo(typeof(BaseClass), "EventPublic");
Assert.NotNull(ei1);
EventInfo ei2 = GetEventInfo(typeof(BaseClass), "EventPublic");
Assert.NotNull(ei2);
Assert.Equal(ei1, ei2);
}
// Test for Equals Method
[Fact]
public void VerifyEqualsMethod2()
{
EventInfo ei1 = GetEventInfo(typeof(BaseClass), "EventPublic");
Assert.NotNull(ei1);
EventInfo ei2 = GetEventInfo(typeof(SubClass), "EventPublic");
Assert.NotNull(ei2);
Assert.NotEqual(ei1, ei2);
}
// Test for Equals Method
[Fact]
public void VerifyEqualsMethod3()
{
EventInfo ei1 = GetEventInfo(typeof(BaseClass), "EventPublic");
Assert.NotNull(ei1);
EventInfo ei2 = GetEventInfo(typeof(BaseClass), "EventPublicStatic");
Assert.NotNull(ei2);
Assert.NotEqual(ei1, ei2);
}
// Test for GetHashCode Method
[Fact]
public void VerifyGetHashCode()
{
EventInfo ei = GetEventInfo(typeof(BaseClass), "EventPublic");
Assert.NotNull(ei);
int hcode = ei.GetHashCode();
Assert.False(hcode <= 0);
}
//private helper methods
private static EventInfo GetEventInfo(Type t, string eventName)
{
TypeInfo ti = t.GetTypeInfo();
IEnumerator<EventInfo> allevents = ti.DeclaredEvents.GetEnumerator();
EventInfo eventFound = null;
while (allevents.MoveNext())
{
if (eventName.Equals(allevents.Current.Name))
{
eventFound = allevents.Current;
break;
}
}
return eventFound;
}
//Event Handler for Testing
private static void MyEventHandler(Object o, EventArgs e)
{
}
//Event Handler for Testing
private static void SomeHandler(Object o)
{
}
public delegate void SomeDelegate(Object o);
}
// Metadata for Reflection
public class BaseClass
{
public event EventHandler EventPublic; // inherited
public static event EventHandler EventPublicStatic;
public virtual event EventHandler EventPublicVirtual;
}
public class SubClass : BaseClass
{
public new event EventHandler EventPublic; //overrides event
public event EventHandler EventPublicNew; // new event
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Memory.Tests;
using System.MemoryTests;
using Microsoft.Xunit.Performance;
using Xunit;
namespace System.Buffers.Tests
{
public class Perf_ReadOnlySequence_TryGet
{
private const int InnerCount = 100_000;
volatile static int _volatileInt = 0;
[Benchmark(InnerIterationCount = InnerCount)]
[InlineData(10_000, 100)]
private static void Byte_Array(int bufSize, int bufOffset)
{
var buffer = new ReadOnlySequence<byte>(new byte[bufSize], bufOffset, bufSize - 2 * bufOffset);
foreach (BenchmarkIteration iteration in Benchmark.Iterations)
{
int localInt = 0;
using (iteration.StartMeasurement())
{
for (int i = 0; i < Benchmark.InnerIterationCount; i++)
{
SequencePosition p = buffer.Start;
while (buffer.TryGet(ref p, out ReadOnlyMemory<byte> memory))
localInt ^= memory.Length;
}
}
_volatileInt = localInt;
}
}
[Benchmark(InnerIterationCount = InnerCount)]
[InlineData(10_000, 100)]
private static void Byte_Memory(int bufSize, int bufOffset)
{
var manager = new CustomMemoryForTest<byte>(new byte[bufSize], bufOffset, bufSize - 2 * bufOffset);
var buffer = new ReadOnlySequence<byte>(manager.Memory);
foreach (BenchmarkIteration iteration in Benchmark.Iterations)
{
int localInt = 0;
using (iteration.StartMeasurement())
{
for (int i = 0; i < Benchmark.InnerIterationCount; i++)
{
SequencePosition p = buffer.Start;
while (buffer.TryGet(ref p, out ReadOnlyMemory<byte> memory))
localInt ^= memory.Length;
}
}
_volatileInt = localInt;
}
}
[Benchmark(InnerIterationCount = InnerCount)]
[InlineData(10_000, 100)]
private static void Byte_SingleSegment(int bufSize, int bufOffset)
{
var segment1 = new BufferSegment<byte>(new byte[bufSize]);
var buffer = new ReadOnlySequence<byte>(segment1, bufOffset, segment1, bufSize - bufOffset);
foreach (BenchmarkIteration iteration in Benchmark.Iterations)
{
int localInt = 0;
using (iteration.StartMeasurement())
{
for (int i = 0; i < Benchmark.InnerIterationCount; i++)
{
SequencePosition p = buffer.Start;
while (buffer.TryGet(ref p, out ReadOnlyMemory<byte> memory))
localInt ^= memory.Length;
}
}
_volatileInt = localInt;
}
}
[Benchmark(InnerIterationCount = InnerCount / 10)]
[InlineData(10_000, 100)]
private static void Byte_MultiSegment(int bufSize, int bufOffset)
{
var segment1 = new BufferSegment<byte>(new byte[bufSize / 10]);
BufferSegment<byte> segment2 = segment1;
for (int j = 0; j < 10; j++)
segment2 = segment2.Append(new byte[bufSize / 10]);
var buffer = new ReadOnlySequence<byte>(segment1, bufOffset, segment2, bufSize / 10 - bufOffset);
foreach (BenchmarkIteration iteration in Benchmark.Iterations)
{
int localInt = 0;
using (iteration.StartMeasurement())
{
for (int i = 0; i < Benchmark.InnerIterationCount; i++)
{
SequencePosition p = buffer.Start;
while (buffer.TryGet(ref p, out ReadOnlyMemory<byte> memory))
localInt ^= memory.Length;
}
}
_volatileInt = localInt;
}
}
[Benchmark(InnerIterationCount = InnerCount)]
private static void Byte_Empty()
{
ReadOnlySequence<byte> buffer = ReadOnlySequence<byte>.Empty;
foreach (BenchmarkIteration iteration in Benchmark.Iterations)
{
int localInt = 0;
using (iteration.StartMeasurement())
{
for (int i = 0; i < Benchmark.InnerIterationCount; i++)
{
SequencePosition p = buffer.Start;
while (buffer.TryGet(ref p, out ReadOnlyMemory<byte> memory))
localInt ^= memory.Length;
}
}
_volatileInt = localInt;
}
}
[Benchmark(InnerIterationCount = InnerCount)]
private static void Byte_Default()
{
ReadOnlySequence<byte> buffer = default;
foreach (BenchmarkIteration iteration in Benchmark.Iterations)
{
int localInt = 0;
using (iteration.StartMeasurement())
{
for (int i = 0; i < Benchmark.InnerIterationCount; i++)
{
SequencePosition p = buffer.Start;
while (buffer.TryGet(ref p, out ReadOnlyMemory<byte> memory))
localInt ^= memory.Length;
}
}
_volatileInt = localInt;
}
}
[Benchmark(InnerIterationCount = InnerCount)]
[InlineData(10_000, 100)]
private static void Char_Array(int bufSize, int bufOffset)
{
var buffer = new ReadOnlySequence<char>(new char[bufSize], bufOffset, bufSize - 2 * bufOffset);
foreach (BenchmarkIteration iteration in Benchmark.Iterations)
{
int localInt = 0;
using (iteration.StartMeasurement())
{
for (int i = 0; i < Benchmark.InnerIterationCount; i++)
{
SequencePosition p = buffer.Start;
while (buffer.TryGet(ref p, out ReadOnlyMemory<char> memory))
localInt ^= memory.Length;
}
}
_volatileInt = localInt;
}
}
[Benchmark(InnerIterationCount = InnerCount)]
[InlineData(10_000, 100)]
private static void Char_Memory(int bufSize, int bufOffset)
{
var manager = new CustomMemoryForTest<char>(new char[bufSize], bufOffset, bufSize - 2 * bufOffset);
var buffer = new ReadOnlySequence<char>(manager.Memory);
foreach (BenchmarkIteration iteration in Benchmark.Iterations)
{
int localInt = 0;
using (iteration.StartMeasurement())
{
for (int i = 0; i < Benchmark.InnerIterationCount; i++)
{
SequencePosition p = buffer.Start;
while (buffer.TryGet(ref p, out ReadOnlyMemory<char> memory))
localInt ^= memory.Length;
}
}
_volatileInt = localInt;
}
}
[Benchmark(InnerIterationCount = InnerCount)]
[InlineData(10_000, 100)]
private static void Char_SingleSegment(int bufSize, int bufOffset)
{
var segment1 = new BufferSegment<char>(new char[bufSize]);
var buffer = new ReadOnlySequence<char>(segment1, bufOffset, segment1, bufSize - bufOffset);
foreach (BenchmarkIteration iteration in Benchmark.Iterations)
{
int localInt = 0;
using (iteration.StartMeasurement())
{
for (int i = 0; i < Benchmark.InnerIterationCount; i++)
{
SequencePosition p = buffer.Start;
while (buffer.TryGet(ref p, out ReadOnlyMemory<char> memory))
localInt ^= memory.Length;
}
}
_volatileInt = localInt;
}
}
[Benchmark(InnerIterationCount = InnerCount / 10)]
[InlineData(10_000, 100)]
private static void Char_MultiSegment(int bufSize, int bufOffset)
{
var segment1 = new BufferSegment<char>(new char[bufSize / 10]);
BufferSegment<char> segment2 = segment1;
for (int j = 0; j < 10; j++)
segment2 = segment2.Append(new char[bufSize / 10]);
var buffer = new ReadOnlySequence<char>(segment1, bufOffset, segment2, bufSize / 10 - bufOffset);
foreach (BenchmarkIteration iteration in Benchmark.Iterations)
{
int localInt = 0;
using (iteration.StartMeasurement())
{
for (int i = 0; i < Benchmark.InnerIterationCount; i++)
{
SequencePosition p = buffer.Start;
while (buffer.TryGet(ref p, out ReadOnlyMemory<char> memory))
localInt ^= memory.Length;
}
}
_volatileInt = localInt;
}
}
[Benchmark(InnerIterationCount = InnerCount)]
[InlineData(10_000, 100)]
private static void String(int bufSize, int bufOffset)
{
ReadOnlyMemory<char> strMemory = new string('a', bufSize).AsMemory();
strMemory = strMemory.Slice(bufOffset, bufSize - bufOffset);
var buffer = new ReadOnlySequence<char>(strMemory);
foreach (BenchmarkIteration iteration in Benchmark.Iterations)
{
int localInt = 0;
using (iteration.StartMeasurement())
{
for (int i = 0; i < Benchmark.InnerIterationCount; i++)
{
SequencePosition p = buffer.Start;
while (buffer.TryGet(ref p, out ReadOnlyMemory<char> memory))
localInt ^= memory.Length;
}
}
_volatileInt = localInt;
}
}
[Benchmark(InnerIterationCount = InnerCount)]
private static void Char_Empty()
{
ReadOnlySequence<char> buffer = ReadOnlySequence<char>.Empty;
foreach (BenchmarkIteration iteration in Benchmark.Iterations)
{
int localInt = 0;
using (iteration.StartMeasurement())
{
for (int i = 0; i < Benchmark.InnerIterationCount; i++)
{
SequencePosition p = buffer.Start;
while (buffer.TryGet(ref p, out ReadOnlyMemory<char> memory))
localInt ^= memory.Length;
}
}
_volatileInt = localInt;
}
}
[Benchmark(InnerIterationCount = InnerCount)]
private static void Char_Default()
{
ReadOnlySequence<char> buffer = default;
foreach (BenchmarkIteration iteration in Benchmark.Iterations)
{
int localInt = 0;
using (iteration.StartMeasurement())
{
for (int i = 0; i < Benchmark.InnerIterationCount; i++)
{
SequencePosition p = buffer.Start;
while (buffer.TryGet(ref p, out ReadOnlyMemory<char> memory))
localInt ^= memory.Length;
}
}
_volatileInt = localInt;
}
}
}
}
| |
using System;
using System.Threading.Tasks;
using Tweetinvi.Events;
using Tweetinvi.Models;
using Tweetinvi.Streaming;
using Xunit;
using Xunit.Abstractions;
using xUnitinvi.TestHelpers;
namespace xUnitinvi.EndToEnd
{
[Collection("EndToEndTests")]
public class StreamEndToEndTests : TweetinviTest
{
public StreamEndToEndTests(ITestOutputHelper logger) : base(logger)
{
}
[Fact]
public async Task SampleStream()
{
if (!EndToEndTestConfig.ShouldRunEndToEndTests)
return;
var stream = _tweetinviTestClient.Streams.CreateSampleStream();
ITweet tweet = null;
StreamStoppedEventArgs streamStoppedEventArgs = null;
stream.TweetReceived += (sender, args) =>
{
tweet = args.Tweet;
_logger.WriteLine("Tweet received!");
_logger.WriteLine(tweet.ToString());
stream.Stop();
};
stream.EventReceived += (sender, args) => { _logger.WriteLine(args.Json); };
stream.StreamStopped += (sender, args) => { streamStoppedEventArgs = args; };
var runStreamTask = Task.Run(async () =>
{
_logger.WriteLine("Before starting stream");
await stream.StartAsync();
_logger.WriteLine("Stream completed");
});
var delayTask = Task.Delay(TimeSpan.FromSeconds(15));
var task = await Task.WhenAny(runStreamTask, delayTask);
if (task != runStreamTask)
{
throw new TimeoutException();
}
_logger.WriteLine(streamStoppedEventArgs.Exception?.ToString() ?? "No exception");
_logger.WriteLine(streamStoppedEventArgs.DisconnectMessage?.ToString() ?? "No disconnect message");
Assert.Null(streamStoppedEventArgs.Exception);
Assert.Null(streamStoppedEventArgs.DisconnectMessage);
Assert.NotNull(tweet);
await Task.Delay(4000); // this is for preventing Enhance Your Calm message from Twitter
}
[Fact]
public async Task FilteredStream()
{
if (!EndToEndTestConfig.ShouldRunEndToEndTests)
return;
var stream = _tweetinviTestClient.Streams.CreateFilteredStream();
stream.AddTrack("twitter");
ITweet tweet = null;
StreamStoppedEventArgs streamStoppedEventArgs = null;
stream.MatchingTweetReceived += (sender, args) =>
{
tweet = args.Tweet;
_logger.WriteLine($"Tweet matched via {args.MatchOn.ToString()}");
_logger.WriteLine(tweet.ToString());
stream.Stop();
};
stream.EventReceived += (sender, args) => { _logger.WriteLine(args.Json); };
stream.StreamStopped += (sender, args) => { streamStoppedEventArgs = args; };
var runStreamTask = Task.Run(async () =>
{
_logger.WriteLine("Before starting stream");
await stream.StartMatchingAllConditionsAsync();
_logger.WriteLine("Stream completed");
});
var delayTask = Task.Delay(TimeSpan.FromSeconds(15));
var task = await Task.WhenAny(runStreamTask, delayTask);
if (task != runStreamTask)
{
throw new TimeoutException();
}
_logger.WriteLine(streamStoppedEventArgs.Exception?.ToString() ?? "No exception");
_logger.WriteLine(streamStoppedEventArgs.DisconnectMessage?.ToString() ?? "No disconnect message");
Assert.Null(streamStoppedEventArgs.Exception);
Assert.Null(streamStoppedEventArgs.DisconnectMessage);
Assert.NotNull(tweet);
await Task.Delay(TimeSpan.FromSeconds(10)); // this is for preventing Enhance Your Calm message from Twitter
}
[Fact]
public async Task FilteredStream_UrlMatching()
{
if (!EndToEndTestConfig.ShouldRunEndToEndTests)
return;
var stream = _tweetinviTestClient.Streams.CreateFilteredStream();
stream.AddTrack("twitter.com");
stream.AddTrack("facebook.com");
stream.AddTrack("amazon.com");
stream.AddTrack("apple.com");
MatchedTweetReceivedEventArgs matchedTweetEvent = null;
stream.MatchingTweetReceived += (sender, args) =>
{
matchedTweetEvent = args;
_logger.WriteLine($"Tweet matched via {args.MatchOn.ToString()}");
_logger.WriteLine(matchedTweetEvent.ToString());
stream.Stop();
};
var runStreamTask = Task.Run(async () =>
{
_logger.WriteLine("Before starting stream");
await stream.StartMatchingAllConditionsAsync();
_logger.WriteLine("Stream completed");
});
// it can take a while before receiving matching tweets
var delayTask = Task.Delay(TimeSpan.FromMinutes(2));
var task = await Task.WhenAny(runStreamTask, delayTask);
if (task != runStreamTask)
{
throw new TimeoutException();
}
Assert.Equal(matchedTweetEvent.MatchOn, MatchOn.URLEntities);
Assert.True(matchedTweetEvent.MatchOn == MatchOn.URLEntities || matchedTweetEvent.QuotedTweetMatchOn == MatchOn.URLEntities);
await Task.Delay(TimeSpan.FromSeconds(10)); // this is for preventing Enhance Your Calm message from Twitter
}
[Fact]
public async Task FilteredStream_UserMentionsMatching()
{
if (!EndToEndTestConfig.ShouldRunEndToEndTests)
return;
var stream = _tweetinviTestClient.Streams.CreateFilteredStream();
stream.AddTrack("@EmmanuelMacron");
MatchedTweetReceivedEventArgs matchedTweetEvent = null;
stream.MatchingTweetReceived += (sender, args) =>
{
matchedTweetEvent = args;
_logger.WriteLine($"Tweet matched via {args.MatchOn.ToString()}");
_logger.WriteLine(matchedTweetEvent.ToString());
stream.Stop();
};
var runStreamTask = Task.Run(async () =>
{
_logger.WriteLine("Before starting stream");
await stream.StartMatchingAllConditionsAsync();
_logger.WriteLine("Stream completed");
});
// it can take a while before receiving matching tweets
var delayTask = Task.Delay(TimeSpan.FromMinutes(2));
var task = await Task.WhenAny(runStreamTask, delayTask);
if (task != runStreamTask)
{
throw new TimeoutException();
}
Assert.Equal(matchedTweetEvent.MatchOn | matchedTweetEvent.QuotedTweetMatchOn | matchedTweetEvent.RetweetMatchOn, MatchOn.TweetText | MatchOn.UserMentionEntities);
await Task.Delay(TimeSpan.FromSeconds(20)); // this is for preventing Enhance Your Calm message from Twitter
}
[Fact]
public async Task FilteredStream_HashtagsMatching()
{
if (!EndToEndTestConfig.ShouldRunEndToEndTests)
return;
var stream = _tweetinviTestClient.Streams.CreateFilteredStream();
stream.AddTrack("#love");
stream.AddTrack("#happy");
MatchedTweetReceivedEventArgs matchedTweetEvent = null;
stream.MatchingTweetReceived += (sender, args) =>
{
matchedTweetEvent = args;
_logger.WriteLine($"Tweet matched via {args.MatchOn.ToString()}");
_logger.WriteLine(matchedTweetEvent.ToString());
stream.Stop();
};
var runStreamTask = Task.Run(async () =>
{
_logger.WriteLine("Before starting stream");
await stream.StartMatchingAllConditionsAsync();
_logger.WriteLine("Stream completed");
});
// it can take a while before receiving matching tweets
var delayTask = Task.Delay(TimeSpan.FromMinutes(2));
var task = await Task.WhenAny(runStreamTask, delayTask);
if (task != runStreamTask)
{
throw new TimeoutException();
}
Assert.Equal(matchedTweetEvent.MatchOn | matchedTweetEvent.QuotedTweetMatchOn | matchedTweetEvent.RetweetMatchOn, MatchOn.TweetText | MatchOn.HashTagEntities);
await Task.Delay(TimeSpan.FromSeconds(10)); // this is for preventing Enhance Your Calm message from Twitter
}
[Fact]
public async Task FilteredStream_CurrencyMatching()
{
if (!EndToEndTestConfig.ShouldRunEndToEndTests)
return;
var stream = _tweetinviTestClient.Streams.CreateFilteredStream();
stream.AddTrack("$USD");
stream.AddTrack("$ETH");
stream.AddTrack("$EUR");
MatchedTweetReceivedEventArgs matchedTweetEvent = null;
stream.MatchingTweetReceived += (sender, args) =>
{
matchedTweetEvent = args;
_logger.WriteLine($"Tweet matched via {args.MatchOn.ToString()}");
_logger.WriteLine(matchedTweetEvent.ToString());
stream.Stop();
};
var runStreamTask = Task.Run(async () =>
{
_logger.WriteLine("Before starting stream");
await stream.StartMatchingAllConditionsAsync();
_logger.WriteLine("Stream completed");
});
// it can take a while before receiving matching tweets
var delayTask = Task.Delay(TimeSpan.FromMinutes(2));
var task = await Task.WhenAny(runStreamTask, delayTask);
if (task != runStreamTask)
{
throw new TimeoutException();
}
Assert.Equal(matchedTweetEvent.MatchOn | matchedTweetEvent.RetweetMatchOn, MatchOn.TweetText | MatchOn.SymbolEntities);
await Task.Delay(TimeSpan.FromSeconds(10)); // this is for preventing Enhance Your Calm message from Twitter
}
[Fact]
public async Task TweetStream()
{
if (!EndToEndTestConfig.ShouldRunEndToEndTests)
return;
var stream = _tweetinviTestClient.Streams.CreateTweetStream();
ITweet tweet = null;
StreamStoppedEventArgs streamStoppedEventArgs = null;
stream.TweetReceived += (sender, args) =>
{
tweet = args.Tweet;
_logger.WriteLine(tweet.ToString());
stream.Stop();
};
stream.EventReceived += (sender, args) => { _logger.WriteLine(args.Json); };
stream.StreamStopped += (sender, args) => { streamStoppedEventArgs = args; };
var runStreamTask = Task.Run(async () =>
{
_logger.WriteLine("Before starting stream");
await stream.StartAsync("https://stream.twitter.com/1.1/statuses/sample.json");
_logger.WriteLine("Stream completed");
});
var delayTask = Task.Delay(TimeSpan.FromSeconds(15));
var task = await Task.WhenAny(runStreamTask, delayTask);
if (task != runStreamTask)
{
throw new TimeoutException();
}
_logger.WriteLine(streamStoppedEventArgs.Exception?.ToString() ?? "No exception");
_logger.WriteLine(streamStoppedEventArgs.DisconnectMessage?.ToString() ?? "No disconnect message");
Assert.Null(streamStoppedEventArgs.Exception);
Assert.Null(streamStoppedEventArgs.DisconnectMessage);
Assert.NotNull(tweet);
await Task.Delay(4000); // this is for preventing Enhance Your Calm message from Twitter
}
[Fact]
public async Task TrackedStreamAsync()
{
if (!EndToEndTestConfig.ShouldRunEndToEndTests)
return;
var stream = _tweetinviTestClient.Streams.CreateTrackedTweetStream();
stream.AddTrack("twitter");
ITweet tweet = null;
StreamStoppedEventArgs streamStoppedEventArgs = null;
stream.MatchingTweetReceived += (sender, args) =>
{
tweet = args.Tweet;
_logger.WriteLine($"Tweet matched via {args.MatchOn.ToString()}");
_logger.WriteLine(tweet.ToString());
stream.Stop();
};
stream.EventReceived += (sender, args) => { _logger.WriteLine(args.Json); };
stream.StreamStopped += (sender, args) => { streamStoppedEventArgs = args; };
var runStreamTask = Task.Run(async () =>
{
_logger.WriteLine("Before starting stream");
await stream.StartAsync("https://stream.twitter.com/1.1/statuses/filter.json?track=twitter");
_logger.WriteLine("Stream completed");
});
var delayTask = Task.Delay(TimeSpan.FromSeconds(15));
var task = await Task.WhenAny(runStreamTask, delayTask);
if (task != runStreamTask)
{
throw new TimeoutException();
}
_logger.WriteLine(streamStoppedEventArgs.Exception?.ToString() ?? "No exception");
_logger.WriteLine(streamStoppedEventArgs.DisconnectMessage?.ToString() ?? "No disconnect message");
Assert.Null(streamStoppedEventArgs.Exception);
Assert.Null(streamStoppedEventArgs.DisconnectMessage);
Assert.NotNull(tweet);
await Task.Delay(4000); // this is for preventing Enhance Your Calm message from Twitter
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using Hyak.Common;
using Microsoft.WindowsAzure.Management.RemoteApp.Models;
namespace Microsoft.WindowsAzure.Management.RemoteApp.Models
{
/// <summary>
/// Details of a template image.
/// </summary>
public partial class TemplateImage
{
private string _id;
/// <summary>
/// Optional. The unique identifier for the image.
/// </summary>
public string Id
{
get { return this._id; }
set { this._id = value; }
}
private string _name;
/// <summary>
/// Optional. The friendly name for the image.
/// </summary>
public string Name
{
get { return this._name; }
set { this._name = value; }
}
private int _numberOfLinkedCollections;
/// <summary>
/// Optional. The number of collections using this image.
/// </summary>
public int NumberOfLinkedCollections
{
get { return this._numberOfLinkedCollections; }
set { this._numberOfLinkedCollections = value; }
}
private OfficeType _officeType;
/// <summary>
/// Optional. For platform template images, the type of Office which is
/// included in the image.
/// </summary>
public OfficeType OfficeType
{
get { return this._officeType; }
set { this._officeType = value; }
}
private string _pathOnClient;
/// <summary>
/// Optional. The path of the image on the client.
/// </summary>
public string PathOnClient
{
get { return this._pathOnClient; }
set { this._pathOnClient = value; }
}
private IList<string> _regionList;
/// <summary>
/// Optional. The list of regions where the image can be used.
/// </summary>
public IList<string> RegionList
{
get { return this._regionList; }
set { this._regionList = value; }
}
private string _sas;
/// <summary>
/// Optional. The image upload SAS key.
/// </summary>
public string Sas
{
get { return this._sas; }
set { this._sas = value; }
}
private DateTime _sasExpiry;
/// <summary>
/// Optional. The time when the image upload SAS key will expire.
/// </summary>
public DateTime SasExpiry
{
get { return this._sasExpiry; }
set { this._sasExpiry = value; }
}
private long _size;
/// <summary>
/// Optional. The image size in bytes.
/// </summary>
public long Size
{
get { return this._size; }
set { this._size = value; }
}
private TemplateImageStatus _status;
/// <summary>
/// Optional. The image status.
/// </summary>
public TemplateImageStatus Status
{
get { return this._status; }
set { this._status = value; }
}
private bool _trialOnly;
/// <summary>
/// Optional. A TrialOnly platform template image may be used only
/// during a subscription's RemoteApp trial period. Once billing is
/// activated, a collection using a TrialOnly image will be
/// permanently disabled.
/// </summary>
public bool TrialOnly
{
get { return this._trialOnly; }
set { this._trialOnly = value; }
}
private TemplateImageType _type;
/// <summary>
/// Optional. The type of the template image.
/// </summary>
public TemplateImageType Type
{
get { return this._type; }
set { this._type = value; }
}
private DateTime _uploadCompleteTime;
/// <summary>
/// Optional. The time when the image upload was completed.
/// </summary>
public DateTime UploadCompleteTime
{
get { return this._uploadCompleteTime; }
set { this._uploadCompleteTime = value; }
}
private DateTime _uploadSetupTime;
/// <summary>
/// Optional. The time when the image upload parameters were set.
/// </summary>
public DateTime UploadSetupTime
{
get { return this._uploadSetupTime; }
set { this._uploadSetupTime = value; }
}
private DateTime _uploadStartTime;
/// <summary>
/// Optional. The time when the image upload was started.
/// </summary>
public DateTime UploadStartTime
{
get { return this._uploadStartTime; }
set { this._uploadStartTime = value; }
}
private string _uri;
/// <summary>
/// Optional. The image upload endpoint URI.
/// </summary>
public string Uri
{
get { return this._uri; }
set { this._uri = value; }
}
/// <summary>
/// Initializes a new instance of the TemplateImage class.
/// </summary>
public TemplateImage()
{
this.RegionList = new LazyList<string>();
}
}
}
| |
//
// This file was generated by the BinaryNotes compiler.
// See http://bnotes.sourceforge.net
// Any modifications to this file will be lost upon recompilation of the source ASN.1.
//
using GSF.ASN1;
using GSF.ASN1.Attributes;
using GSF.ASN1.Coders;
using GSF.ASN1.Types;
namespace GSF.MMS.Model
{
[ASN1PreparedElement]
[ASN1BoxedType(Name = "CS_Start_Request")]
public class CS_Start_Request : IASN1PreparedElement
{
private static readonly IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(CS_Start_Request));
private CS_Start_RequestChoiceType val;
[ASN1Element(Name = "CS-Start-Request", IsOptional = false, HasTag = true, Tag = 0, HasDefaultValue = false)]
public CS_Start_RequestChoiceType Value
{
get
{
return val;
}
set
{
val = value;
}
}
public void initWithDefaults()
{
}
public IASN1PreparedElementData PreparedData
{
get
{
return preparedData;
}
}
[ASN1PreparedElement]
[ASN1Choice(Name = "CS-Start-Request")]
public class CS_Start_RequestChoiceType : IASN1PreparedElement
{
private static IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(CS_Start_RequestChoiceType));
private ControllingSequenceType controlling_;
private bool controlling_selected;
private NullObject normal_;
private bool normal_selected;
[ASN1Null(Name = "normal")]
[ASN1Element(Name = "normal", IsOptional = false, HasTag = false, HasDefaultValue = false)]
public NullObject Normal
{
get
{
return normal_;
}
set
{
selectNormal(value);
}
}
[ASN1Element(Name = "controlling", IsOptional = false, HasTag = false, HasDefaultValue = false)]
public ControllingSequenceType Controlling
{
get
{
return controlling_;
}
set
{
selectControlling(value);
}
}
public void initWithDefaults()
{
}
public IASN1PreparedElementData PreparedData
{
get
{
return preparedData;
}
}
public bool isNormalSelected()
{
return normal_selected;
}
public void selectNormal()
{
selectNormal(new NullObject());
}
public void selectNormal(NullObject val)
{
normal_ = val;
normal_selected = true;
controlling_selected = false;
}
public bool isControllingSelected()
{
return controlling_selected;
}
public void selectControlling(ControllingSequenceType val)
{
controlling_ = val;
controlling_selected = true;
normal_selected = false;
}
[ASN1PreparedElement]
[ASN1Sequence(Name = "controlling", IsSet = false)]
public class ControllingSequenceType : IASN1PreparedElement
{
private static IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(ControllingSequenceType));
private StartCount startCount_;
private string startLocation_;
private bool startLocation_present;
[ASN1String(Name = "",
StringType = UniversalTags.VisibleString, IsUCS = false)]
[ASN1Element(Name = "startLocation", IsOptional = true, HasTag = true, Tag = 0, HasDefaultValue = false)]
public string StartLocation
{
get
{
return startLocation_;
}
set
{
startLocation_ = value;
startLocation_present = true;
}
}
[ASN1Element(Name = "startCount", IsOptional = false, HasTag = true, Tag = 1, HasDefaultValue = true)]
public StartCount StartCount
{
get
{
return startCount_;
}
set
{
startCount_ = value;
}
}
public void initWithDefaults()
{
StartCount param_StartCount =
null;
StartCount = param_StartCount;
}
public IASN1PreparedElementData PreparedData
{
get
{
return preparedData;
}
}
public bool isStartLocationPresent()
{
return startLocation_present;
}
}
}
}
}
| |
// 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.Diagnostics;
using System.IO;
using System.IO.Pipelines;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Connections;
namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http
{
/// <summary>
/// http://tools.ietf.org/html/rfc2616#section-3.6.1
/// </summary>
internal sealed class Http1ChunkedEncodingMessageBody : Http1MessageBody
{
// byte consts don't have a data type annotation so we pre-cast it
private const byte ByteCR = (byte)'\r';
// "7FFFFFFF\r\n" is the largest chunk size that could be returned as an int.
private const int MaxChunkPrefixBytes = 10;
private long _inputLength;
private Mode _mode = Mode.Prefix;
private volatile bool _canceled;
private Task? _pumpTask;
private readonly Pipe _requestBodyPipe;
private ReadResult _readResult;
public Http1ChunkedEncodingMessageBody(Http1Connection context, bool keepAlive)
: base(context, keepAlive)
{
_requestBodyPipe = CreateRequestBodyPipe(context);
}
public override void AdvanceTo(SequencePosition consumed, SequencePosition examined)
{
TrackConsumedAndExaminedBytes(_readResult, consumed, examined);
_requestBodyPipe.Reader.AdvanceTo(consumed, examined);
}
public override bool TryReadInternal(out ReadResult readResult)
{
TryStartAsync();
var boolResult = _requestBodyPipe.Reader.TryRead(out _readResult);
readResult = _readResult;
CountBytesRead(readResult.Buffer.Length);
if (_readResult.IsCompleted)
{
TryStop();
}
return boolResult;
}
public override async ValueTask<ReadResult> ReadAsyncInternal(CancellationToken cancellationToken = default)
{
await TryStartAsync();
try
{
var readAwaitable = _requestBodyPipe.Reader.ReadAsync(cancellationToken);
_readResult = await StartTimingReadAsync(readAwaitable, cancellationToken);
}
catch (ConnectionAbortedException ex)
{
throw new TaskCanceledException("The request was aborted", ex);
}
StopTimingRead(_readResult.Buffer.Length);
if (_readResult.IsCompleted)
{
TryStop();
}
return _readResult;
}
public override void CancelPendingRead()
{
_requestBodyPipe.Reader.CancelPendingRead();
}
private async Task PumpAsync()
{
Debug.Assert(!RequestUpgrade, "Upgraded connections should never use this code path!");
Exception? error = null;
try
{
var awaitable = _context.Input.ReadAsync();
if (!awaitable.IsCompleted)
{
await TryProduceContinueAsync();
}
while (true)
{
var result = await awaitable;
if (_context.RequestTimedOut)
{
KestrelBadHttpRequestException.Throw(RequestRejectionReason.RequestBodyTimeout);
}
var readableBuffer = result.Buffer;
var consumed = readableBuffer.Start;
var examined = readableBuffer.Start;
try
{
if (_canceled)
{
break;
}
if (!readableBuffer.IsEmpty)
{
bool done;
done = Read(readableBuffer, _requestBodyPipe.Writer, out consumed, out examined);
await _requestBodyPipe.Writer.FlushAsync();
if (done)
{
break;
}
}
// Read() will have already have greedily consumed the entire request body if able.
if (result.IsCompleted)
{
ThrowUnexpectedEndOfRequestContent();
}
}
finally
{
_context.Input.AdvanceTo(consumed, examined);
}
awaitable = _context.Input.ReadAsync();
}
}
catch (Exception ex)
{
error = ex;
}
finally
{
await _requestBodyPipe.Writer.CompleteAsync(error);
}
}
protected override ValueTask OnStopAsync()
{
if (!_context.HasStartedConsumingRequestBody)
{
return default;
}
// call complete here on the reader
_requestBodyPipe.Reader.Complete();
Debug.Assert(_pumpTask != null, "OnReadStartedAsync must have been called.");
// PumpTask catches all Exceptions internally.
if (_pumpTask.IsCompleted)
{
// At this point both the request body pipe reader and writer should be completed.
_requestBodyPipe.Reset();
return default;
}
// Should I call complete here?
return StopAsyncAwaited(_pumpTask);
}
private async ValueTask StopAsyncAwaited(Task pumpTask)
{
_canceled = true;
_context.Input.CancelPendingRead();
await pumpTask;
// At this point both the request body pipe reader and writer should be completed.
_requestBodyPipe.Reset();
}
protected override Task OnReadStartedAsync()
{
_pumpTask = PumpAsync();
return Task.CompletedTask;
}
private bool Read(ReadOnlySequence<byte> readableBuffer, PipeWriter writableBuffer, out SequencePosition consumed, out SequencePosition examined)
{
consumed = default;
examined = default;
while (_mode < Mode.Trailer)
{
if (_mode == Mode.Prefix)
{
ParseChunkedPrefix(readableBuffer, out consumed, out examined);
if (_mode == Mode.Prefix)
{
return false;
}
readableBuffer = readableBuffer.Slice(consumed);
}
if (_mode == Mode.Extension)
{
ParseExtension(readableBuffer, out consumed, out examined);
if (_mode == Mode.Extension)
{
return false;
}
readableBuffer = readableBuffer.Slice(consumed);
}
if (_mode == Mode.Data)
{
ReadChunkedData(readableBuffer, writableBuffer, out consumed, out examined);
if (_mode == Mode.Data)
{
return false;
}
readableBuffer = readableBuffer.Slice(consumed);
}
if (_mode == Mode.Suffix)
{
ParseChunkedSuffix(readableBuffer, out consumed, out examined);
if (_mode == Mode.Suffix)
{
return false;
}
readableBuffer = readableBuffer.Slice(consumed);
}
}
// Chunks finished, parse trailers
if (_mode == Mode.Trailer)
{
ParseChunkedTrailer(readableBuffer, out consumed, out examined);
if (_mode == Mode.Trailer)
{
return false;
}
readableBuffer = readableBuffer.Slice(consumed);
}
// _consumedBytes aren't tracked for trailer headers, since headers have separate limits.
if (_mode == Mode.TrailerHeaders)
{
var reader = new SequenceReader<byte>(readableBuffer);
if (_context.TakeMessageHeaders(ref reader, trailers: true))
{
examined = reader.Position;
_mode = Mode.Complete;
}
else
{
examined = readableBuffer.End;
}
consumed = reader.Position;
}
return _mode == Mode.Complete;
}
private void ParseChunkedPrefix(in ReadOnlySequence<byte> buffer, out SequencePosition consumed, out SequencePosition examined)
{
consumed = buffer.Start;
var reader = new SequenceReader<byte>(buffer);
if (!reader.TryRead(out var ch1) || !reader.TryRead(out var ch2))
{
examined = reader.Position;
return;
}
// Advance examined before possibly throwing, so we don't risk examining less than the previous call to ParseChunkedPrefix.
examined = reader.Position;
var chunkSize = CalculateChunkSize(ch1, 0);
ch1 = ch2;
while (reader.Consumed < MaxChunkPrefixBytes)
{
if (ch1 == ';')
{
consumed = reader.Position;
examined = reader.Position;
AddAndCheckObservedBytes(reader.Consumed);
_inputLength = chunkSize;
_mode = Mode.Extension;
return;
}
if (!reader.TryRead(out ch2))
{
examined = reader.Position;
return;
}
// Advance examined before possibly throwing, so we don't risk examining less than the previous call to ParseChunkedPrefix.
examined = reader.Position;
if (ch1 == '\r' && ch2 == '\n')
{
consumed = reader.Position;
AddAndCheckObservedBytes(reader.Consumed);
_inputLength = chunkSize;
_mode = chunkSize > 0 ? Mode.Data : Mode.Trailer;
return;
}
chunkSize = CalculateChunkSize(ch1, chunkSize);
ch1 = ch2;
}
// At this point, 10 bytes have been consumed which is enough to parse the max value "7FFFFFFF\r\n".
KestrelBadHttpRequestException.Throw(RequestRejectionReason.BadChunkSizeData);
}
private void ParseExtension(ReadOnlySequence<byte> buffer, out SequencePosition consumed, out SequencePosition examined)
{
// Chunk-extensions not currently parsed
// Just drain the data
examined = buffer.Start;
do
{
SequencePosition? extensionCursorPosition = buffer.PositionOf(ByteCR);
if (extensionCursorPosition == null)
{
// End marker not found yet
consumed = buffer.End;
examined = buffer.End;
AddAndCheckObservedBytes(buffer.Length);
return;
};
var extensionCursor = extensionCursorPosition.Value;
var charsToByteCRExclusive = buffer.Slice(0, extensionCursor).Length;
var suffixBuffer = buffer.Slice(extensionCursor);
if (suffixBuffer.Length < 2)
{
consumed = extensionCursor;
examined = buffer.End;
AddAndCheckObservedBytes(charsToByteCRExclusive);
return;
}
suffixBuffer = suffixBuffer.Slice(0, 2);
var suffixSpan = suffixBuffer.ToSpan();
if (suffixSpan[1] == '\n')
{
// We consumed the \r\n at the end of the extension, so switch modes.
_mode = _inputLength > 0 ? Mode.Data : Mode.Trailer;
consumed = suffixBuffer.End;
examined = suffixBuffer.End;
AddAndCheckObservedBytes(charsToByteCRExclusive + 2);
}
else
{
// Don't consume suffixSpan[1] in case it is also a \r.
buffer = buffer.Slice(charsToByteCRExclusive + 1);
consumed = extensionCursor;
AddAndCheckObservedBytes(charsToByteCRExclusive + 1);
}
} while (_mode == Mode.Extension);
}
private void ReadChunkedData(in ReadOnlySequence<byte> buffer, PipeWriter writableBuffer, out SequencePosition consumed, out SequencePosition examined)
{
var actual = Math.Min(buffer.Length, _inputLength);
consumed = buffer.GetPosition(actual);
examined = consumed;
buffer.Slice(0, actual).CopyTo(writableBuffer);
_inputLength -= actual;
AddAndCheckObservedBytes(actual);
if (_inputLength == 0)
{
_mode = Mode.Suffix;
}
}
private void ParseChunkedSuffix(in ReadOnlySequence<byte> buffer, out SequencePosition consumed, out SequencePosition examined)
{
consumed = buffer.Start;
if (buffer.Length < 2)
{
examined = buffer.End;
return;
}
var suffixBuffer = buffer.Slice(0, 2);
var suffixSpan = suffixBuffer.ToSpan();
// Advance examined before possibly throwing, so we don't risk examining less than the previous call to ParseChunkedSuffix.
examined = suffixBuffer.End;
if (suffixSpan[0] == '\r' && suffixSpan[1] == '\n')
{
consumed = suffixBuffer.End;
AddAndCheckObservedBytes(2);
_mode = Mode.Prefix;
}
else
{
KestrelBadHttpRequestException.Throw(RequestRejectionReason.BadChunkSuffix);
}
}
private void ParseChunkedTrailer(in ReadOnlySequence<byte> buffer, out SequencePosition consumed, out SequencePosition examined)
{
consumed = buffer.Start;
if (buffer.Length < 2)
{
examined = buffer.End;
return;
}
var trailerBuffer = buffer.Slice(0, 2);
var trailerSpan = trailerBuffer.ToSpan();
// Advance examined before possibly throwing, so we don't risk examining less than the previous call to ParseChunkedTrailer.
examined = trailerBuffer.End;
if (trailerSpan[0] == '\r' && trailerSpan[1] == '\n')
{
consumed = trailerBuffer.End;
AddAndCheckObservedBytes(2);
_mode = Mode.Complete;
// No trailers
_context.OnTrailersComplete();
}
else
{
_mode = Mode.TrailerHeaders;
}
}
private static int CalculateChunkSize(int extraHexDigit, int currentParsedSize)
{
try
{
checked
{
if (extraHexDigit >= '0' && extraHexDigit <= '9')
{
return currentParsedSize * 0x10 + (extraHexDigit - '0');
}
else if (extraHexDigit >= 'A' && extraHexDigit <= 'F')
{
return currentParsedSize * 0x10 + (extraHexDigit - ('A' - 10));
}
else if (extraHexDigit >= 'a' && extraHexDigit <= 'f')
{
return currentParsedSize * 0x10 + (extraHexDigit - ('a' - 10));
}
}
}
catch (OverflowException ex)
{
throw new IOException(CoreStrings.BadRequest_BadChunkSizeData, ex);
}
KestrelBadHttpRequestException.Throw(RequestRejectionReason.BadChunkSizeData);
return -1; // can't happen, but compiler complains
}
private enum Mode
{
Prefix,
Extension,
Data,
Suffix,
Trailer,
TrailerHeaders,
Complete
};
private static Pipe CreateRequestBodyPipe(Http1Connection context)
=> new Pipe(new PipeOptions
(
pool: context.MemoryPool,
readerScheduler: context.ServiceContext.Scheduler,
writerScheduler: PipeScheduler.Inline,
pauseWriterThreshold: 1,
resumeWriterThreshold: 1,
useSynchronizationContext: false,
minimumSegmentSize: context.MemoryPool.GetMinimumSegmentSize()
));
}
}
| |
//
// Author:
// Jb Evain ([email protected])
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
using System.Collections.Generic;
using Mono.Collections.Generic;
using SR = System.Reflection;
using Mono.Cecil.Metadata;
namespace Mono.Cecil {
enum ImportGenericKind {
Definition,
Open,
}
struct ImportGenericContext {
Collection<IGenericParameterProvider> stack;
public bool IsEmpty { get { return stack == null; } }
public ImportGenericContext (IGenericParameterProvider provider)
{
stack = null;
Push (provider);
}
public void Push (IGenericParameterProvider provider)
{
if (stack == null)
stack = new Collection<IGenericParameterProvider> (1) { provider };
else
stack.Add (provider);
}
public void Pop ()
{
stack.RemoveAt (stack.Count - 1);
}
public TypeReference MethodParameter (string method, int position)
{
for (int i = stack.Count - 1; i >= 0; i--) {
var candidate = stack [i] as MethodReference;
if (candidate == null)
continue;
if (method != candidate.Name)
continue;
return candidate.GenericParameters [position];
}
throw new InvalidOperationException ();
}
public TypeReference TypeParameter (string type, int position)
{
for (int i = stack.Count - 1; i >= 0; i--) {
var candidate = GenericTypeFor (stack [i]);
if (candidate.FullName != type)
continue;
return candidate.GenericParameters [position];
}
throw new InvalidOperationException ();
}
static TypeReference GenericTypeFor (IGenericParameterProvider context)
{
var type = context as TypeReference;
if (type != null)
return type.GetElementType ();
var method = context as MethodReference;
if (method != null)
return method.DeclaringType.GetElementType ();
throw new InvalidOperationException ();
}
}
class MetadataImporter {
readonly ModuleDefinition module;
public MetadataImporter (ModuleDefinition module)
{
this.module = module;
}
#if !CF
static readonly Dictionary<Type, ElementType> type_etype_mapping = new Dictionary<Type, ElementType> (18) {
{ typeof (void), ElementType.Void },
{ typeof (bool), ElementType.Boolean },
{ typeof (char), ElementType.Char },
{ typeof (sbyte), ElementType.I1 },
{ typeof (byte), ElementType.U1 },
{ typeof (short), ElementType.I2 },
{ typeof (ushort), ElementType.U2 },
{ typeof (int), ElementType.I4 },
{ typeof (uint), ElementType.U4 },
{ typeof (long), ElementType.I8 },
{ typeof (ulong), ElementType.U8 },
{ typeof (float), ElementType.R4 },
{ typeof (double), ElementType.R8 },
{ typeof (string), ElementType.String },
{ typeof (TypedReference), ElementType.TypedByRef },
{ typeof (IntPtr), ElementType.I },
{ typeof (UIntPtr), ElementType.U },
{ typeof (object), ElementType.Object },
};
public TypeReference ImportType (Type type, ImportGenericContext context)
{
return ImportType (type, context, ImportGenericKind.Open);
}
public TypeReference ImportType (Type type, ImportGenericContext context, ImportGenericKind import_kind)
{
if (IsTypeSpecification (type) || ImportOpenGenericType (type, import_kind))
return ImportTypeSpecification (type, context);
var reference = new TypeReference (
string.Empty,
type.Name,
module,
ImportScope (type.Assembly),
type.IsValueType);
reference.etype = ImportElementType (type);
if (IsNestedType (type))
reference.DeclaringType = ImportType (type.DeclaringType, context, import_kind);
else
reference.Namespace = type.Namespace ?? string.Empty;
if (type.IsGenericType)
ImportGenericParameters (reference, type.GetGenericArguments ());
return reference;
}
static bool ImportOpenGenericType (Type type, ImportGenericKind import_kind)
{
return type.IsGenericType && type.IsGenericTypeDefinition && import_kind == ImportGenericKind.Open;
}
static bool ImportOpenGenericMethod (SR.MethodBase method, ImportGenericKind import_kind)
{
return method.IsGenericMethod && method.IsGenericMethodDefinition && import_kind == ImportGenericKind.Open;
}
static bool IsNestedType (Type type)
{
#if !SILVERLIGHT
return type.IsNested;
#else
return type.DeclaringType != null;
#endif
}
TypeReference ImportTypeSpecification (Type type, ImportGenericContext context)
{
if (type.IsByRef)
return new ByReferenceType (ImportType (type.GetElementType (), context));
if (type.IsPointer)
return new PointerType (ImportType (type.GetElementType (), context));
if (type.IsArray)
return new ArrayType (ImportType (type.GetElementType (), context), type.GetArrayRank ());
if (type.IsGenericType)
return ImportGenericInstance (type, context);
if (type.IsGenericParameter)
return ImportGenericParameter (type, context);
throw new NotSupportedException (type.FullName);
}
static TypeReference ImportGenericParameter (Type type, ImportGenericContext context)
{
if (context.IsEmpty)
throw new InvalidOperationException ();
if (type.DeclaringMethod != null)
return context.MethodParameter (type.DeclaringMethod.Name, type.GenericParameterPosition);
if (type.DeclaringType != null)
return context.TypeParameter (NormalizedFullName (type.DeclaringType), type.GenericParameterPosition);
throw new InvalidOperationException();
}
private static string NormalizedFullName (Type type)
{
if (IsNestedType (type))
return NormalizedFullName (type.DeclaringType) + "/" + type.Name;
return type.FullName;
}
TypeReference ImportGenericInstance (Type type, ImportGenericContext context)
{
var element_type = ImportType (type.GetGenericTypeDefinition (), context, ImportGenericKind.Definition);
var instance = new GenericInstanceType (element_type);
var arguments = type.GetGenericArguments ();
var instance_arguments = instance.GenericArguments;
context.Push (element_type);
try {
for (int i = 0; i < arguments.Length; i++)
instance_arguments.Add (ImportType (arguments [i], context));
return instance;
} finally {
context.Pop ();
}
}
static bool IsTypeSpecification (Type type)
{
return type.HasElementType
|| IsGenericInstance (type)
|| type.IsGenericParameter;
}
static bool IsGenericInstance (Type type)
{
return type.IsGenericType && !type.IsGenericTypeDefinition;
}
static ElementType ImportElementType (Type type)
{
ElementType etype;
if (!type_etype_mapping.TryGetValue (type, out etype))
return ElementType.None;
return etype;
}
AssemblyNameReference ImportScope (SR.Assembly assembly)
{
AssemblyNameReference scope;
#if !SILVERLIGHT
var name = assembly.GetName ();
if (TryGetAssemblyNameReference (name, out scope))
return scope;
scope = new AssemblyNameReference (name.Name, name.Version) {
Culture = name.CultureInfo.Name,
PublicKeyToken = name.GetPublicKeyToken (),
HashAlgorithm = (AssemblyHashAlgorithm) name.HashAlgorithm,
};
module.AssemblyReferences.Add (scope);
return scope;
#else
var name = AssemblyNameReference.Parse (assembly.FullName);
if (TryGetAssemblyNameReference (name, out scope))
return scope;
module.AssemblyReferences.Add (name);
return name;
#endif
}
#if !SILVERLIGHT
bool TryGetAssemblyNameReference (SR.AssemblyName name, out AssemblyNameReference assembly_reference)
{
var references = module.AssemblyReferences;
for (int i = 0; i < references.Count; i++) {
var reference = references [i];
if (name.FullName != reference.FullName) // TODO compare field by field
continue;
assembly_reference = reference;
return true;
}
assembly_reference = null;
return false;
}
#endif
public FieldReference ImportField (SR.FieldInfo field, ImportGenericContext context)
{
var declaring_type = ImportType (field.DeclaringType, context);
if (IsGenericInstance (field.DeclaringType))
field = ResolveFieldDefinition (field);
context.Push (declaring_type);
try {
return new FieldReference {
Name = field.Name,
DeclaringType = declaring_type,
FieldType = ImportType (field.FieldType, context),
};
} finally {
context.Pop ();
}
}
static SR.FieldInfo ResolveFieldDefinition (SR.FieldInfo field)
{
#if !SILVERLIGHT
return field.Module.ResolveField (field.MetadataToken);
#else
return field.DeclaringType.GetGenericTypeDefinition ().GetField (field.Name,
SR.BindingFlags.Public
| SR.BindingFlags.NonPublic
| (field.IsStatic ? SR.BindingFlags.Static : SR.BindingFlags.Instance));
#endif
}
public MethodReference ImportMethod (SR.MethodBase method, ImportGenericContext context, ImportGenericKind import_kind)
{
if (IsMethodSpecification (method) || ImportOpenGenericMethod (method, import_kind))
return ImportMethodSpecification (method, context);
var declaring_type = ImportType (method.DeclaringType, context);
if (IsGenericInstance (method.DeclaringType))
method = method.Module.ResolveMethod (method.MetadataToken);
var reference = new MethodReference {
Name = method.Name,
HasThis = HasCallingConvention (method, SR.CallingConventions.HasThis),
ExplicitThis = HasCallingConvention (method, SR.CallingConventions.ExplicitThis),
DeclaringType = ImportType (method.DeclaringType, context, ImportGenericKind.Definition),
};
if (HasCallingConvention (method, SR.CallingConventions.VarArgs))
reference.CallingConvention &= MethodCallingConvention.VarArg;
if (method.IsGenericMethod)
ImportGenericParameters (reference, method.GetGenericArguments ());
context.Push (reference);
try {
var method_info = method as SR.MethodInfo;
reference.ReturnType = method_info != null
? ImportType (method_info.ReturnType, context)
: ImportType (typeof (void), default (ImportGenericContext));
var parameters = method.GetParameters ();
var reference_parameters = reference.Parameters;
for (int i = 0; i < parameters.Length; i++)
reference_parameters.Add (
new ParameterDefinition (ImportType (parameters [i].ParameterType, context)));
reference.DeclaringType = declaring_type;
return reference;
} finally {
context.Pop ();
}
}
static void ImportGenericParameters (IGenericParameterProvider provider, Type [] arguments)
{
var provider_parameters = provider.GenericParameters;
for (int i = 0; i < arguments.Length; i++)
provider_parameters.Add (new GenericParameter (arguments [i].Name, provider));
}
static bool IsMethodSpecification (SR.MethodBase method)
{
return method.IsGenericMethod && !method.IsGenericMethodDefinition;
}
MethodReference ImportMethodSpecification (SR.MethodBase method, ImportGenericContext context)
{
var method_info = method as SR.MethodInfo;
if (method_info == null)
throw new InvalidOperationException ();
var element_method = ImportMethod (method_info.GetGenericMethodDefinition (), context, ImportGenericKind.Definition);
var instance = new GenericInstanceMethod (element_method);
var arguments = method.GetGenericArguments ();
var instance_arguments = instance.GenericArguments;
context.Push (element_method);
try {
for (int i = 0; i < arguments.Length; i++)
instance_arguments.Add (ImportType (arguments [i], context));
return instance;
} finally {
context.Pop ();
}
}
static bool HasCallingConvention (SR.MethodBase method, SR.CallingConventions conventions)
{
return (method.CallingConvention & conventions) != 0;
}
#endif
public virtual TypeReference ImportType (TypeReference type, ImportGenericContext context)
{
if (type.IsTypeSpecification ())
return ImportTypeSpecification (type, context);
var reference = new TypeReference (
type.Namespace,
type.Name,
module,
ImportScope (type.Scope),
type.IsValueType);
MetadataSystem.TryProcessPrimitiveTypeReference (reference);
if (type.IsNested)
reference.DeclaringType = ImportType (type.DeclaringType, context);
if (type.HasGenericParameters)
ImportGenericParameters (reference, type);
return reference;
}
IMetadataScope ImportScope (IMetadataScope scope)
{
switch (scope.MetadataScopeType) {
case MetadataScopeType.AssemblyNameReference:
return ImportAssemblyName ((AssemblyNameReference) scope);
case MetadataScopeType.ModuleDefinition:
if (scope == module) return scope;
return ImportAssemblyName (((ModuleDefinition) scope).Assembly.Name);
case MetadataScopeType.ModuleReference:
throw new NotImplementedException ();
}
throw new NotSupportedException ();
}
protected virtual AssemblyNameReference ImportAssemblyName (AssemblyNameReference name)
{
AssemblyNameReference reference;
if (TryGetAssemblyNameReference (name, out reference))
return reference;
reference = new AssemblyNameReference (name.Name, name.Version) {
Culture = name.Culture,
HashAlgorithm = name.HashAlgorithm,
IsRetargetable = name.IsRetargetable
};
var pk_token = !name.PublicKeyToken.IsNullOrEmpty ()
? new byte [name.PublicKeyToken.Length]
: Empty<byte>.Array;
if (pk_token.Length > 0)
Buffer.BlockCopy (name.PublicKeyToken, 0, pk_token, 0, pk_token.Length);
reference.PublicKeyToken = pk_token;
module.AssemblyReferences.Add (reference);
return reference;
}
bool TryGetAssemblyNameReference (AssemblyNameReference name_reference, out AssemblyNameReference assembly_reference)
{
var references = module.AssemblyReferences;
for (int i = 0; i < references.Count; i++) {
var reference = references [i];
if (name_reference.FullName != reference.FullName) // TODO compare field by field
continue;
assembly_reference = reference;
return true;
}
assembly_reference = null;
return false;
}
static void ImportGenericParameters (IGenericParameterProvider imported, IGenericParameterProvider original)
{
var parameters = original.GenericParameters;
var imported_parameters = imported.GenericParameters;
for (int i = 0; i < parameters.Count; i++)
imported_parameters.Add (new GenericParameter (parameters [i].Name, imported));
}
TypeReference ImportTypeSpecification (TypeReference type, ImportGenericContext context)
{
switch (type.etype) {
case ElementType.SzArray:
var vector = (ArrayType) type;
return new ArrayType (ImportType (vector.ElementType, context));
case ElementType.Ptr:
var pointer = (PointerType) type;
return new PointerType (ImportType (pointer.ElementType, context));
case ElementType.ByRef:
var byref = (ByReferenceType) type;
return new ByReferenceType (ImportType (byref.ElementType, context));
case ElementType.Pinned:
var pinned = (PinnedType) type;
return new PinnedType (ImportType (pinned.ElementType, context));
case ElementType.Sentinel:
var sentinel = (SentinelType) type;
return new SentinelType (ImportType (sentinel.ElementType, context));
case ElementType.CModOpt:
var modopt = (OptionalModifierType) type;
return new OptionalModifierType (
ImportType (modopt.ModifierType, context),
ImportType (modopt.ElementType, context));
case ElementType.CModReqD:
var modreq = (RequiredModifierType) type;
return new RequiredModifierType (
ImportType (modreq.ModifierType, context),
ImportType (modreq.ElementType, context));
case ElementType.Array:
var array = (ArrayType) type;
var imported_array = new ArrayType (ImportType (array.ElementType, context));
if (array.IsVector)
return imported_array;
var dimensions = array.Dimensions;
var imported_dimensions = imported_array.Dimensions;
imported_dimensions.Clear ();
for (int i = 0; i < dimensions.Count; i++) {
var dimension = dimensions [i];
imported_dimensions.Add (new ArrayDimension (dimension.LowerBound, dimension.UpperBound));
}
return imported_array;
case ElementType.GenericInst:
var instance = (GenericInstanceType) type;
var element_type = ImportType (instance.ElementType, context);
var imported_instance = new GenericInstanceType (element_type);
var arguments = instance.GenericArguments;
var imported_arguments = imported_instance.GenericArguments;
for (int i = 0; i < arguments.Count; i++)
imported_arguments.Add (ImportType (arguments [i], context));
return imported_instance;
case ElementType.Var:
var var_parameter = (GenericParameter) type;
if (var_parameter.DeclaringType == null)
throw new InvalidOperationException ();
return context.TypeParameter (var_parameter.DeclaringType.FullName, var_parameter.Position);
case ElementType.MVar:
var mvar_parameter = (GenericParameter) type;
if (mvar_parameter.DeclaringMethod == null)
throw new InvalidOperationException ();
return context.MethodParameter (mvar_parameter.DeclaringMethod.Name, mvar_parameter.Position);
}
throw new NotSupportedException (type.etype.ToString ());
}
public FieldReference ImportField (FieldReference field, ImportGenericContext context)
{
var declaring_type = ImportType (field.DeclaringType, context);
context.Push (declaring_type);
try {
return new FieldReference {
Name = field.Name,
DeclaringType = declaring_type,
FieldType = ImportType (field.FieldType, context),
};
} finally {
context.Pop ();
}
}
public MethodReference ImportMethod (MethodReference method, ImportGenericContext context)
{
if (method.IsGenericInstance)
return ImportMethodSpecification (method, context);
var declaring_type = ImportType (method.DeclaringType, context);
var reference = new MethodReference {
Name = method.Name,
HasThis = method.HasThis,
ExplicitThis = method.ExplicitThis,
DeclaringType = declaring_type,
CallingConvention = method.CallingConvention,
};
if (method.HasGenericParameters)
ImportGenericParameters (reference, method);
context.Push (reference);
try {
reference.ReturnType = ImportType (method.ReturnType, context);
if (!method.HasParameters)
return reference;
var reference_parameters = reference.Parameters;
var parameters = method.Parameters;
for (int i = 0; i < parameters.Count; i++)
reference_parameters.Add (
new ParameterDefinition (ImportType (parameters [i].ParameterType, context)));
return reference;
} finally {
context.Pop();
}
}
MethodSpecification ImportMethodSpecification (MethodReference method, ImportGenericContext context)
{
if (!method.IsGenericInstance)
throw new NotSupportedException ();
var instance = (GenericInstanceMethod) method;
var element_method = ImportMethod (instance.ElementMethod, context);
var imported_instance = new GenericInstanceMethod (element_method);
var arguments = instance.GenericArguments;
var imported_arguments = imported_instance.GenericArguments;
for (int i = 0; i < arguments.Count; i++)
imported_arguments.Add (ImportType (arguments [i], context));
return imported_instance;
}
}
}
| |
// 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.Globalization;
using System.Net;
using System.Net.Http.Headers;
using System.Net.Security;
using System.Runtime.ExceptionServices;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Security.Authentication;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using RTApiInformation = Windows.Foundation.Metadata.ApiInformation;
using RTHttpBaseProtocolFilter = Windows.Web.Http.Filters.HttpBaseProtocolFilter;
using RTHttpCacheReadBehavior = Windows.Web.Http.Filters.HttpCacheReadBehavior;
using RTHttpCacheWriteBehavior = Windows.Web.Http.Filters.HttpCacheWriteBehavior;
using RTHttpCookieUsageBehavior = Windows.Web.Http.Filters.HttpCookieUsageBehavior;
using RTHttpRequestMessage = Windows.Web.Http.HttpRequestMessage;
using RTPasswordCredential = Windows.Security.Credentials.PasswordCredential;
using RTCertificate = Windows.Security.Cryptography.Certificates.Certificate;
using RTChainValidationResult = Windows.Security.Cryptography.Certificates.ChainValidationResult;
using RTHttpServerCustomValidationRequestedEventArgs = Windows.Web.Http.Filters.HttpServerCustomValidationRequestedEventArgs;
namespace System.Net.Http
{
public partial class HttpClientHandler : HttpMessageHandler
{
private const string RequestMessageLookupKey = "System.Net.Http.HttpRequestMessage";
private const string SavedExceptionDispatchInfoLookupKey = "System.Runtime.ExceptionServices.ExceptionDispatchInfo";
private const string ClientAuthenticationOID = "1.3.6.1.5.5.7.3.2";
private static Oid s_serverAuthOid = new Oid("1.3.6.1.5.5.7.3.1", "1.3.6.1.5.5.7.3.1");
private static readonly Lazy<bool> s_RTCookieUsageBehaviorSupported =
new Lazy<bool>(InitRTCookieUsageBehaviorSupported);
internal static bool RTCookieUsageBehaviorSupported => s_RTCookieUsageBehaviorSupported.Value;
private static readonly Lazy<bool> s_RTNoCacheSupported =
new Lazy<bool>(InitRTNoCacheSupported);
private static bool RTNoCacheSupported => s_RTNoCacheSupported.Value;
private static readonly Lazy<bool> s_RTServerCustomValidationRequestedSupported =
new Lazy<bool>(InitRTServerCustomValidationRequestedSupported);
private static bool RTServerCustomValidationRequestedSupported => s_RTServerCustomValidationRequestedSupported.Value;
#region Fields
private readonly HttpHandlerToFilter _handlerToFilter;
private readonly HttpMessageHandler _diagnosticsPipeline;
private RTHttpBaseProtocolFilter _rtFilter;
private ClientCertificateOption _clientCertificateOptions;
private CookieContainer _cookieContainer;
private bool _useCookies;
private DecompressionMethods _automaticDecompression;
private bool _allowAutoRedirect;
private int _maxAutomaticRedirections;
private ICredentials _defaultProxyCredentials;
private ICredentials _credentials;
private IWebProxy _proxy;
private X509Certificate2Collection _clientCertificates;
private IDictionary<String, Object> _properties; // Only create dictionary when required.
private Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> _serverCertificateCustomValidationCallback;
#endregion Fields
#region Properties
public virtual bool SupportsAutomaticDecompression
{
get { return true; }
}
public virtual bool SupportsProxy
{
get { return false; }
}
public virtual bool SupportsRedirectConfiguration
{
get { return false; }
}
public bool UseCookies
{
get { return _useCookies; }
set
{
CheckDisposedOrStarted();
_useCookies = value;
}
}
public CookieContainer CookieContainer
{
get { return _cookieContainer; }
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (!UseCookies)
{
throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture,
SR.net_http_invalid_enable_first, nameof(UseCookies), "true"));
}
CheckDisposedOrStarted();
_cookieContainer = value;
}
}
public ClientCertificateOption ClientCertificateOptions
{
get { return _clientCertificateOptions; }
set
{
if (value != ClientCertificateOption.Manual &&
value != ClientCertificateOption.Automatic)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_clientCertificateOptions = value;
}
}
public DecompressionMethods AutomaticDecompression
{
get { return _automaticDecompression; }
set
{
CheckDisposedOrStarted();
// Automatic decompression is implemented downstack.
// HBPF will decompress both gzip and deflate, we will set
// accept-encoding for one, the other, or both passed in here.
_rtFilter.AutomaticDecompression = (value != DecompressionMethods.None);
_automaticDecompression = value;
}
}
public bool UseProxy
{
get { return _rtFilter.UseProxy; }
set
{
CheckDisposedOrStarted();
_rtFilter.UseProxy = value;
}
}
public IWebProxy Proxy
{
// We don't actually support setting a different proxy because our Http stack in NETNative
// layers on top of the WinRT HttpClient which uses Wininet. And that API layer simply
// uses the proxy information in the registry (and the same that Internet Explorer uses).
// However, we can't throw PlatformNotSupportedException because the .NET Desktop stack
// does support this and doing so would break apps. So, we'll just let this get/set work
// even though we ignore it. The majority of apps actually use the default proxy anyways
// so setting it here would be a no-op.
get { return _proxy; }
set
{
CheckDisposedOrStarted();
_proxy = value;
}
}
public bool PreAuthenticate
{
get { return true; }
set
{
CheckDisposedOrStarted();
}
}
public bool UseDefaultCredentials
{
get { return false; }
set
{
CheckDisposedOrStarted();
}
}
public ICredentials Credentials
{
get
{
return _credentials;
}
set
{
CheckDisposedOrStarted();
if (value != null && value != CredentialCache.DefaultCredentials && !(value is NetworkCredential))
{
throw new PlatformNotSupportedException(String.Format(CultureInfo.InvariantCulture,
SR.net_http_value_not_supported, value, nameof(Credentials)));
}
_credentials = value;
}
}
public ICredentials DefaultProxyCredentials
{
get
{
return _defaultProxyCredentials;
}
set
{
CheckDisposedOrStarted();
if (value != null && value != CredentialCache.DefaultCredentials && !(value is NetworkCredential))
{
throw new PlatformNotSupportedException(String.Format(CultureInfo.InvariantCulture,
SR.net_http_value_not_supported, value, nameof(DefaultProxyCredentials)));
}
_defaultProxyCredentials = value;;
}
}
public bool AllowAutoRedirect
{
get { return _allowAutoRedirect; }
set
{
CheckDisposedOrStarted();
_allowAutoRedirect = value;
}
}
public int MaxAutomaticRedirections
{
get { return _maxAutomaticRedirections; }
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
}
}
public int MaxConnectionsPerServer
{
get { return (int)_rtFilter.MaxConnectionsPerServer; }
set
{
CheckDisposedOrStarted();
_rtFilter.MaxConnectionsPerServer = (uint)value;
}
}
public int MaxResponseHeadersLength
{
// Windows.Web.Http is built on WinINet. There is no maximum limit (except for out of memory)
// for received response headers. So, returning -1 (indicating no limit) is appropriate.
get { return -1; }
set
{
CheckDisposedOrStarted();
}
}
public X509CertificateCollection ClientCertificates
{
get
{
if (_clientCertificateOptions != ClientCertificateOption.Manual)
{
throw new InvalidOperationException(SR.Format(
SR.net_http_invalid_enable_first,
nameof(ClientCertificateOptions),
nameof(ClientCertificateOption.Manual)));
}
if (_clientCertificates == null)
{
_clientCertificates = new X509Certificate2Collection();
}
return _clientCertificates;
}
}
public Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> ServerCertificateCustomValidationCallback
{
get
{
return _serverCertificateCustomValidationCallback;
}
set
{
CheckDisposedOrStarted();
if (value != null)
{
if (!RTServerCustomValidationRequestedSupported)
{
throw new PlatformNotSupportedException(string.Format(CultureInfo.InvariantCulture,
SR.net_http_feature_requires_Windows10Version1607));
}
}
_serverCertificateCustomValidationCallback = value;
}
}
public bool CheckCertificateRevocationList
{
// The WinRT API always checks for certificate revocation. If the revocation status is indeterminate
// (such as revocation server is offline), then the WinRT API will indicate "success" and not fail
// the request.
get { return true; }
set
{
CheckDisposedOrStarted();
}
}
public SslProtocols SslProtocols
{
// The WinRT API does not expose a property to control this. It always uses the system default.
get { return SslProtocols.None; }
set
{
CheckDisposedOrStarted();
}
}
public IDictionary<String, Object> Properties
{
get
{
if (_properties == null)
{
_properties = new Dictionary<String, object>();
}
return _properties;
}
}
#endregion Properties
#region De/Constructors
public HttpClientHandler()
{
_rtFilter = CreateFilter();
_handlerToFilter = new HttpHandlerToFilter(_rtFilter, this);
_handlerToFilter.RequestMessageLookupKey = RequestMessageLookupKey;
_handlerToFilter.SavedExceptionDispatchInfoLookupKey = SavedExceptionDispatchInfoLookupKey;
_diagnosticsPipeline = new DiagnosticsHandler(_handlerToFilter);
_clientCertificateOptions = ClientCertificateOption.Manual;
_useCookies = true; // deal with cookies by default.
_cookieContainer = new CookieContainer(); // default container used for dealing with auto-cookies.
_allowAutoRedirect = true;
_maxAutomaticRedirections = 50;
_automaticDecompression = DecompressionMethods.None;
}
private RTHttpBaseProtocolFilter CreateFilter()
{
var filter = new RTHttpBaseProtocolFilter();
// Always turn off WinRT cookie processing if the WinRT API supports turning it off.
// Use .NET CookieContainer handling only.
if (RTCookieUsageBehaviorSupported)
{
filter.CookieUsageBehavior = RTHttpCookieUsageBehavior.NoCookies;
}
// Handle redirections at the .NET layer so that we can see cookies on redirect responses
// and have control of the number of redirections allowed.
filter.AllowAutoRedirect = false;
filter.AutomaticDecompression = false;
// We don't support using the UI model in HttpBaseProtocolFilter() especially for auto-handling 401 responses.
filter.AllowUI = false;
// The .NET Desktop System.Net Http APIs (based on HttpWebRequest/HttpClient) uses no caching by default.
// To preserve app-compat, we turn off caching in the WinRT HttpClient APIs.
filter.CacheControl.ReadBehavior = RTNoCacheSupported ?
RTHttpCacheReadBehavior.NoCache : RTHttpCacheReadBehavior.MostRecent;
filter.CacheControl.WriteBehavior = RTHttpCacheWriteBehavior.NoCache;
return filter;
}
protected override void Dispose(bool disposing)
{
if (disposing && !_disposed)
{
_disposed = true;
try
{
_rtFilter.Dispose();
}
catch (InvalidComObjectException)
{
// We'll ignore this error since it can happen when Dispose() is called from an object's finalizer
// and the WinRT object (rtFilter) has already been disposed by the .NET Native runtime.
}
}
base.Dispose(disposing);
}
#endregion De/Constructors
#region Request Setup
private async Task ConfigureRequest(HttpRequestMessage request)
{
ApplyDecompressionSettings(request);
await ApplyClientCertificateSettings().ConfigureAwait(false);
}
private void ApplyDecompressionSettings(HttpRequestMessage request)
{
// Decompression: Add the Gzip and Deflate headers if not already present.
ApplyDecompressionSetting(request, DecompressionMethods.GZip, "gzip");
ApplyDecompressionSetting(request, DecompressionMethods.Deflate, "deflate");
}
private void ApplyDecompressionSetting(HttpRequestMessage request, DecompressionMethods method, string methodName)
{
if ((AutomaticDecompression & method) == method)
{
bool found = false;
foreach (StringWithQualityHeaderValue encoding in request.Headers.AcceptEncoding)
{
if (methodName.Equals(encoding.Value, StringComparison.OrdinalIgnoreCase))
{
found = true;
break;
}
}
if (!found)
{
request.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue(methodName));
}
}
}
private async Task ApplyClientCertificateSettings()
{
if (ClientCertificateOptions == ClientCertificateOption.Manual)
{
if (_clientCertificates != null && _clientCertificates.Count > 0)
{
X509Certificate2 clientCert = CertificateHelper.GetEligibleClientCertificate(_clientCertificates);
if (clientCert == null)
{
return;
}
RTCertificate rtClientCert = await CertificateHelper.ConvertDotNetClientCertToWinRtClientCertAsync(clientCert);
if (rtClientCert == null)
{
throw new PlatformNotSupportedException(string.Format(CultureInfo.InvariantCulture,
SR.net_http_feature_UWPClientCertSupportRequiresCertInPersonalCertificateStore));
}
_rtFilter.ClientCertificate = rtClientCert;
}
return;
}
else
{
X509Certificate2 clientCert = CertificateHelper.GetEligibleClientCertificate();
if (clientCert == null)
{
return;
}
// Unlike in the .Manual case above, the conversion to WinRT Certificate should always work;
// so we just use an Assert. All the possible client certs were enumerated from that store and
// filtered down to a single client cert.
RTCertificate rtClientCert = await CertificateHelper.ConvertDotNetClientCertToWinRtClientCertAsync(clientCert);
Debug.Assert(rtClientCert != null);
_rtFilter.ClientCertificate = rtClientCert;
}
}
private RTPasswordCredential RTPasswordCredentialFromICredentials(ICredentials creds)
{
// The WinRT PasswordCredential object does not have a special credentials value for "default credentials".
// In general, the UWP HTTP platform automatically manages sending default credentials, if no explicit
// credential was specified, based on if the app has EnterpriseAuthentication capability and if the endpoint
// is listed in an intranet zone.
//
// A WinRT PasswordCredential object that is either null or created with the default constructor (i.e. with
// empty values for username and password) indicates that there is no explicit credential. And that means
// that the default logged-on credentials might be sent to the endpoint.
//
// There is currently no WinRT API to turn off sending default credentials other than the capability
// and intranet zone checks described above. In general, the UWP HTTP model for specifying default
// credentials is orthogonal to how the .NET System.Net APIs have been designed.
if (creds == null || creds == CredentialCache.DefaultCredentials)
{
return null;
}
else
{
Debug.Assert(creds is NetworkCredential);
NetworkCredential networkCred = (NetworkCredential)creds;
// Creating a new WinRT PasswordCredential object with the default constructor ends up
// with empty strings for username and password inside the object. However, one can't assign
// empty strings to those properties; otherwise, it will throw an error.
RTPasswordCredential rtCreds = new RTPasswordCredential();
if (!string.IsNullOrEmpty(networkCred.UserName))
{
if (!string.IsNullOrEmpty(networkCred.Domain))
{
rtCreds.UserName = networkCred.Domain + "\\" + networkCred.UserName;
}
else
{
rtCreds.UserName = networkCred.UserName;
}
}
if (!string.IsNullOrEmpty(networkCred.Password))
{
rtCreds.Password = networkCred.Password;
}
return rtCreds;
}
}
private void SetFilterProxyCredential()
{
// We don't support changing the proxy settings in the UAP version of HttpClient since it's layered on
// WinRT HttpClient. But we do support passing in explicit proxy credentials, if specified, which we can
// get from the specified or default proxy.
ICredentials proxyCredentials = null;
if (UseProxy)
{
if (_proxy != null)
{
proxyCredentials = _proxy.Credentials;
}
else
{
proxyCredentials = _defaultProxyCredentials;
}
}
_rtFilter.ProxyCredential = RTPasswordCredentialFromICredentials(proxyCredentials);
}
private void SetFilterServerCredential()
{
_rtFilter.ServerCredential = RTPasswordCredentialFromICredentials(_credentials);
}
#endregion Request Setup
#region Request Execution
protected internal override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
CancellationToken cancellationToken)
{
CheckDisposed();
SetOperationStarted();
HttpResponseMessage response;
try
{
if (string.Equals(request.Method.Method, HttpMethod.Trace.Method, StringComparison.OrdinalIgnoreCase))
{
// https://github.com/dotnet/corefx/issues/22161
throw new PlatformNotSupportedException(string.Format(CultureInfo.InvariantCulture,
SR.net_http_httpmethod_notsupported_error, request.Method.Method));
}
await ConfigureRequest(request).ConfigureAwait(false);
Task<HttpResponseMessage> responseTask = DiagnosticsHandler.IsEnabled() ?
_diagnosticsPipeline.SendAsync(request, cancellationToken) :
_handlerToFilter.SendAsync(request, cancellationToken);
response = await responseTask.ConfigureAwait(false);
}
catch (OperationCanceledException)
{
throw;
}
catch (Exception ex)
{
// Convert back to the expected exception type.
throw new HttpRequestException(SR.net_http_client_execution_error, ex);
}
return response;
}
#endregion Request Execution
#region Helpers
private void SetOperationStarted()
{
if (!_operationStarted)
{
// Since this is the first operation, we set all the necessary WinRT filter properties.
SetFilterProxyCredential();
SetFilterServerCredential();
if (_serverCertificateCustomValidationCallback != null)
{
Debug.Assert(RTServerCustomValidationRequestedSupported);
// The WinRT layer uses a different model for the certificate callback. The callback is
// considered "extra" validation. We need to explicitly ignore errors so that the callback
// will get called.
//
// In addition, the WinRT layer restricts some errors so that they cannot be ignored, such
// as "Revoked". This will result in behavior differences between UWP and other platforms.
// The following errors cannot be ignored right now in the WinRT layer:
//
// ChainValidationResult.BasicConstraintsError
// ChainValidationResult.InvalidCertificateAuthorityPolicy
// ChainValidationResult.InvalidSignature
// ChainValidationResult.OtherErrors
// ChainValidationResult.Revoked
// ChainValidationResult.UnknownCriticalExtension
_rtFilter.IgnorableServerCertificateErrors.Add(RTChainValidationResult.Expired);
_rtFilter.IgnorableServerCertificateErrors.Add(RTChainValidationResult.IncompleteChain);
_rtFilter.IgnorableServerCertificateErrors.Add(RTChainValidationResult.InvalidName);
_rtFilter.IgnorableServerCertificateErrors.Add(RTChainValidationResult.RevocationFailure);
_rtFilter.IgnorableServerCertificateErrors.Add(RTChainValidationResult.RevocationInformationMissing);
_rtFilter.IgnorableServerCertificateErrors.Add(RTChainValidationResult.Untrusted);
_rtFilter.IgnorableServerCertificateErrors.Add(RTChainValidationResult.WrongUsage);
_rtFilter.ServerCustomValidationRequested += RTServerCertificateCallback;
}
_operationStarted = true;
}
}
private static bool InitRTCookieUsageBehaviorSupported()
{
return RTApiInformation.IsPropertyPresent(
"Windows.Web.Http.Filters.HttpBaseProtocolFilter",
"CookieUsageBehavior");
}
private static bool InitRTNoCacheSupported()
{
return RTApiInformation.IsEnumNamedValuePresent(
"Windows.Web.Http.Filters.HttpCacheReadBehavior",
"NoCache");
}
private static bool InitRTServerCustomValidationRequestedSupported()
{
return RTApiInformation.IsEventPresent(
"Windows.Web.Http.Filters.HttpBaseProtocolFilter",
"ServerCustomValidationRequested");
}
internal void RTServerCertificateCallback(RTHttpBaseProtocolFilter sender, RTHttpServerCustomValidationRequestedEventArgs args)
{
bool success = RTServerCertificateCallbackHelper(
args.RequestMessage,
args.ServerCertificate,
args.ServerIntermediateCertificates,
args.ServerCertificateErrors);
if (!success)
{
args.Reject();
}
}
private bool RTServerCertificateCallbackHelper(
RTHttpRequestMessage requestMessage,
RTCertificate cert,
IReadOnlyList<RTCertificate> intermediateCerts,
IReadOnlyList<RTChainValidationResult> certErrors)
{
// Convert WinRT certificate to .NET certificate.
X509Certificate2 serverCert = CertificateHelper.ConvertPublicKeyCertificate(cert);
// Create .NET X509Chain from the WinRT information. We need to rebuild the chain since WinRT only
// gives us an array of intermediate certificates and not a X509Chain object.
var serverChain = new X509Chain();
SslPolicyErrors sslPolicyErrors = SslPolicyErrors.None;
foreach (RTCertificate intermediateCert in intermediateCerts)
{
serverChain.ChainPolicy.ExtraStore.Add(CertificateHelper.ConvertPublicKeyCertificate(cert));
}
serverChain.ChainPolicy.RevocationMode = X509RevocationMode.Online; // WinRT always checks revocation.
serverChain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot;
// Authenticate the remote party: (e.g. when operating in client mode, authenticate the server).
serverChain.ChainPolicy.ApplicationPolicy.Add(s_serverAuthOid);
if (!serverChain.Build(serverCert))
{
sslPolicyErrors |= SslPolicyErrors.RemoteCertificateChainErrors;
}
// Determine name-mismatch error from the existing WinRT information since .NET X509Chain.Build does not
// return that in the X509Chain.ChainStatus fields.
foreach (RTChainValidationResult result in certErrors)
{
if (result == RTChainValidationResult.InvalidName)
{
sslPolicyErrors |= SslPolicyErrors.RemoteCertificateNameMismatch;
break;
}
}
// Get the .NET HttpRequestMessage we saved in the property bag of the WinRT HttpRequestMessage.
HttpRequestMessage request = (HttpRequestMessage)requestMessage.Properties[RequestMessageLookupKey];
// Call the .NET callback.
bool success = false;
try
{
success = _serverCertificateCustomValidationCallback(request, serverCert, serverChain, sslPolicyErrors);
}
catch (Exception ex)
{
// Save the exception info. We will return it later via the SendAsync response processing.
requestMessage.Properties.Add(
SavedExceptionDispatchInfoLookupKey,
ExceptionDispatchInfo.Capture(ex));
}
finally
{
serverChain.Dispose();
serverCert.Dispose();
}
return success;
}
#endregion Helpers
}
}
| |
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Collections.Generic;
#if FRAMEWORK_4_0_OR_ABOVE
using System.Threading.Tasks;
#else
using System.Threading;
#endif
using log4net.Appender;
using log4net.Core;
using log4net.Util;
namespace log4net.Appender
{
/// <summary>
/// Appender that forwards LoggingEvents asynchronously
/// </summary>
/// <remarks>
/// This appender forwards LoggingEvents to a list of attached appenders.
/// The events are forwarded asynchronously using the ThreadPool.
/// This allows the calling thread to be released quickly, however it does
/// not guarantee the ordering of events delivered to the attached appenders.
/// </remarks>
public sealed class AsyncAppender : ForwardingAppender
{
/// <summary>
/// Creates a new AsyncAppender.
/// </summary>
public AsyncAppender()
{
#if FRAMEWORK_4_0_OR_ABOVE
logTask = new Task(() => { });
logTask.Start();
#endif
}
/// <summary>
/// Gets or sets a the fields that will be fixed in the event
/// </summary>
/// <value>
/// The event fields that will be fixed before the event is forwarded
/// </value>
/// <remarks>
/// <para>
/// The logging event needs to have certain thread specific values
/// captured before it can be forwarded to a different thread.
/// See <see cref="LoggingEvent.Fix"/> for details.
/// </para>
/// </remarks>
/// <seealso cref="LoggingEvent.Fix"/>
public FixFlags Fix
{
get { return m_fixFlags; }
set { m_fixFlags = value; }
}
/// <summary>
/// Forward the logging event to the attached appenders on a ThreadPool thread
/// </summary>
/// <param name="loggingEvent">The event to log.</param>
/// <remarks>
/// <para>
/// Delivers the logging event to all the attached appenders on a ThreadPool thread.
/// </para>
/// </remarks>
override protected void Append(LoggingEvent loggingEvent)
{
loggingEvent.Fix = m_fixFlags;
lock (lockObject)
{
if (closed)
{
return;
}
events.Add(loggingEvent);
}
#if FRAMEWORK_4_0_OR_ABOVE
logTask.ContinueWith(AsyncAppend);
#else
ThreadPool.QueueUserWorkItem(AsyncAppend, null);
#endif
}
/// <summary>
/// Forward the logging events to the attached appenders on a ThreadPool thread
/// </summary>
/// <param name="loggingEvents">The array of events to log.</param>
/// <remarks>
/// <para>
/// Delivers the logging events to all the attached appenders on a ThreadPool thread.
/// </para>
/// </remarks>
override protected void Append(LoggingEvent[] loggingEvents)
{
foreach (LoggingEvent loggingEvent in loggingEvents)
{
loggingEvent.Fix = m_fixFlags;
}
lock (lockObject)
{
if (closed)
{
return;
}
events.AddRange(loggingEvents);
}
#if FRAMEWORK_4_0_OR_ABOVE
logTask.ContinueWith(AsyncAppend);
#else
ThreadPool.QueueUserWorkItem(AsyncAppend, null);
#endif
}
/// <summary>
/// Closes the appender and releases resources.
/// </summary>
/// <remarks>
/// <para>
/// Releases any resources allocated within the appender such as file handles,
/// network connections, etc.
/// </para>
/// <para>
/// It is a programming error to append to a closed appender.
/// </para>
/// </remarks>
override protected void OnClose()
{
lock (lockObject)
{
#if FRAMEWORK_4_0_OR_ABOVE
if (!closed)
{
logTask.Wait();
}
#endif
closed = true;
}
base.OnClose();
}
private void AsyncAppend(object _ignored)
{
#if FRAMEWORK_4_0_OR_ABOVE // ContinueWith already ensures there is only one thread executing this method at a time
ForwardEvents();
#else
lock (lockObject)
{
if (inLoggingLoop)
{
return;
}
inLoggingLoop = true;
}
try
{
while (true)
{
if (!ForwardEvents())
{
break;
}
}
}
finally
{
lock (lockObject)
{
inLoggingLoop = false;
}
}
#endif
}
/// <summary>
/// Forwards the queued events to the nested appenders.
/// </summary>
/// <returns>whether there have been any events to forward.</returns>
private bool ForwardEvents()
{
LoggingEvent[] loggingEvents = null;
lock (lockObject)
{
loggingEvents = events.ToArray();
events.Clear();
}
if (loggingEvents.Length == 0)
{
return false;
}
base.Append(loggingEvents);
return true;
}
private FixFlags m_fixFlags = FixFlags.All;
private readonly object lockObject = new object();
private readonly List<LoggingEvent> events = new List<LoggingEvent>();
private bool closed = false;
#if FRAMEWORK_4_0_OR_ABOVE
private readonly Task logTask;
#else
private bool inLoggingLoop = false;
#endif
}
}
| |
using System;
using System.Runtime.InteropServices;
using System.ComponentModel;
namespace SharpGL
{
/// <summary>
/// Useful functions imported from the Win32 SDK.
/// </summary>
public static class Win32
{
/// <summary>
/// Initializes the <see cref="Win32"/> class.
/// </summary>
static Win32()
{
// Load the openGL library - without this wgl calls will fail.
IntPtr glLibrary = Win32.LoadLibrary(OpenGL32);
}
// The names of the libraries we're importing.
public const string Kernel32 = "kernel32.dll";
public const string OpenGL32 = "opengl32.dll";
public const string Glu32 = "Glu32.dll";
public const string Gdi32 = "gdi32.dll";
public const string User32 = "user32.dll";
#region Kernel32 Functions
[DllImport(Kernel32)]
public static extern IntPtr LoadLibrary(string lpFileName);
#endregion
#region WGL Functions
/// <summary>
/// Gets the current render context.
/// </summary>
/// <returns>The current render context.</returns>
[DllImport(OpenGL32)]
public static extern IntPtr wglGetCurrentContext();
/// <summary>
/// Make the specified render context current.
/// </summary>
/// <param name="hdc">The handle to the device context.</param>
/// <param name="hrc">The handle to the render context.</param>
/// <returns></returns>
[DllImport(OpenGL32)]
public static extern int wglMakeCurrent(IntPtr hdc, IntPtr hrc);
/// <summary>
/// Creates a render context from the device context.
/// </summary>
/// <param name="hdc">The handle to the device context.</param>
/// <returns>The handle to the render context.</returns>
[DllImport(OpenGL32)]
public static extern IntPtr wglCreateContext(IntPtr hdc);
/// <summary>
/// Deletes the render context.
/// </summary>
/// <param name="hrc">The handle to the render context.</param>
/// <returns></returns>
[DllImport(OpenGL32)]
public static extern int wglDeleteContext(IntPtr hrc);
/// <summary>
/// Gets a proc address.
/// </summary>
/// <param name="name">The name of the function.</param>
/// <returns>The address of the function.</returns>
[DllImport(OpenGL32)]
public static extern IntPtr wglGetProcAddress(string name);
/// <summary>
/// The wglUseFontBitmaps function creates a set of bitmap display lists for use in the current OpenGL rendering context. The set of bitmap display lists is based on the glyphs in the currently selected font in the device context. You can then use bitmaps to draw characters in an OpenGL image.
/// </summary>
/// <param name="hDC">Specifies the device context whose currently selected font will be used to form the glyph bitmap display lists in the current OpenGL rendering context..</param>
/// <param name="first">Specifies the first glyph in the run of glyphs that will be used to form glyph bitmap display lists.</param>
/// <param name="count">Specifies the number of glyphs in the run of glyphs that will be used to form glyph bitmap display lists. The function creates count display lists, one for each glyph in the run.</param>
/// <param name="listBase">Specifies a starting display list.</param>
/// <returns>If the function succeeds, the return value is TRUE. If the function fails, the return value is FALSE. To get extended error information, call GetLastError.</returns>
[DllImport(OpenGL32)]
public static extern bool wglUseFontBitmaps(IntPtr hDC, uint first, uint count, uint listBase);
/// <summary>
/// The wglUseFontOutlines function creates a set of display lists, one for each glyph of the currently selected outline font of a device context, for use with the current rendering context.
/// </summary>
/// <param name="hDC">The h DC.</param>
/// <param name="first">The first.</param>
/// <param name="count">The count.</param>
/// <param name="listBase">The list base.</param>
/// <param name="deviation">The deviation.</param>
/// <param name="extrusion">The extrusion.</param>
/// <param name="format">The format.</param>
/// <param name="lpgmf">The LPGMF.</param>
/// <returns></returns>
[DllImport(OpenGL32)]
public static extern bool wglUseFontOutlines(IntPtr hDC, uint first, uint count, uint listBase,
float deviation, float extrusion, int format, IntPtr lpgmf);
/// <summary>
/// Link two render contexts so they share lists (buffer IDs, etc.)
/// </summary>
/// <param name="hrc1">The first context.</param>
/// <param name="hrc2">The second context.</param>
/// <returns>If the function succeeds, the return value is TRUE. If the function fails, the return value is FALSE.
/// To get extended error information, call GetLastError.</returns>
[DllImport(OpenGL32)]
public static extern bool wglShareLists(IntPtr hrc1, IntPtr hrc2);
#endregion
#region PixelFormatDescriptor structure and flags.
[StructLayout(LayoutKind.Explicit)]
public class PIXELFORMATDESCRIPTOR
{
[FieldOffset(0)]
public UInt16 nSize;
[FieldOffset(2)]
public UInt16 nVersion;
[FieldOffset(4)]
public UInt32 dwFlags;
[FieldOffset(8)]
public Byte iPixelType;
[FieldOffset(9)]
public Byte cColorBits;
[FieldOffset(10)]
public Byte cRedBits;
[FieldOffset(11)]
public Byte cRedShift;
[FieldOffset(12)]
public Byte cGreenBits;
[FieldOffset(13)]
public Byte cGreenShift;
[FieldOffset(14)]
public Byte cBlueBits;
[FieldOffset(15)]
public Byte cBlueShift;
[FieldOffset(16)]
public Byte cAlphaBits;
[FieldOffset(17)]
public Byte cAlphaShift;
[FieldOffset(18)]
public Byte cAccumBits;
[FieldOffset(19)]
public Byte cAccumRedBits;
[FieldOffset(20)]
public Byte cAccumGreenBits;
[FieldOffset(21)]
public Byte cAccumBlueBits;
[FieldOffset(22)]
public Byte cAccumAlphaBits;
[FieldOffset(23)]
public Byte cDepthBits;
[FieldOffset(24)]
public Byte cStencilBits;
[FieldOffset(25)]
public Byte cAuxBuffers;
[FieldOffset(26)]
public SByte iLayerType;
[FieldOffset(27)]
public Byte bReserved;
[FieldOffset(28)]
public UInt32 dwLayerMask;
[FieldOffset(32)]
public UInt32 dwVisibleMask;
[FieldOffset(36)]
public UInt32 dwDamageMask;
public void Init()
{
nSize = (ushort)Marshal.SizeOf(this);
}
}
public struct PixelFormatDescriptor
{
public ushort nSize;
public ushort nVersion;
public uint dwFlags;
public byte iPixelType;
public byte cColorBits;
public byte cRedBits;
public byte cRedShift;
public byte cGreenBits;
public byte cGreenShift;
public byte cBlueBits;
public byte cBlueShift;
public byte cAlphaBits;
public byte cAlphaShift;
public byte cAccumBits;
public byte cAccumRedBits;
public byte cAccumGreenBits;
public byte cAccumBlueBits;
public byte cAccumAlphaBits;
public byte cDepthBits;
public byte cStencilBits;
public byte cAuxBuffers;
public sbyte iLayerType;
public byte bReserved;
public uint dwLayerMask;
public uint dwVisibleMask;
public uint dwDamageMask;
}
public const byte PFD_TYPE_RGBA = 0;
public const byte PFD_TYPE_COLORINDEX = 1;
public const uint PFD_DOUBLEBUFFER = 1;
public const uint PFD_STEREO = 2;
public const uint PFD_DRAW_TO_WINDOW = 4;
public const uint PFD_DRAW_TO_BITMAP = 8;
public const uint PFD_SUPPORT_GDI = 16;
public const uint PFD_SUPPORT_OPENGL = 32;
public const uint PFD_GENERIC_FORMAT = 64;
public const uint PFD_NEED_PALETTE = 128;
public const uint PFD_NEED_SYSTEM_PALETTE = 256;
public const uint PFD_SWAP_EXCHANGE = 512;
public const uint PFD_SWAP_COPY = 1024;
public const uint PFD_SWAP_LAYER_BUFFERS = 2048;
public const uint PFD_GENERIC_ACCELERATED = 4096;
public const uint PFD_SUPPORT_DIRECTDRAW = 8192;
public const sbyte PFD_MAIN_PLANE = 0;
public const sbyte PFD_OVERLAY_PLANE = 1;
public const sbyte PFD_UNDERLAY_PLANE = -1;
public delegate IntPtr WndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
[DllImport(User32)]
public static extern IntPtr DefWindowProc(IntPtr hWnd, uint uMsg, IntPtr wParam, IntPtr lParam);
[DllImport(User32, SetLastError = true)]
public static extern IntPtr CreateWindowEx(
WindowStylesEx dwExStyle,
string lpClassName,
string lpWindowName,
WindowStyles dwStyle,
int x,
int y,
int nWidth,
int nHeight,
IntPtr hWndParent,
IntPtr hMenu,
IntPtr hInstance,
IntPtr lpParam);
[Flags]
public enum WindowStylesEx : uint
{
/// <summary>
/// Specifies that a window created with this style accepts drag-drop files.
/// </summary>
WS_EX_ACCEPTFILES = 0x00000010,
/// <summary>
/// Forces a top-level window onto the taskbar when the window is visible.
/// </summary>
WS_EX_APPWINDOW = 0x00040000,
/// <summary>
/// Specifies that a window has a border with a sunken edge.
/// </summary>
WS_EX_CLIENTEDGE = 0x00000200,
/// <summary>
/// Windows XP: Paints all descendants of a window in bottom-to-top painting order using double-buffering. For more information, see Remarks. This cannot be used if the window has a class style of either CS_OWNDC or CS_CLASSDC.
/// </summary>
WS_EX_COMPOSITED = 0x02000000,
/// <summary>
/// Includes a question mark in the title bar of the window. When the user clicks the question mark, the cursor changes to a question mark with a pointer. If the user then clicks a child window, the child receives a WM_HELP message. The child window should pass the message to the parent window procedure, which should call the WinHelp function using the HELP_WM_HELP command. The Help application displays a pop-up window that typically contains help for the child window.
/// WS_EX_CONTEXTHELP cannot be used with the WS_MAXIMIZEBOX or WS_MINIMIZEBOX styles.
/// </summary>
WS_EX_CONTEXTHELP = 0x00000400,
/// <summary>
/// The window itself contains child windows that should take part in dialog box navigation. If this style is specified, the dialog manager recurses into children of this window when performing navigation operations such as handling the TAB key, an arrow key, or a keyboard mnemonic.
/// </summary>
WS_EX_CONTROLPARENT = 0x00010000,
/// <summary>
/// Creates a window that has a double border; the window can, optionally, be created with a title bar by specifying the WS_CAPTION style in the dwStyle parameter.
/// </summary>
WS_EX_DLGMODALFRAME = 0x00000001,
/// <summary>
/// Windows 2000/XP: Creates a layered window. Note that this cannot be used for child windows. Also, this cannot be used if the window has a class style of either CS_OWNDC or CS_CLASSDC.
/// </summary>
WS_EX_LAYERED = 0x00080000,
/// <summary>
/// Arabic and Hebrew versions of Windows 98/Me, Windows 2000/XP: Creates a window whose horizontal origin is on the right edge. Increasing horizontal values advance to the left.
/// </summary>
WS_EX_LAYOUTRTL = 0x00400000,
/// <summary>
/// Creates a window that has generic left-aligned properties. This is the default.
/// </summary>
WS_EX_LEFT = 0x00000000,
/// <summary>
/// If the shell language is Hebrew, Arabic, or another language that supports reading order alignment, the vertical scroll bar (if present) is to the left of the client area. For other languages, the style is ignored.
/// </summary>
WS_EX_LEFTSCROLLBAR = 0x00004000,
/// <summary>
/// The window text is displayed using left-to-right reading-order properties. This is the default.
/// </summary>
WS_EX_LTRREADING = 0x00000000,
/// <summary>
/// Creates a multiple-document interface (MDI) child window.
/// </summary>
WS_EX_MDICHILD = 0x00000040,
/// <summary>
/// Windows 2000/XP: A top-level window created with this style does not become the foreground window when the user clicks it. The system does not bring this window to the foreground when the user minimizes or closes the foreground window.
/// To activate the window, use the SetActiveWindow or SetForegroundWindow function.
/// The window does not appear on the taskbar by default. To force the window to appear on the taskbar, use the WS_EX_APPWINDOW style.
/// </summary>
WS_EX_NOACTIVATE = 0x08000000,
/// <summary>
/// Windows 2000/XP: A window created with this style does not pass its window layout to its child windows.
/// </summary>
WS_EX_NOINHERITLAYOUT = 0x00100000,
/// <summary>
/// Specifies that a child window created with this style does not send the WM_PARENTNOTIFY message to its parent window when it is created or destroyed.
/// </summary>
WS_EX_NOPARENTNOTIFY = 0x00000004,
/// <summary>
/// Combines the WS_EX_CLIENTEDGE and WS_EX_WINDOWEDGE styles.
/// </summary>
WS_EX_OVERLAPPEDWINDOW = WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE,
/// <summary>
/// Combines the WS_EX_WINDOWEDGE, WS_EX_TOOLWINDOW, and WS_EX_TOPMOST styles.
/// </summary>
WS_EX_PALETTEWINDOW = WS_EX_WINDOWEDGE | WS_EX_TOOLWINDOW | WS_EX_TOPMOST,
/// <summary>
/// The window has generic "right-aligned" properties. This depends on the window class. This style has an effect only if the shell language is Hebrew, Arabic, or another language that supports reading-order alignment; otherwise, the style is ignored.
/// Using the WS_EX_RIGHT style for static or edit controls has the same effect as using the SS_RIGHT or ES_RIGHT style, respectively. Using this style with button controls has the same effect as using BS_RIGHT and BS_RIGHTBUTTON styles.
/// </summary>
WS_EX_RIGHT = 0x00001000,
/// <summary>
/// Vertical scroll bar (if present) is to the right of the client area. This is the default.
/// </summary>
WS_EX_RIGHTSCROLLBAR = 0x00000000,
/// <summary>
/// If the shell language is Hebrew, Arabic, or another language that supports reading-order alignment, the window text is displayed using right-to-left reading-order properties. For other languages, the style is ignored.
/// </summary>
WS_EX_RTLREADING = 0x00002000,
/// <summary>
/// Creates a window with a three-dimensional border style intended to be used for items that do not accept user input.
/// </summary>
WS_EX_STATICEDGE = 0x00020000,
/// <summary>
/// Creates a tool window; that is, a window intended to be used as a floating toolbar. A tool window has a title bar that is shorter than a normal title bar, and the window title is drawn using a smaller font. A tool window does not appear in the taskbar or in the dialog that appears when the user presses ALT+TAB. If a tool window has a system menu, its icon is not displayed on the title bar. However, you can display the system menu by right-clicking or by typing ALT+SPACE.
/// </summary>
WS_EX_TOOLWINDOW = 0x00000080,
/// <summary>
/// Specifies that a window created with this style should be placed above all non-topmost windows and should stay above them, even when the window is deactivated. To add or remove this style, use the SetWindowPos function.
/// </summary>
WS_EX_TOPMOST = 0x00000008,
/// <summary>
/// Specifies that a window created with this style should not be painted until siblings beneath the window (that were created by the same thread) have been painted. The window appears transparent because the bits of underlying sibling windows have already been painted.
/// To achieve transparency without these restrictions, use the SetWindowRgn function.
/// </summary>
WS_EX_TRANSPARENT = 0x00000020,
/// <summary>
/// Specifies that a window has a border with a raised edge.
/// </summary>
WS_EX_WINDOWEDGE = 0x00000100
}
[Flags()]
public enum WindowStyles : uint
{
/// <summary>The window has a thin-line border.</summary>
WS_BORDER = 0x800000,
/// <summary>The window has a title bar (includes the WS_BORDER style).</summary>
WS_CAPTION = 0xc00000,
/// <summary>The window is a child window. A window with this style cannot have a menu bar. This style cannot be used with the WS_POPUP style.</summary>
WS_CHILD = 0x40000000,
/// <summary>Excludes the area occupied by child windows when drawing occurs within the parent window. This style is used when creating the parent window.</summary>
WS_CLIPCHILDREN = 0x2000000,
/// <summary>
/// Clips child windows relative to each other; that is, when a particular child window receives a WM_PAINT message, the WS_CLIPSIBLINGS style clips all other overlapping child windows out of the region of the child window to be updated.
/// If WS_CLIPSIBLINGS is not specified and child windows overlap, it is possible, when drawing within the client area of a child window, to draw within the client area of a neighboring child window.
/// </summary>
WS_CLIPSIBLINGS = 0x4000000,
/// <summary>The window is initially disabled. A disabled window cannot receive input from the user. To change this after a window has been created, use the EnableWindow function.</summary>
WS_DISABLED = 0x8000000,
/// <summary>The window has a border of a style typically used with dialog boxes. A window with this style cannot have a title bar.</summary>
WS_DLGFRAME = 0x400000,
/// <summary>
/// The window is the first control of a group of controls. The group consists of this first control and all controls defined after it, up to the next control with the WS_GROUP style.
/// The first control in each group usually has the WS_TABSTOP style so that the user can move from group to group. The user can subsequently change the keyboard focus from one control in the group to the next control in the group by using the direction keys.
/// You can turn this style on and off to change dialog box navigation. To change this style after a window has been created, use the SetWindowLong function.
/// </summary>
WS_GROUP = 0x20000,
/// <summary>The window has a horizontal scroll bar.</summary>
WS_HSCROLL = 0x100000,
/// <summary>The window is initially maximized.</summary>
WS_MAXIMIZE = 0x1000000,
/// <summary>The window has a maximize button. Cannot be combined with the WS_EX_CONTEXTHELP style. The WS_SYSMENU style must also be specified.</summary>
WS_MAXIMIZEBOX = 0x10000,
/// <summary>The window is initially minimized.</summary>
WS_MINIMIZE = 0x20000000,
/// <summary>The window has a minimize button. Cannot be combined with the WS_EX_CONTEXTHELP style. The WS_SYSMENU style must also be specified.</summary>
WS_MINIMIZEBOX = 0x20000,
/// <summary>The window is an overlapped window. An overlapped window has a title bar and a border.</summary>
WS_OVERLAPPED = 0x0,
/// <summary>The window is an overlapped window.</summary>
WS_OVERLAPPEDWINDOW = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_SIZEFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX,
/// <summary>The window is a pop-up window. This style cannot be used with the WS_CHILD style.</summary>
WS_POPUP = 0x80000000u,
/// <summary>The window is a pop-up window. The WS_CAPTION and WS_POPUPWINDOW styles must be combined to make the window menu visible.</summary>
WS_POPUPWINDOW = WS_POPUP | WS_BORDER | WS_SYSMENU,
/// <summary>The window has a sizing border.</summary>
WS_SIZEFRAME = 0x40000,
/// <summary>The window has a window menu on its title bar. The WS_CAPTION style must also be specified.</summary>
WS_SYSMENU = 0x80000,
/// <summary>
/// The window is a control that can receive the keyboard focus when the user presses the TAB key.
/// Pressing the TAB key changes the keyboard focus to the next control with the WS_TABSTOP style.
/// You can turn this style on and off to change dialog box navigation. To change this style after a window has been created, use the SetWindowLong function.
/// For user-created windows and modeless dialogs to work with tab stops, alter the message loop to call the IsDialogMessage function.
/// </summary>
WS_TABSTOP = 0x10000,
/// <summary>The window is initially visible. This style can be turned on and off by using the ShowWindow or SetWindowPos function.</summary>
WS_VISIBLE = 0x10000000,
/// <summary>The window has a vertical scroll bar.</summary>
WS_VSCROLL = 0x200000
}
[Flags]
public enum ClassStyles : uint
{
ByteAlignClient = 0x1000,
ByteAlignWindow = 0x2000,
ClassDC = 0x40,
DoubleClicks = 0x8,
DropShadow = 0x20000,
GlobalClass = 0x4000,
HorizontalRedraw = 0x2,
NoClose = 0x200,
OwnDC = 0x20,
ParentDC = 0x80,
SaveBits = 0x800,
VerticalRedraw = 0x1
}
[StructLayout(LayoutKind.Sequential)]
public struct WNDCLASSEX
{
public uint cbSize;
public ClassStyles style;
[MarshalAs(UnmanagedType.FunctionPtr)]
public WndProc lpfnWndProc;
public int cbClsExtra;
public int cbWndExtra;
public IntPtr hInstance;
public IntPtr hIcon;
public IntPtr hCursor;
public IntPtr hbrBackground;
public string lpszMenuName;
public string lpszClassName;
public IntPtr hIconSm;
public void Init()
{
cbSize = (uint)Marshal.SizeOf(this);
}
}
[StructLayout(LayoutKind.Sequential)]
public struct BITMAPINFO
{
public Int32 biSize;
public Int32 biWidth;
public Int32 biHeight;
public Int16 biPlanes;
public Int16 biBitCount;
public Int32 biCompression;
public Int32 biSizeImage;
public Int32 biXPelsPerMeter;
public Int32 biYPelsPerMeter;
public Int32 biClrUsed;
public Int32 biClrImportant;
public void Init()
{
biSize = Marshal.SizeOf(this);
}
}
#endregion
#region Win32 Function Definitions.
// Unmanaged functions from the Win32 graphics library.
[DllImport(Gdi32, SetLastError = true)]
public unsafe static extern int ChoosePixelFormat(IntPtr hDC,
[In, MarshalAs(UnmanagedType.LPStruct)] PIXELFORMATDESCRIPTOR ppfd);
[DllImport(Gdi32, SetLastError = true)]
public unsafe static extern int SetPixelFormat(IntPtr hDC, int iPixelFormat,
[In, MarshalAs(UnmanagedType.LPStruct)] PIXELFORMATDESCRIPTOR ppfd );
[DllImport(Gdi32)]
public static extern IntPtr GetStockObject(uint fnObject);
[DllImport(Gdi32)]
public static extern int SwapBuffers(IntPtr hDC);
[DllImport(Gdi32)]
public static extern bool BitBlt(IntPtr hDC, int x, int y, int width,
int height, IntPtr hDCSource, int sourceX, int sourceY, uint type);
[DllImport(Gdi32)]
public static extern IntPtr CreateDIBSection(IntPtr hdc, [In] ref BITMAPINFO pbmi,
uint pila, out IntPtr ppvBits, IntPtr hSection, uint dwOffset);
[DllImport(Gdi32, SetLastError = true)]
public static extern IntPtr SelectObject(IntPtr hdc, IntPtr hgdiobj);
[DllImport(Gdi32)]
public static extern bool DeleteObject(IntPtr hObject);
[DllImport(Gdi32)]
public static extern IntPtr CreateCompatibleDC(IntPtr hDC);
[DllImport(Gdi32)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool DeleteDC(IntPtr hDC);
[DllImport(Gdi32)]
public static extern IntPtr CreateFont(int nHeight, int nWidth, int nEscapement,
int nOrientation, uint fnWeight, uint fdwItalic, uint fdwUnderline, uint
fdwStrikeOut, uint fdwCharSet, uint fdwOutputPrecision, uint
fdwClipPrecision, uint fdwQuality, uint fdwPitchAndFamily, string lpszFace);
#endregion
#region User32 Functions
[DllImport(User32)]
public static extern IntPtr GetDC(IntPtr hWnd);
[DllImport(User32)]
public static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);
[DllImport(User32)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool DestroyWindow(IntPtr hWnd);
[DllImport(User32)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, SetWindowPosFlags uFlags);
[DllImport(User32)]
[return: MarshalAs(UnmanagedType.U2)]
public static extern short RegisterClassEx([In] ref WNDCLASSEX lpwcx);
#endregion
[Flags]
public enum SetWindowPosFlags : uint
{
SWP_ASYNCWINDOWPOS = 0x4000,
SWP_DEFERERASE = 0x2000,
SWP_DRAWFRAME = 0x0020,
SWP_FRAMECHANGED = 0x0020,
SWP_HIDEWINDOW = 0x0080,
SWP_NOACTIVATE = 0x0010,
SWP_NOCOPYBITS = 0x0100,
SWP_NOMOVE = 0x0002,
SWP_NOOWNERZORDER = 0x0200,
SWP_NOREDRAW = 0x0008,
SWP_NOREPOSITION = 0x0200,
SWP_NOSENDCHANGING = 0x0400,
SWP_NOSIZE = 0x0001,
SWP_NOZORDER = 0x0004,
SWP_SHOWWINDOW = 0x0040,
}
#region Windows Messages
public const int WM_ACTIVATE = 0x0006;
public const int WM_ACTIVATEAPP = 0x001C;
public const int WM_AFXFIRST = 0x0360;
public const int WM_AFXLAST = 0x037F;
public const int WM_APP = 0x8000;
public const int WM_ASKCBFORMATNAME = 0x030C;
public const int WM_CANCELJOURNAL = 0x004B;
public const int WM_CANCELMODE = 0x001F;
public const int WM_CAPTURECHANGED = 0x0215;
public const int WM_CHANGECBCHAIN = 0x030D;
public const int WM_CHANGEUISTATE = 0x0127;
public const int WM_CHAR = 0x0102;
public const int WM_CHARTOITEM = 0x002F;
public const int WM_CHILDACTIVATE = 0x0022;
public const int WM_CLEAR = 0x0303;
public const int WM_CLOSE = 0x0010;
public const int WM_COMMAND = 0x0111;
public const int WM_COMPACTING = 0x0041;
public const int WM_COMPAREITEM = 0x0039;
public const int WM_CONTEXTMENU = 0x007B;
public const int WM_COPY = 0x0301;
public const int WM_COPYDATA = 0x004A;
public const int WM_CREATE = 0x0001;
public const int WM_CTLCOLORBTN = 0x0135;
public const int WM_CTLCOLORDLG = 0x0136;
public const int WM_CTLCOLOREDIT = 0x0133;
public const int WM_CTLCOLORLISTBOX = 0x0134;
public const int WM_CTLCOLORMSGBOX = 0x0132;
public const int WM_CTLCOLORSCROLLBAR = 0x0137;
public const int WM_CTLCOLORSTATIC = 0x0138;
public const int WM_CUT = 0x0300;
public const int WM_DEADCHAR = 0x0103;
public const int WM_DELETEITEM = 0x002D;
public const int WM_DESTROY = 0x0002;
public const int WM_DESTROYCLIPBOARD = 0x0307;
public const int WM_DEVICECHANGE = 0x0219;
public const int WM_DEVMODECHANGE = 0x001B;
public const int WM_DISPLAYCHANGE = 0x007E;
public const int WM_DRAWCLIPBOARD = 0x0308;
public const int WM_DRAWITEM = 0x002B;
public const int WM_DROPFILES = 0x0233;
public const int WM_ENABLE = 0x000A;
public const int WM_ENDSESSION = 0x0016;
public const int WM_ENTERIDLE = 0x0121;
public const int WM_ENTERMENULOOP = 0x0211;
public const int WM_ENTERSIZEMOVE = 0x0231;
public const int WM_ERASEBKGND = 0x0014;
public const int WM_EXITMENULOOP = 0x0212;
public const int WM_EXITSIZEMOVE = 0x0232;
public const int WM_FONTCHANGE = 0x001D;
public const int WM_GETDLGCODE = 0x0087;
public const int WM_GETFONT = 0x0031;
public const int WM_GETHOTKEY = 0x0033;
public const int WM_GETICON = 0x007F;
public const int WM_GETMINMAXINFO = 0x0024;
public const int WM_GETOBJECT = 0x003D;
public const int WM_GETTEXT = 0x000D;
public const int WM_GETTEXTLENGTH = 0x000E;
public const int WM_HANDHELDFIRST = 0x0358;
public const int WM_HANDHELDLAST = 0x035F;
public const int WM_HELP = 0x0053;
public const int WM_HOTKEY = 0x0312;
public const int WM_HSCROLL = 0x0114;
public const int WM_HSCROLLCLIPBOARD = 0x030E;
public const int WM_ICONERASEBKGND = 0x0027;
public const int WM_IME_CHAR = 0x0286;
public const int WM_IME_COMPOSITION = 0x010F;
public const int WM_IME_COMPOSITIONFULL = 0x0284;
public const int WM_IME_CONTROL = 0x0283;
public const int WM_IME_ENDCOMPOSITION = 0x010E;
public const int WM_IME_KEYDOWN = 0x0290;
public const int WM_IME_KEYLAST = 0x010F;
public const int WM_IME_KEYUP = 0x0291;
public const int WM_IME_NOTIFY = 0x0282;
public const int WM_IME_REQUEST = 0x0288;
public const int WM_IME_SELECT = 0x0285;
public const int WM_IME_SETCONTEXT = 0x0281;
public const int WM_IME_STARTCOMPOSITION = 0x010D;
public const int WM_INITDIALOG = 0x0110;
public const int WM_INITMENU = 0x0116;
public const int WM_INITMENUPOPUP = 0x0117;
public const int WM_INPUTLANGCHANGE = 0x0051;
public const int WM_INPUTLANGCHANGEREQUEST = 0x0050;
public const int WM_KEYDOWN = 0x0100;
public const int WM_KEYFIRST = 0x0100;
public const int WM_KEYLAST = 0x0108;
public const int WM_KEYUP = 0x0101;
public const int WM_KILLFOCUS = 0x0008;
public const int WM_LBUTTONDBLCLK = 0x0203;
public const int WM_LBUTTONDOWN = 0x0201;
public const int WM_LBUTTONUP = 0x0202;
public const int WM_MBUTTONDBLCLK = 0x0209;
public const int WM_MBUTTONDOWN = 0x0207;
public const int WM_MBUTTONUP = 0x0208;
public const int WM_MDIACTIVATE = 0x0222;
public const int WM_MDICASCADE = 0x0227;
public const int WM_MDICREATE = 0x0220;
public const int WM_MDIDESTROY = 0x0221;
public const int WM_MDIGETACTIVE = 0x0229;
public const int WM_MDIICONARRANGE = 0x0228;
public const int WM_MDIMAXIMIZE = 0x0225;
public const int WM_MDINEXT = 0x0224;
public const int WM_MDIREFRESHMENU = 0x0234;
public const int WM_MDIRESTORE = 0x0223;
public const int WM_MDISETMENU = 0x0230;
public const int WM_MDITILE = 0x0226;
public const int WM_MEASUREITEM = 0x002C;
public const int WM_MENUCHAR = 0x0120;
public const int WM_MENUCOMMAND = 0x0126;
public const int WM_MENUDRAG = 0x0123;
public const int WM_MENUGETOBJECT = 0x0124;
public const int WM_MENURBUTTONUP = 0x0122;
public const int WM_MENUSELECT = 0x011F;
public const int WM_MOUSEACTIVATE = 0x0021;
public const int WM_MOUSEFIRST = 0x0200;
public const int WM_MOUSEHOVER = 0x02A1;
public const int WM_MOUSELAST = 0x020D;
public const int WM_MOUSELEAVE = 0x02A3;
public const int WM_MOUSEMOVE = 0x0200;
public const int WM_MOUSEWHEEL = 0x020A;
public const int WM_MOUSEHWHEEL = 0x020E;
public const int WM_MOVE = 0x0003;
public const int WM_MOVING = 0x0216;
public const int WM_NCACTIVATE = 0x0086;
public const int WM_NCCALCSIZE = 0x0083;
public const int WM_NCCREATE = 0x0081;
public const int WM_NCDESTROY = 0x0082;
public const int WM_NCHITTEST = 0x0084;
public const int WM_NCLBUTTONDBLCLK = 0x00A3;
public const int WM_NCLBUTTONDOWN = 0x00A1;
public const int WM_NCLBUTTONUP = 0x00A2;
public const int WM_NCMBUTTONDBLCLK = 0x00A9;
public const int WM_NCMBUTTONDOWN = 0x00A7;
public const int WM_NCMBUTTONUP = 0x00A8;
public const int WM_NCMOUSEMOVE = 0x00A0;
public const int WM_NCPAINT = 0x0085;
public const int WM_NCRBUTTONDBLCLK = 0x00A6;
public const int WM_NCRBUTTONDOWN = 0x00A4;
public const int WM_NCRBUTTONUP = 0x00A5;
public const int WM_NEXTDLGCTL = 0x0028;
public const int WM_NEXTMENU = 0x0213;
public const int WM_NOTIFY = 0x004E;
public const int WM_NOTIFYFORMAT = 0x0055;
public const int WM_NULL = 0x0000;
public const int WM_PAINT = 0x000F;
public const int WM_PAINTCLIPBOARD = 0x0309;
public const int WM_PAINTICON = 0x0026;
public const int WM_PALETTECHANGED = 0x0311;
public const int WM_PALETTEISCHANGING = 0x0310;
public const int WM_PARENTNOTIFY = 0x0210;
public const int WM_PASTE = 0x0302;
public const int WM_PENWINFIRST = 0x0380;
public const int WM_PENWINLAST = 0x038F;
public const int WM_POWER = 0x0048;
public const int WM_POWERBROADCAST = 0x0218;
public const int WM_PRINT = 0x0317;
public const int WM_PRINTCLIENT = 0x0318;
public const int WM_QUERYDRAGICON = 0x0037;
public const int WM_QUERYENDSESSION = 0x0011;
public const int WM_QUERYNEWPALETTE = 0x030F;
public const int WM_QUERYOPEN = 0x0013;
public const int WM_QUEUESYNC = 0x0023;
public const int WM_QUIT = 0x0012;
public const int WM_RBUTTONDBLCLK = 0x0206;
public const int WM_RBUTTONDOWN = 0x0204;
public const int WM_RBUTTONUP = 0x0205;
public const int WM_RENDERALLFORMATS = 0x0306;
public const int WM_RENDERFORMAT = 0x0305;
public const int WM_SETCURSOR = 0x0020;
public const int WM_SETFOCUS = 0x0007;
public const int WM_SETFONT = 0x0030;
public const int WM_SETHOTKEY = 0x0032;
public const int WM_SETICON = 0x0080;
public const int WM_SETREDRAW = 0x000B;
public const int WM_SETTEXT = 0x000C;
public const int WM_SETTINGCHANGE = 0x001A;
public const int WM_SHOWWINDOW = 0x0018;
public const int WM_SIZE = 0x0005;
public const int WM_SIZECLIPBOARD = 0x030B;
public const int WM_SIZING = 0x0214;
public const int WM_SPOOLERSTATUS = 0x002A;
public const int WM_STYLECHANGED = 0x007D;
public const int WM_STYLECHANGING = 0x007C;
public const int WM_SYNCPAINT = 0x0088;
public const int WM_SYSCHAR = 0x0106;
public const int WM_SYSCOLORCHANGE = 0x0015;
public const int WM_SYSCOMMAND = 0x0112;
public const int WM_SYSDEADCHAR = 0x0107;
public const int WM_SYSKEYDOWN = 0x0104;
public const int WM_SYSKEYUP = 0x0105;
public const int WM_TCARD = 0x0052;
public const int WM_TIMECHANGE = 0x001E;
public const int WM_TIMER = 0x0113;
public const int WM_UNDO = 0x0304;
public const int WM_UNINITMENUPOPUP = 0x0125;
public const int WM_USER = 0x0400;
public const int WM_USERCHANGED = 0x0054;
public const int WM_VKEYTOITEM = 0x002E;
public const int WM_VSCROLL = 0x0115;
public const int WM_VSCROLLCLIPBOARD = 0x030A;
public const int WM_WINDOWPOSCHANGED = 0x0047;
public const int WM_WINDOWPOSCHANGING = 0x0046;
public const int WM_WININICHANGE = 0x001A;
public const int WM_XBUTTONDBLCLK = 0x020D;
public const int WM_XBUTTONDOWN = 0x020B;
public const int WM_XBUTTONUP = 0x020C;
#endregion
public const uint WHITE_BRUSH = 0;
public const uint LTGRAY_BRUSH = 1;
public const uint GRAY_BRUSH = 2;
public const uint DKGRAY_BRUSH = 3;
public const uint BLACK_BRUSH = 4;
public const uint NULL_BRUSH = 5;
public const uint HOLLOW_BRUSH = NULL_BRUSH;
public const uint WHITE_PEN = 6;
public const uint BLACK_PEN = 7;
public const uint NULL_PEN = 8;
public const uint OEM_FIXED_FONT = 10;
public const uint ANSI_FIXED_FONT = 11;
public const uint ANSI_VAR_FONT = 12;
public const uint SYSTEM_FONT = 13;
public const uint DEVICE_DEFAULT_FONT = 14;
public const uint DEFAULT_PALETTE = 15;
public const uint SYSTEM_FIXED_FONT = 16;
public const uint DEFAULT_GUI_FONT = 17;
public const uint DC_BRUSH = 18;
public const uint DC_PEN = 19;
public const uint DEFAULT_PITCH = 0;
public const uint FIXED_PITCH = 1;
public const uint VARIABLE_PITCH = 2;
public const uint DEFAULT_QUALITY = 0;
public const uint DRAFT_QUALITY = 1;
public const uint PROOF_QUALITY = 2;
public const uint NONANTIALIASED_QUALITY = 3;
public const uint ANTIALIASED_QUALITY = 4;
public const uint CLEARTYPE_QUALITY = 5;
public const uint CLEARTYPE_NATURAL_QUALITY = 6;
public const uint CLIP_DEFAULT_PRECIS = 0;
public const uint CLIP_CHARACTER_PRECIS = 1;
public const uint CLIP_STROKE_PRECIS = 2;
public const uint CLIP_MASK = 0xf;
public const uint OUT_DEFAULT_PRECIS = 0;
public const uint OUT_STRING_PRECIS = 1;
public const uint OUT_CHARACTER_PRECIS = 2;
public const uint OUT_STROKE_PRECIS = 3;
public const uint OUT_TT_PRECIS = 4;
public const uint OUT_DEVICE_PRECIS = 5;
public const uint OUT_RASTER_PRECIS = 6;
public const uint OUT_TT_ONLY_PRECIS = 7;
public const uint OUT_OUTLINE_PRECIS = 8;
public const uint OUT_SCREEN_OUTLINE_PRECIS = 9;
public const uint OUT_PS_ONLY_PRECIS = 10;
public const uint ANSI_CHARSET = 0;
public const uint DEFAULT_CHARSET = 1;
public const uint SYMBOL_CHARSET = 2;
public const uint FW_DONTCARE = 0;
public const uint FW_THIN = 100;
public const uint FW_EXTRALIGHT = 200;
public const uint FW_LIGHT = 300;
public const uint FW_NORMAL = 400;
public const uint FW_MEDIUM = 500;
public const uint FW_SEMIBOLD = 600;
public const uint FW_BOLD = 700;
public const uint FW_EXTRABOLD = 800;
public const uint FW_HEAVY = 900;
public const uint SRCCOPY = 0x00CC0020; // dest = source
public const uint SRCPAINT = 0x00EE0086; // dest = source OR dest
public const uint SRCAND = 0x008800C6; // dest = source AND dest
public const uint SRCINVERT = 0x00660046; // dest = source XOR dest
public const uint SRCERASE = 0x00440328; // dest = source AND (NOT dest )
public const uint NOTSRCCOPY = 0x00330008; // dest = (NOT source)
public const uint NOTSRCERASE = 0x001100A6; // dest = (NOT src) AND (NOT dest)
public const uint MERGECOPY = 0x00C000CA; // dest = (source AND pattern)
public const uint MERGEPAINT = 0x00BB0226; // dest = (NOT source) OR dest
public const uint PATCOPY = 0x00F00021; // dest = pattern
public const uint PATPAINT = 0x00FB0A09; // dest = DPSnoo
public const uint PATINVERT = 0x005A0049; // dest = pattern XOR dest
public const uint DSTINVERT = 0x00550009; // dest = (NOT dest)
public const uint BLACKNESS = 0x00000042; // dest = BLACK
public const uint WHITENESS = 0x00FF0062; // dest = WHITE
public const uint DIB_RGB_COLORS = 0;
public const uint DIB_PAL_COLORS = 1;
public const uint CS_VREDRAW = 0x0001;
public const uint CS_HREDRAW = 0x0002;
public const uint CS_DBLCLKS = 0x0008;
public const uint CS_OWNDC = 0x0020;
public const uint CS_CLASSDC = 0x0040;
public const uint CS_PARENTDC = 0x0080;
public const uint CS_NOCLOSE = 0x0200;
public const uint CS_SAVEBITS = 0x0800;
public const uint CS_BYTEALIGNCLIENT = 0x1000;
public const uint CS_BYTEALIGNWINDOW = 0x2000;
public const uint CS_GLOBALCLASS = 0x4000;
}
}
| |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using SlackAPI.RPCMessages;
namespace SlackAPI
{
/// <summary>
/// SlackClient is intended to solely handle RPC (HTTP-based) functionality. Does not handle WebSocket connectivity.
///
/// For WebSocket connectivity, refer to <see cref="SlackAPI.SlackSocketClient"/>
/// </summary>
public class SlackClient
{
readonly string APIToken;
bool authWorks = false;
const string APIBaseLocation = "https://slack.com/api/";
const int Timeout = 5000;
const char StartHighlight = '\uE001';
const char EndHightlight = '\uE001';
static List<Tuple<string, string>> replacers = new List<Tuple<string, string>>(){
new Tuple<string,string>("&", "&"),
new Tuple<string,string>("<", "<"),
new Tuple<string,string>(">", ">")
};
//Dictionary<int, Action<ReceivingMessage>> socketCallbacks;
public Self MySelf;
public User MyData;
public Team MyTeam;
public List<string> starredChannels;
public List<User> Users;
public List<Channel> Channels;
public List<Channel> Groups;
public List<DirectMessageConversation> DirectMessages;
public Dictionary<string, User> UserLookup;
public Dictionary<string, Channel> ChannelLookup;
public Dictionary<string, Channel> GroupLookup;
public Dictionary<string, DirectMessageConversation> DirectMessageLookup;
public Dictionary<string, Conversation> ConversationLookup;
//public event Action<ReceivingMessage> OnUserTyping;
//public event Action<ReceivingMessage> OnMessageReceived;
//public event Action<ReceivingMessage> OnPresenceChanged;
//public event Action<ReceivingMessage> OnHello;
public SlackClient(string token)
{
APIToken = token;
}
public virtual void Connect(Action<LoginResponse> onConnected = null, Action onSocketConnected = null)
{
EmitLogin((loginDetails) =>
{
if(loginDetails.ok)
Connected(loginDetails);
if (onConnected != null)
onConnected(loginDetails);
});
}
protected virtual void Connected(LoginResponse loginDetails)
{
MySelf = loginDetails.self;
MyData = loginDetails.users.First((c) => c.id == MySelf.id);
MyTeam = loginDetails.team;
Users = new List<User>(loginDetails.users.Where((c) => !c.deleted));
Channels = new List<Channel>(loginDetails.channels);
Groups = new List<Channel>(loginDetails.groups);
DirectMessages = new List<DirectMessageConversation>(loginDetails.ims.Where((c) => Users.Exists((a) => a.id == c.user) && c.id != MySelf.id));
starredChannels =
Groups.Where((c) => c.is_starred).Select((c) => c.id)
.Union(
DirectMessages.Where((c) => c.is_starred).Select((c) => c.user)
).Union(
Channels.Where((c) => c.is_starred).Select((c) => c.id)
).ToList();
UserLookup = new Dictionary<string, User>();
foreach (User u in Users) UserLookup.Add(u.id, u);
ChannelLookup = new Dictionary<string, Channel>();
ConversationLookup = new Dictionary<string, Conversation>();
foreach (Channel c in Channels)
{
ChannelLookup.Add(c.id, c);
ConversationLookup.Add(c.id, c);
}
GroupLookup = new Dictionary<string, Channel>();
foreach (Channel g in Groups)
{
GroupLookup.Add(g.id, g);
ConversationLookup.Add(g.id, g);
}
DirectMessageLookup = new Dictionary<string, DirectMessageConversation>();
foreach (DirectMessageConversation im in DirectMessages)
{
DirectMessageLookup.Add(im.id, im);
ConversationLookup.Add(im.id, im);
}
}
internal static Uri GetSlackUri(string path, Tuple<string, string>[] getParameters)
{
string parameters = getParameters
.Where(x => x.Item2 != null)
.Select(new Func<Tuple<string, string>, string>(a =>
{
try
{
return string.Format("{0}={1}", Uri.EscapeDataString(a.Item1), Uri.EscapeDataString(a.Item2));
}
catch (Exception ex)
{
throw new InvalidOperationException(string.Format("Failed when processing '{0}'.", a), ex);
}
}))
.Aggregate((a, b) =>
{
if (string.IsNullOrEmpty(a))
return b;
else
return string.Format("{0}&{1}", a, b);
});
Uri requestUri = new Uri(string.Format("{0}?{1}", path, parameters));
return requestUri;
}
public static void APIRequest<K>(Action<K> callback, Tuple<string, string>[] getParameters, Tuple<string, string>[] postParameters)
where K : Response
{
RequestPath path = RequestPath.GetRequestPath<K>();
//TODO: Custom paths? Appropriate subdomain paths? Not sure.
//Maybe store custom path in the requestpath.path itself?
Uri requestUri = GetSlackUri(Path.Combine(APIBaseLocation, path.Path), getParameters);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestUri);
//This will handle all of the processing.
RequestState<K> state = new RequestState<K>(request, postParameters, callback);
state.Begin();
}
public static void APIGetRequest<K>(Action<K> callback, params Tuple<string, string>[] getParameters)
where K : Response
{
APIRequest<K>(callback, getParameters, new Tuple<string, string>[0]);
}
public void APIRequestWithToken<K>(Action<K> callback, params Tuple<string,string>[] getParameters)
where K : Response
{
Tuple<string, string>[] tokenArray = new Tuple<string, string>[]{
new Tuple<string,string>("token", APIToken)
};
if (getParameters != null && getParameters.Length > 0)
tokenArray = tokenArray.Concat(getParameters).ToArray();
APIRequest(callback, tokenArray, new Tuple<string, string>[0]);
}
[Obsolete("Please use the OAuth method for authenticating users")]
public static void StartAuth(Action<AuthStartResponse> callback, string email)
{
APIRequest(callback, new Tuple<string, string>[] { new Tuple<string, string>("email", email) }, new Tuple<string, string>[0]);
}
public static void FindTeam(Action<FindTeamResponse> callback, string team)
{
//This seems to accept both 'team.slack.com' and just plain 'team'.
//Going to go with the latter.
Tuple<string, string> domainName = new Tuple<string, string>("domain", team);
APIRequest(callback, new Tuple<string, string>[] { domainName }, new Tuple<string, string>[0]);
}
public static void AuthSignin(Action<AuthSigninResponse> callback, string userId, string teamId, string password)
{
APIRequest(callback, new Tuple<string, string>[] {
new Tuple<string,string>("user", userId),
new Tuple<string,string>("team", teamId),
new Tuple<string,string>("password", password)
}, new Tuple<string, string>[0]);
}
public void TestAuth(Action<AuthTestResponse> callback)
{
APIRequestWithToken(callback);
}
public void GetUserList(Action<UserListResponse> callback)
{
APIRequestWithToken(callback);
}
public void ChannelsCreate(Action<ChannelCreateResponse> callback, string name) {
APIRequestWithToken(callback, new Tuple<string, string>("name", name));
}
public void GetChannelList(Action<ChannelListResponse> callback, bool ExcludeArchived = true)
{
APIRequestWithToken(callback, new Tuple<string, string>("exclude_archived", ExcludeArchived ? "1" : "0"));
}
public void GetGroupsList(Action<GroupListResponse> callback, bool ExcludeArchived = true)
{
APIRequestWithToken(callback, new Tuple<string, string>("exclude_archived", ExcludeArchived ? "1" : "0"));
}
public void GetDirectMessageList(Action<DirectMessageConversationListResponse> callback)
{
APIRequestWithToken(callback);
}
public void GetFiles(Action<FileListResponse> callback, string userId = null, DateTime? from = null, DateTime? to = null, int? count = null, int? page = null, FileTypes types = FileTypes.all)
{
List<Tuple<string, string>> parameters = new List<Tuple<string, string>>();
if (!string.IsNullOrEmpty(userId))
parameters.Add(new Tuple<string,string>("user", userId));
if (from.HasValue)
parameters.Add(new Tuple<string, string>("ts_from", from.Value.ToProperTimeStamp()));
if (to.HasValue)
parameters.Add(new Tuple<string, string>("ts_to", to.Value.ToProperTimeStamp()));
if (!types.HasFlag(FileTypes.all))
{
FileTypes[] values = (FileTypes[])Enum.GetValues(typeof(FileTypes));
StringBuilder building = new StringBuilder();
bool first = true;
for (int i = 0; i < values.Length; ++i)
{
if (types.HasFlag(values[i]))
{
if (!first) building.Append(",");
building.Append(values[i].ToString());
first = false;
}
}
if (building.Length > 0)
parameters.Add(new Tuple<string, string>("types", building.ToString()));
}
if (count.HasValue)
parameters.Add(new Tuple<string, string>("count", count.Value.ToString()));
if (page.HasValue)
parameters.Add(new Tuple<string, string>("page", page.Value.ToString()));
APIRequestWithToken(callback, parameters.ToArray());
}
void GetHistory<K>(Action<K> historyCallback, string channel, DateTime? latest = null, DateTime? oldest = null, int? count = null)
where K : MessageHistory
{
List<Tuple<string,string>> parameters = new List<Tuple<string,string>>();
parameters.Add(new Tuple<string, string>("channel", channel));
if(latest.HasValue)
parameters.Add(new Tuple<string, string>("latest", latest.Value.ToProperTimeStamp()));
if(oldest.HasValue)
parameters.Add(new Tuple<string, string>("oldest", oldest.Value.ToProperTimeStamp()));
if(count.HasValue)
parameters.Add(new Tuple<string,string>("count", count.Value.ToString()));
APIRequestWithToken(historyCallback, parameters.ToArray());
}
public void GetChannelHistory(Action<ChannelMessageHistory> callback, Channel channelInfo, DateTime? latest = null, DateTime? oldest = null, int? count = null)
{
GetHistory(callback, channelInfo.id, latest, oldest, count);
}
public void GetDirectMessageHistory(Action<MessageHistory> callback, DirectMessageConversation conversationInfo, DateTime? latest = null, DateTime? oldest = null, int? count = null)
{
GetHistory(callback, conversationInfo.id, latest, oldest, count);
}
public void GetGroupHistory(Action<GroupMessageHistory> callback, Channel groupInfo, DateTime? latest = null, DateTime? oldest = null, int? count = null)
{
GetHistory(callback, groupInfo.id, latest, oldest, count);
}
public void MarkChannel(Action<MarkResponse> callback, string channelId, DateTime ts)
{
APIRequestWithToken(callback,
new Tuple<string, string>("channel", channelId),
new Tuple<string, string>("ts", ts.ToProperTimeStamp())
);
}
public void GetFileInfo(Action<FileInfoResponse> callback, string fileId, int? page = null, int? count = null)
{
List<Tuple<string,string>> parameters = new List<Tuple<string,string>>();
parameters.Add(new Tuple<string,string>("file", fileId));
if(count.HasValue)
parameters.Add(new Tuple<string,string>("count", count.Value.ToString()));
if (page.HasValue)
parameters.Add(new Tuple<string, string>("page", page.Value.ToString()));
APIRequestWithToken(callback, parameters.ToArray());
}
#region Groups
public void GroupsArchive(Action<GroupArchiveResponse> callback, string channelId)
{
APIRequestWithToken(callback, new Tuple<string, string>("channel", channelId));
}
public void GroupsClose(Action<GroupCloseResponse> callback, string channelId)
{
APIRequestWithToken(callback, new Tuple<string, string>("channel", channelId));
}
public void GroupsCreate(Action<GroupCreateResponse> callback, string name)
{
APIRequestWithToken(callback, new Tuple<string, string>("name", name));
}
public void GroupsCreateChild(Action<GroupCreateChildResponse> callback, string channelId)
{
APIRequestWithToken(callback, new Tuple<string, string>("channel", channelId));
}
public void GroupsInvite(Action<GroupInviteResponse> callback, string userId, string channelId)
{
List<Tuple<string, string>> parameters = new List<Tuple<string, string>>();
parameters.Add(new Tuple<string, string>("channel", channelId));
parameters.Add(new Tuple<string, string>("user", userId));
APIRequestWithToken(callback, parameters.ToArray());
}
public void GroupsKick(Action<GroupKickResponse> callback, string userId, string channelId)
{
List<Tuple<string, string>> parameters = new List<Tuple<string, string>>();
parameters.Add(new Tuple<string, string>("channel", channelId));
parameters.Add(new Tuple<string, string>("user", userId));
APIRequestWithToken(callback, parameters.ToArray());
}
public void GroupsLeave(Action<GroupLeaveResponse> callback, string channelId)
{
APIRequestWithToken(callback, new Tuple<string, string>("channel", channelId));
}
public void GroupsMark(Action<GroupMarkResponse> callback, string channelId, DateTime ts)
{
APIRequestWithToken(callback, new Tuple<string, string>("channel", channelId), new Tuple<string, string>("ts", ts.ToProperTimeStamp()));
}
public void GroupsOpen(Action<GroupOpenResponse> callback, string channelId)
{
APIRequestWithToken(callback, new Tuple<string, string>("channel", channelId));
}
public void GroupsRename(Action<GroupRenameResponse> callback, string channelId, string name)
{
List<Tuple<string, string>> parameters = new List<Tuple<string, string>>();
parameters.Add(new Tuple<string, string>("channel", channelId));
parameters.Add(new Tuple<string, string>("name", name));
APIRequestWithToken(callback, parameters.ToArray());
}
public void GroupsSetPurpose(Action<GroupSetPurposeResponse> callback, string channelId, string purpose)
{
List<Tuple<string, string>> parameters = new List<Tuple<string, string>>();
parameters.Add(new Tuple<string, string>("channel", channelId));
parameters.Add(new Tuple<string, string>("purpose", purpose));
APIRequestWithToken(callback, parameters.ToArray());
}
public void GroupsSetTopic(Action<GroupSetPurposeResponse> callback, string channelId, string topic)
{
List<Tuple<string, string>> parameters = new List<Tuple<string, string>>();
parameters.Add(new Tuple<string, string>("channel", channelId));
parameters.Add(new Tuple<string, string>("topic", topic));
APIRequestWithToken(callback, parameters.ToArray());
}
public void GroupsUnarchive(Action<GroupUnarchiveResponse> callback, string channelId)
{
APIRequestWithToken(callback, new Tuple<string, string>("channel", channelId));
}
#endregion
public void SearchAll(Action<SearchResponseAll> callback, string query, SearchSort? sorting = null, SearchSortDirection? direction = null, bool enableHighlights = false, int? count = null, int? page = null)
{
List<Tuple<string, string>> parameters = new List<Tuple<string, string>>();
parameters.Add(new Tuple<string, string>("query", query));
if (sorting.HasValue)
parameters.Add(new Tuple<string, string>("sort", sorting.Value.ToString()));
if (direction.HasValue)
parameters.Add(new Tuple<string, string>("sort_dir", direction.Value.ToString()));
if (enableHighlights)
parameters.Add(new Tuple<string, string>("highlight", "1"));
if (count.HasValue)
parameters.Add(new Tuple<string, string>("count", count.Value.ToString()));
if (page.HasValue)
parameters.Add(new Tuple<string, string>("page", page.Value.ToString()));
APIRequestWithToken(callback, parameters.ToArray());
}
public void SearchMessages(Action<SearchResponseMessages> callback, string query, SearchSort? sorting = null, SearchSortDirection? direction = null, bool enableHighlights = false, int? count = null, int? page = null)
{
List<Tuple<string, string>> parameters = new List<Tuple<string, string>>();
parameters.Add(new Tuple<string, string>("query", query));
if (sorting.HasValue)
parameters.Add(new Tuple<string, string>("sort", sorting.Value.ToString()));
if (direction.HasValue)
parameters.Add(new Tuple<string, string>("sort_dir", direction.Value.ToString()));
if (enableHighlights)
parameters.Add(new Tuple<string, string>("highlight", "1"));
if (count.HasValue)
parameters.Add(new Tuple<string, string>("count", count.Value.ToString()));
if (page.HasValue)
parameters.Add(new Tuple<string, string>("page", page.Value.ToString()));
APIRequestWithToken(callback, parameters.ToArray());
}
public void SearchFiles(Action<SearchResponseFiles> callback, string query, SearchSort? sorting = null, SearchSortDirection? direction = null, bool enableHighlights = false, int? count = null, int? page = null)
{
List<Tuple<string, string>> parameters = new List<Tuple<string, string>>();
parameters.Add(new Tuple<string, string>("query", query));
if (sorting.HasValue)
parameters.Add(new Tuple<string, string>("sort", sorting.Value.ToString()));
if (direction.HasValue)
parameters.Add(new Tuple<string, string>("sort_dir", direction.Value.ToString()));
if (enableHighlights)
parameters.Add(new Tuple<string, string>("highlight", "1"));
if (count.HasValue)
parameters.Add(new Tuple<string, string>("count", count.Value.ToString()));
if (page.HasValue)
parameters.Add(new Tuple<string, string>("page", page.Value.ToString()));
APIRequestWithToken(callback, parameters.ToArray());
}
public void GetStars(Action<StarListResponse> callback, string userId = null, int? count = null, int? page = null){
List<Tuple<string,string>> parameters = new List<Tuple<string,string>>();
if(!string.IsNullOrEmpty(userId))
parameters.Add(new Tuple<string,string>("user", userId));
if(count.HasValue)
parameters.Add(new Tuple<string,string>("count", count.Value.ToString()));
if(page.HasValue)
parameters.Add(new Tuple<string,string>("page", page.Value.ToString()));
APIRequestWithToken(callback, parameters.ToArray());
}
public void DeleteMessage(Action<DeletedResponse> callback, string channelId, DateTime ts)
{
List<Tuple<string, string>> parameters = new List<Tuple<string, string>>()
{
new Tuple<string,string>("ts", ts.ToProperTimeStamp()),
new Tuple<string,string>("channel", channelId)
};
APIRequestWithToken(callback, parameters.ToArray());
}
public void EmitPresence(Action<PresenceResponse> callback, Presence status)
{
APIRequestWithToken(callback, new Tuple<string, string>("presence", status.ToString()));
}
public void GetPreferences(Action<UserPreferencesResponse> callback)
{
APIRequestWithToken(callback);
}
#region Users
public void GetCounts(Action<UserCountsResponse> callback)
{
APIRequestWithToken(callback);
}
public void GetPresence(Action<UserGetPresenceResponse> callback, string user)
{
APIRequestWithToken(callback, new Tuple<string, string>("user", user));
}
public void GetInfo(Action<UserInfoResponse> callback, string user)
{
APIRequestWithToken(callback, new Tuple<string, string>("user", user));
}
#endregion
public void EmitLogin(Action<LoginResponse> callback, string agent = "Inumedia.SlackAPI")
{
APIRequestWithToken(callback, new Tuple<string, string>("agent", agent));
}
public void Update(
Action<UpdateResponse> callback,
string ts,
string channelId,
string text,
string botName = null,
string parse = null,
bool linkNames = false,
Attachment[] attachments = null,
bool as_user = false)
{
List<Tuple<string, string>> parameters = new List<Tuple<string, string>>();
parameters.Add(new Tuple<string, string>("ts", ts));
parameters.Add(new Tuple<string, string>("channel", channelId));
parameters.Add(new Tuple<string, string>("text", text));
if (!string.IsNullOrEmpty(botName))
parameters.Add(new Tuple<string, string>("username", botName));
if (!string.IsNullOrEmpty(parse))
parameters.Add(new Tuple<string, string>("parse", parse));
if (linkNames)
parameters.Add(new Tuple<string, string>("link_names", "1"));
if (attachments != null && attachments.Length > 0)
parameters.Add(new Tuple<string, string>("attachments", JsonConvert.SerializeObject(attachments)));
parameters.Add(new Tuple<string, string>("as_user", as_user.ToString()));
APIRequestWithToken(callback, parameters.ToArray());
}
public void JoinDirectMessageChannel(Action<JoinDirectMessageChannelResponse> callback, string user)
{
var param = new Tuple<string, string>("user", user);
APIRequestWithToken(callback, param);
}
public void PostMessage(
Action<PostMessageResponse> callback,
string channelId,
string text,
string botName = null,
string parse = null,
bool linkNames = false,
Attachment[] attachments = null,
bool unfurl_links = false,
string icon_url = null,
string icon_emoji = null,
bool as_user = false)
{
List<Tuple<string,string>> parameters = new List<Tuple<string,string>>();
parameters.Add(new Tuple<string,string>("channel", channelId));
parameters.Add(new Tuple<string,string>("text", text));
if(!string.IsNullOrEmpty(botName))
parameters.Add(new Tuple<string,string>("username", botName));
if (!string.IsNullOrEmpty(parse))
parameters.Add(new Tuple<string, string>("parse", parse));
if (linkNames)
parameters.Add(new Tuple<string, string>("link_names", "1"));
if (attachments != null && attachments.Length > 0)
parameters.Add(new Tuple<string, string>("attachments", JsonConvert.SerializeObject(attachments)));
if (unfurl_links)
parameters.Add(new Tuple<string, string>("unfurl_links", "1"));
if (!string.IsNullOrEmpty(icon_url))
parameters.Add(new Tuple<string, string>("icon_url", icon_url));
if (!string.IsNullOrEmpty(icon_emoji))
parameters.Add(new Tuple<string, string>("icon_emoji", icon_emoji));
parameters.Add(new Tuple<string, string>("as_user", as_user.ToString()));
APIRequestWithToken(callback, parameters.ToArray());
}
public void AddReaction(
Action<ReactionAddedResponse> callback,
string name = null,
string channel = null,
string timestamp = null)
{
List<Tuple<string, string>> parameters = new List<Tuple<string, string>>();
if (!string.IsNullOrEmpty(name))
parameters.Add(new Tuple<string, string>("name", name));
if (!string.IsNullOrEmpty(channel))
parameters.Add(new Tuple<string, string>("channel", channel));
if (!string.IsNullOrEmpty(timestamp))
parameters.Add(new Tuple<string, string>("timestamp", timestamp));
APIRequestWithToken(callback, parameters.ToArray());
}
public void UploadFile(Action<FileUploadResponse> callback, byte[] fileData, string fileName, string[] channelIds, string title = null, string initialComment = null, bool useAsync = false, string fileType = null)
{
Uri target = new Uri(Path.Combine(APIBaseLocation, useAsync ? "files.uploadAsync" : "files.upload"));
List<string> parameters = new List<string>();
parameters.Add(string.Format("token={0}", APIToken));
//File/Content
if (!string.IsNullOrEmpty(fileType))
parameters.Add(string.Format("{0}={1}", "filetype", fileType));
if (!string.IsNullOrEmpty(fileName))
parameters.Add(string.Format("{0}={1}", "filename", fileName));
if (!string.IsNullOrEmpty(title))
parameters.Add(string.Format("{0}={1}", "title", title));
if (!string.IsNullOrEmpty(initialComment))
parameters.Add(string.Format("{0}={1}", "initial_comment", initialComment));
parameters.Add(string.Format("{0}={1}", "channels", string.Join(",", channelIds)));
using(HttpClient client = new HttpClient())
using (MultipartFormDataContent form = new MultipartFormDataContent())
{
form.Add(new ByteArrayContent(fileData), "file", fileName);
HttpResponseMessage response = client.PostAsync(string.Format("{0}?{1}", target, string.Join("&", parameters.ToArray())), form).Result;
string result = response.Content.ReadAsStringAsync().Result;
callback(result.Deserialize<FileUploadResponse>());
}
}
private static string BuildScope(SlackScope scope)
{
var builder = new StringBuilder();
if ((int)(scope & SlackScope.Identify) != 0)
builder.Append("identify");
if ((int)(scope & SlackScope.Read) != 0)
{
if(builder.Length > 0)
builder.Append(",");
builder.Append("read");
}
if ((int)(scope & SlackScope.Post) != 0)
{
if(builder.Length > 0)
builder.Append(",");
builder.Append("post");
}
if ((int)(scope & SlackScope.Client) != 0)
{
if(builder.Length > 0)
builder.Append(",");
builder.Append("client");
}
if ((int)(scope & SlackScope.Admin) != 0)
{
if(builder.Length > 0)
builder.Append(",");
builder.Append("admin");
}
return builder.ToString();
}
public static Uri GetAuthorizeUri(string clientId, SlackScope scopes, string redirectUri = null, string state = null, string team = null)
{
string theScopes = BuildScope(scopes);
return GetSlackUri("https://slack.com/oauth/authorize", new Tuple<string, string>[] { new Tuple<string, string>("client_id", clientId),
new Tuple<string, string>("redirect_uri", redirectUri),
new Tuple<string, string>("state", state),
new Tuple<string, string>("scope", theScopes),
new Tuple<string, string>("team", team)});
}
public static void GetAccessToken(Action<AccessTokenResponse> callback, string clientId, string clientSecret, string redirectUri, string code)
{
APIRequest<AccessTokenResponse>(callback, new Tuple<string, string>[] { new Tuple<string, string>("client_id", clientId),
new Tuple<string, string>("client_secret", clientSecret), new Tuple<string, string>("code", code),
new Tuple<string, string>("redirect_uri", redirectUri) }, new Tuple<string, string>[] {});
}
public static void RegisterConverter(JsonConverter converter)
{
if (converter == null)
{
throw new ArgumentNullException("converter");
}
Extensions.Converters.Add(converter);
}
}
}
| |
/*
* Copyright (C) 2012, 2013 OUYA, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;
using Debug = UnityEngine.Debug;
public class OuyaMenuAdmin : MonoBehaviour
{
private static Vector3 m_pos = Vector3.zero;
private static Vector3 m_euler = Vector3.zero;
[MenuItem("OUYA/Export Core Package", priority = 100)]
public static void MenuPackageCore()
{
string[] paths =
{
"ProjectSettings/InputManager.asset",
"Assets/Ouya/LitJson",
"Assets/Ouya/SDK",
"Assets/Plugins",
};
AssetDatabase.ExportPackage(paths, "OuyaSDK-Core.unitypackage", ExportPackageOptions.IncludeDependencies | ExportPackageOptions.Recurse | ExportPackageOptions.Interactive);
Debug.Log(string.Format("Export OuyaSDK-Core.unitypackage success in: {0}", Directory.GetCurrentDirectory()));
}
[MenuItem("OUYA/Export Examples Package", priority = 110)]
public static void MenuPackageExamples()
{
string[] paths =
{
"Assets/Ouya/Examples",
};
AssetDatabase.ExportPackage(paths, "OuyaSDK-Examples.unitypackage", ExportPackageOptions.IncludeDependencies | ExportPackageOptions.Recurse | ExportPackageOptions.Interactive);
Debug.Log(string.Format("Export OuyaSDK-Examples.unitypackage success in: {0}", Directory.GetCurrentDirectory()));
}
[MenuItem("OUYA/Export StarterKit Package", priority = 120)]
public static void MenuPackageStarterKit()
{
string[] paths =
{
"Assets/Ouya/StarterKit",
};
AssetDatabase.ExportPackage(paths, "OuyaSDK-StarterKit.unitypackage", ExportPackageOptions.IncludeDependencies | ExportPackageOptions.Recurse | ExportPackageOptions.Interactive);
Debug.Log(string.Format("Export OuyaSDK-StarterKit.unitypackage success in: {0}", Directory.GetCurrentDirectory()));
}
[MenuItem("OUYA/Copy Object Transform", priority=1000)]
public static void MenuCopyObjectTransform()
{
if (Selection.activeGameObject)
{
m_pos = Selection.activeGameObject.transform.position;
m_euler = Selection.activeGameObject.transform.rotation.eulerAngles;
}
}
[MenuItem("OUYA/Copy Scene Transform", priority = 1000)]
public static void MenuCopySceneTransform()
{
if (SceneView.currentDrawingSceneView &&
SceneView.currentDrawingSceneView.camera &&
SceneView.currentDrawingSceneView.camera.transform)
{
m_pos = SceneView.currentDrawingSceneView.camera.transform.position;
m_euler = SceneView.currentDrawingSceneView.camera.transform.rotation.eulerAngles;
}
}
[MenuItem("OUYA/Paste Stored Transform", priority = 1000)]
public static void MenuSetTransform()
{
if (Selection.activeGameObject)
{
Selection.activeGameObject.transform.position = m_pos;
Selection.activeGameObject.transform.rotation = Quaternion.Euler(m_euler);
}
}
public static void MenuGeneratePluginJar()
{
UpdatePaths();
if (CompileApplicationClasses())
{
BuildApplicationJar();
AssetDatabase.Refresh();
}
}
private static string m_pathUnityProject = string.Empty;
private static string m_pathUnityEditor = string.Empty;
private static string m_pathUnityJar = string.Empty;
private static string m_pathJDK = string.Empty;
private static string m_pathToolsJar = string.Empty;
private static string m_pathJar = string.Empty;
private static string m_pathJavaC = string.Empty;
private static string m_pathJavaP = string.Empty;
private static string m_pathSrc = string.Empty;
private static string m_pathSDK = string.Empty;
private static string m_pathOuyaSDKJar = string.Empty;
private static string m_pathGsonJar = string.Empty;
private static void UpdatePaths()
{
m_pathUnityProject = new DirectoryInfo(Directory.GetCurrentDirectory()).FullName;
switch (Application.platform)
{
case RuntimePlatform.OSXEditor:
m_pathUnityEditor = EditorApplication.applicationPath;
m_pathUnityJar = string.Format("{0}/{1}", m_pathUnityEditor, OuyaPanel.PATH_UNITY_JAR_MAC);
break;
case RuntimePlatform.WindowsEditor:
m_pathUnityEditor = new FileInfo(EditorApplication.applicationPath).Directory.FullName;
m_pathUnityJar = string.Format("{0}/{1}", m_pathUnityEditor, OuyaPanel.PATH_UNITY_JAR_WIN);
break;
}
m_pathSrc = string.Format("{0}/Assets/Plugins/Android/src", m_pathUnityProject);
m_pathSDK = EditorPrefs.GetString(OuyaPanel.KEY_PATH_ANDROID_SDK);
m_pathJDK = EditorPrefs.GetString(OuyaPanel.KEY_PATH_JAVA_JDK);
switch (Application.platform)
{
case RuntimePlatform.OSXEditor:
m_pathToolsJar = string.Format("{0}/Contents/Classes/classes.jar", m_pathJDK);
m_pathJar = string.Format("{0}/Contents/Commands/{1}", m_pathJDK, OuyaPanel.FILE_JAR_MAC);
m_pathJavaC = string.Format("{0}/Contents/Commands/{1}", m_pathJDK, OuyaPanel.FILE_JAVAC_MAC);
m_pathJavaP = string.Format("{0}/Contents/Commands/{1}", m_pathJDK, OuyaPanel.FILE_JAVAP_MAC);
break;
case RuntimePlatform.WindowsEditor:
m_pathToolsJar = string.Format("{0}/lib/tools.jar", m_pathJDK);
m_pathJar = string.Format("{0}/{1}/{2}", m_pathJDK, OuyaPanel.REL_JAVA_PLATFORM_TOOLS, OuyaPanel.FILE_JAR_WIN);
m_pathJavaC = string.Format("{0}/{1}/{2}", m_pathJDK, OuyaPanel.REL_JAVA_PLATFORM_TOOLS, OuyaPanel.FILE_JAVAC_WIN);
m_pathJavaP = string.Format("{0}/{1}/{2}", m_pathJDK, OuyaPanel.REL_JAVA_PLATFORM_TOOLS, OuyaPanel.FILE_JAVAP_WIN);
break;
}
m_pathOuyaSDKJar = string.Format("{0}/Assets/Plugins/Android/libs/ouya-sdk.jar", m_pathUnityProject);
m_pathGsonJar = string.Format("{0}/Assets/Plugins/Android/libs/gson-2.2.2.jar", m_pathUnityProject);
}
private static string GetPathAndroidJar()
{
return string.Format("{0}/platforms/android-{1}/android.jar", m_pathSDK, (int)PlayerSettings.Android.minSdkVersion);
}
static bool CompileApplicationClasses()
{
string pathClasses = string.Format("{0}/Assets/Plugins/Android/Classes", m_pathUnityProject);
if (!Directory.Exists(pathClasses))
{
Directory.CreateDirectory(pathClasses);
}
string includeFiles = string.Format("\"{0}/OuyaUnityPlugin.java\" \"{0}/IOuyaActivity.java\" \"{0}/UnityOuyaFacade.java\"", m_pathSrc);
string jars = string.Empty;
if (File.Exists(m_pathToolsJar))
{
Debug.Log(string.Format("Found Java tools jar: {0}", m_pathToolsJar));
}
else
{
Debug.LogError(string.Format("Failed to find Java tools jar: {0}", m_pathToolsJar));
return false;
}
if (File.Exists(GetPathAndroidJar()))
{
Debug.Log(string.Format("Found Android jar: {0}", GetPathAndroidJar()));
}
else
{
Debug.LogError(string.Format("Failed to find Android jar: {0}", GetPathAndroidJar()));
return false;
}
if (File.Exists(m_pathGsonJar))
{
Debug.Log(string.Format("Found GJON jar: {0}", m_pathGsonJar));
}
else
{
Debug.LogError(string.Format("Failed to find GSON jar: {0}", m_pathGsonJar));
return false;
}
if (File.Exists(m_pathUnityJar))
{
Debug.Log(string.Format("Found Unity jar: {0}", m_pathUnityJar));
}
else
{
Debug.LogError(string.Format("Failed to find Unity jar: {0}", m_pathUnityJar));
return false;
}
string output = string.Empty;
string error = string.Empty;
switch (Application.platform)
{
case RuntimePlatform.OSXEditor:
jars = string.Format("\"{0}:{1}:{2}:{3}:{4}\"", m_pathToolsJar, GetPathAndroidJar(), m_pathGsonJar, m_pathUnityJar, m_pathOuyaSDKJar);
OuyaPanel.RunProcess(m_pathJavaC, string.Empty, string.Format("-g -source 1.6 -target 1.6 {0} -classpath {1} -bootclasspath {1} -d \"{2}\"",
includeFiles,
jars,
pathClasses),
ref output,
ref error);
break;
case RuntimePlatform.WindowsEditor:
jars = string.Format("\"{0}\";\"{1}\";\"{2}\";\"{3}\";\"{4}\"", m_pathToolsJar, GetPathAndroidJar(), m_pathGsonJar, m_pathUnityJar, m_pathOuyaSDKJar);
OuyaPanel.RunProcess(m_pathJavaC, string.Empty, string.Format("-Xlint:deprecation -g -source 1.6 -target 1.6 {0} -classpath {1} -bootclasspath {1} -d \"{2}\"",
includeFiles,
jars,
pathClasses),
ref output,
ref error);
break;
default:
return false;
}
if (!string.IsNullOrEmpty(error))
{
Debug.LogError(error);
if (OuyaPanel.StopOnErrors)
{
return false;
}
}
return true;
}
static void BuildApplicationJar()
{
string pathClasses = string.Format("{0}/Assets/Plugins/Android/Classes", m_pathUnityProject);
OuyaPanel.RunProcess(m_pathJar, pathClasses, string.Format("cvfM OuyaUnityPlugin.jar tv/"));
OuyaPanel.RunProcess(m_pathJavaP, pathClasses, "-s tv.ouya.sdk.OuyaUnityPlugin");
OuyaPanel.RunProcess(m_pathJavaP, pathClasses, "-s tv.ouya.sdk.UnityOuyaFacade");
OuyaPanel.RunProcess(m_pathJavaP, pathClasses, "-s tv.ouya.sdk.IOuyaActivity");
string pathAppJar = string.Format("{0}/OuyaUnityPlugin.jar", pathClasses);
string pathDest = string.Format("{0}/Assets/Plugins/Android/OuyaUnityPlugin.jar", m_pathUnityProject);
if (File.Exists(pathDest))
{
File.Delete(pathDest);
}
if (File.Exists(pathAppJar))
{
File.Move(pathAppJar, pathDest);
}
if (Directory.Exists(pathClasses))
{
Directory.Delete(pathClasses, true);
}
}
}
| |
using System;
using System.Globalization;
using System.Collections.Generic;
using Sasoma.Utils;
using Sasoma.Microdata.Interfaces;
using Sasoma.Languages.Core;
using Sasoma.Microdata.Properties;
namespace Sasoma.Microdata.Types
{
/// <summary>
/// A music store.
/// </summary>
public class MusicStore_Core : TypeCore, IStore
{
public MusicStore_Core()
{
this._TypeId = 179;
this._Id = "MusicStore";
this._Schema_Org_Url = "http://schema.org/MusicStore";
string label = "";
GetLabel(out label, "MusicStore", typeof(MusicStore_Core));
this._Label = label;
this._Ancestors = new int[]{266,193,155,252};
this._SubTypes = new int[0];
this._SuperTypes = new int[]{252};
this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,47,75,77,94,95,130,137,36,60,152,156,167};
}
/// <summary>
/// Physical address of the item.
/// </summary>
private Address_Core address;
public Address_Core Address
{
get
{
return address;
}
set
{
address = value;
SetPropertyInstance(address);
}
}
/// <summary>
/// The overall rating, based on a collection of reviews or ratings, of the item.
/// </summary>
private Properties.AggregateRating_Core aggregateRating;
public Properties.AggregateRating_Core AggregateRating
{
get
{
return aggregateRating;
}
set
{
aggregateRating = value;
SetPropertyInstance(aggregateRating);
}
}
/// <summary>
/// The larger organization that this local business is a branch of, if any.
/// </summary>
private BranchOf_Core branchOf;
public BranchOf_Core BranchOf
{
get
{
return branchOf;
}
set
{
branchOf = value;
SetPropertyInstance(branchOf);
}
}
/// <summary>
/// A contact point for a person or organization.
/// </summary>
private ContactPoints_Core contactPoints;
public ContactPoints_Core ContactPoints
{
get
{
return contactPoints;
}
set
{
contactPoints = value;
SetPropertyInstance(contactPoints);
}
}
/// <summary>
/// The basic containment relation between places.
/// </summary>
private ContainedIn_Core containedIn;
public ContainedIn_Core ContainedIn
{
get
{
return containedIn;
}
set
{
containedIn = value;
SetPropertyInstance(containedIn);
}
}
/// <summary>
/// The currency accepted (in <a href=\http://en.wikipedia.org/wiki/ISO_4217\ target=\new\>ISO 4217 currency format</a>).
/// </summary>
private CurrenciesAccepted_Core currenciesAccepted;
public CurrenciesAccepted_Core CurrenciesAccepted
{
get
{
return currenciesAccepted;
}
set
{
currenciesAccepted = value;
SetPropertyInstance(currenciesAccepted);
}
}
/// <summary>
/// A short description of the item.
/// </summary>
private Description_Core description;
public Description_Core Description
{
get
{
return description;
}
set
{
description = value;
SetPropertyInstance(description);
}
}
/// <summary>
/// Email address.
/// </summary>
private Email_Core email;
public Email_Core Email
{
get
{
return email;
}
set
{
email = value;
SetPropertyInstance(email);
}
}
/// <summary>
/// People working for this organization.
/// </summary>
private Employees_Core employees;
public Employees_Core Employees
{
get
{
return employees;
}
set
{
employees = value;
SetPropertyInstance(employees);
}
}
/// <summary>
/// Upcoming or past events associated with this place or organization.
/// </summary>
private Events_Core events;
public Events_Core Events
{
get
{
return events;
}
set
{
events = value;
SetPropertyInstance(events);
}
}
/// <summary>
/// The fax number.
/// </summary>
private FaxNumber_Core faxNumber;
public FaxNumber_Core FaxNumber
{
get
{
return faxNumber;
}
set
{
faxNumber = value;
SetPropertyInstance(faxNumber);
}
}
/// <summary>
/// A person who founded this organization.
/// </summary>
private Founders_Core founders;
public Founders_Core Founders
{
get
{
return founders;
}
set
{
founders = value;
SetPropertyInstance(founders);
}
}
/// <summary>
/// The date that this organization was founded.
/// </summary>
private FoundingDate_Core foundingDate;
public FoundingDate_Core FoundingDate
{
get
{
return foundingDate;
}
set
{
foundingDate = value;
SetPropertyInstance(foundingDate);
}
}
/// <summary>
/// The geo coordinates of the place.
/// </summary>
private Geo_Core geo;
public Geo_Core Geo
{
get
{
return geo;
}
set
{
geo = value;
SetPropertyInstance(geo);
}
}
/// <summary>
/// URL of an image of the item.
/// </summary>
private Image_Core image;
public Image_Core Image
{
get
{
return image;
}
set
{
image = value;
SetPropertyInstance(image);
}
}
/// <summary>
/// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>.
/// </summary>
private InteractionCount_Core interactionCount;
public InteractionCount_Core InteractionCount
{
get
{
return interactionCount;
}
set
{
interactionCount = value;
SetPropertyInstance(interactionCount);
}
}
/// <summary>
/// The location of the event or organization.
/// </summary>
private Location_Core location;
public Location_Core Location
{
get
{
return location;
}
set
{
location = value;
SetPropertyInstance(location);
}
}
/// <summary>
/// A URL to a map of the place.
/// </summary>
private Maps_Core maps;
public Maps_Core Maps
{
get
{
return maps;
}
set
{
maps = value;
SetPropertyInstance(maps);
}
}
/// <summary>
/// A member of this organization.
/// </summary>
private Members_Core members;
public Members_Core Members
{
get
{
return members;
}
set
{
members = value;
SetPropertyInstance(members);
}
}
/// <summary>
/// The name of the item.
/// </summary>
private Name_Core name;
public Name_Core Name
{
get
{
return name;
}
set
{
name = value;
SetPropertyInstance(name);
}
}
/// <summary>
/// The opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'.<br/>- Days are specified using the following two-letter combinations: <code>Mo</code>, <code>Tu</code>, <code>We</code>, <code>Th</code>, <code>Fr</code>, <code>Sa</code>, <code>Su</code>.<br/>- Times are specified using 24:00 time. For example, 3pm is specified as <code>15:00</code>. <br/>- Here is an example: <code><time itemprop=\openingHours\ datetime=\Tu,Th 16:00-20:00\>Tuesdays and Thursdays 4-8pm</time></code>. <br/>- If a business is open 7 days a week, then it can be specified as <code><time itemprop=\openingHours\ datetime=\Mo-Su\>Monday through Sunday, all day</time></code>.
/// </summary>
private OpeningHours_Core openingHours;
public OpeningHours_Core OpeningHours
{
get
{
return openingHours;
}
set
{
openingHours = value;
SetPropertyInstance(openingHours);
}
}
/// <summary>
/// Cash, credit card, etc.
/// </summary>
private PaymentAccepted_Core paymentAccepted;
public PaymentAccepted_Core PaymentAccepted
{
get
{
return paymentAccepted;
}
set
{
paymentAccepted = value;
SetPropertyInstance(paymentAccepted);
}
}
/// <summary>
/// Photographs of this place.
/// </summary>
private Photos_Core photos;
public Photos_Core Photos
{
get
{
return photos;
}
set
{
photos = value;
SetPropertyInstance(photos);
}
}
/// <summary>
/// The price range of the business, for example <code>$$$</code>.
/// </summary>
private PriceRange_Core priceRange;
public PriceRange_Core PriceRange
{
get
{
return priceRange;
}
set
{
priceRange = value;
SetPropertyInstance(priceRange);
}
}
/// <summary>
/// Review of the item.
/// </summary>
private Reviews_Core reviews;
public Reviews_Core Reviews
{
get
{
return reviews;
}
set
{
reviews = value;
SetPropertyInstance(reviews);
}
}
/// <summary>
/// The telephone number.
/// </summary>
private Telephone_Core telephone;
public Telephone_Core Telephone
{
get
{
return telephone;
}
set
{
telephone = value;
SetPropertyInstance(telephone);
}
}
/// <summary>
/// URL of the item.
/// </summary>
private Properties.URL_Core uRL;
public Properties.URL_Core URL
{
get
{
return uRL;
}
set
{
uRL = value;
SetPropertyInstance(uRL);
}
}
}
}
| |
// $Id$
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
using System;
using System.Diagnostics;
namespace Org.Apache.Etch.Bindings.Csharp.Util
{
/// <summary>
/// Packetizes a stream data source. Reads a packet header,
/// a 32-bit flag and a 32-bit length, little-endian, verifies
/// the flag, and then, using the length from the header,
/// reads the packet data and passes it to the packet handler.
/// As a packet source, accepts a packet and prepends a packet
/// header to it before delivering it to a data source.
/// </summary>
public class Packetizer : SessionData, TransportPacket
{
/// <summary>
/// URI term to specify max packet size
/// </summary>
public const String MAX_PKT_SIZE_TERM = "Packetizer.maxPktSize";
private const int SIG = unchecked( (int) 0xdeadbeef );
private const int HEADER_SIZE = 8;
/// <summary>
/// The default maximum packet size that will be accepted, 16376 bytes.
/// </summary>
public const int DEFAULT_MAX_PKT_SIZE = 16384 - HEADER_SIZE;
/// <summary>
/// Constructs the Packetizer with the specified transport
/// and the packet size.
/// </summary>
/// <param name="transport">Transport to send data</param>
/// <param name="maxPktSize">the maximum packet size that will be accepted.
/// Must be >= 0. If maxPktSize == 0, the default will be used.</param>
private Packetizer( TransportData transport, int maxPktSize )
{
if ( maxPktSize < 0 )
throw new ArgumentOutOfRangeException( "maxPktSize < 0" );
this.transport = transport;
this.maxPktSize = maxPktSize;
transport.SetSession(this);
}
public Packetizer( TransportData transport, URL uri, Resources resources )
: this( transport, (int)uri.GetIntegerTerm( MAX_PKT_SIZE_TERM, DEFAULT_MAX_PKT_SIZE ) )
{
// nothing to do.
}
public Packetizer(TransportData transport, String uri, Resources resources)
: this(transport, new URL(uri), resources)
{
// nothing to do.
}
private readonly TransportData transport;
private SessionPacket session;
private readonly int maxPktSize;
public override string ToString()
{
return String.Format("Packetizer / {0}", transport);
}
private bool wantHeader = true;
private int bodyLen;
private readonly FlexBuffer savedBuf = new FlexBuffer();
private int ProcessHeader( FlexBuffer buf, bool reset )
{
int sig = buf.GetInt();
if ( sig != SIG )
throw new Exception( "bad SIG" );
int pktSize = buf.GetInt();
if ( reset )
buf.Reset();
if ( pktSize < 0 || (maxPktSize > 0 && pktSize > maxPktSize) )
throw new Exception( "pktSize < 0 || (maxPktSize > 0 && pktSize > maxPktSize)" );
return pktSize;
}
public int HeaderSize()
{
return HEADER_SIZE;
}
public Object SessionQuery( Object query )
{
return session.SessionQuery( query );
}
public void SessionControl( Object control, Object value )
{
session.SessionControl( control, value );
}
public void SessionNotify( Object eventObj )
{
session.SessionNotify( eventObj );
}
public Object TransportQuery( Object query )
{
return transport.TransportQuery( query );
}
public void TransportControl( Object control, Object value )
{
transport.TransportControl( control, value );
}
public void TransportNotify( Object eventObj )
{
transport.TransportNotify( eventObj );
}
#region TransportPacket Members
public void SetSession(SessionPacket session)
{
this.session = session;
}
public SessionPacket GetSession()
{
return this.session;
}
public void TransportPacket(Who recipient, FlexBuffer buf)
{
// Data-ize the packet
// assert index is at the start of the header.
int dataSize = buf.Avail();
if (dataSize < HEADER_SIZE)
throw new ArgumentException("dataSize < HEADER_SIZE");
int pktSize = dataSize - HEADER_SIZE;
if (maxPktSize > 0 && pktSize > maxPktSize)
throw new ArgumentException( "maxPktSize > 0 && pktSize > maxPktSize" );
int index = buf.Index();
buf.PutInt(SIG);
buf.PutInt(pktSize);
buf.SetIndex(index);
transport.TransportData(recipient, buf);
}
#endregion
#region SessionData Members
public void SessionData(Who sender, FlexBuffer buf)
{
while (buf.Avail() > 0)
{
if (wantHeader)
{
// do we have enough to make a header
if ((savedBuf.Length() + buf.Avail()) >= HEADER_SIZE)
{
int pktSize;
if (savedBuf.Length() == 0)
{
// savedBuf is empty, entire header in buf.
pktSize = ProcessHeader(buf, false);
}
else // header split across savedBuf and buf
{
// move just enough data from buf to savedBuf to have a header.
int needFromBuf = HEADER_SIZE - savedBuf.Length();
savedBuf.Put(buf, needFromBuf);
savedBuf.SetIndex(0);
pktSize = ProcessHeader(savedBuf, true);
}
if (pktSize == 0)
continue;
bodyLen = pktSize;
wantHeader = false;
}
else // want header but not enough space to make it
{
// save buf in savedBuf.
savedBuf.SetIndex(savedBuf.Length());
savedBuf.Put(buf);
}
}
else if ((savedBuf.Length() + buf.Avail()) >= bodyLen)
{
// want body, and there's enough to make it.
// three possible cases: the body is entirely in savedBuf,
// the body is split, or the body is entirely in buf. assert
// that the body cannot entirely be in savedBuf, or else
// we'd have processed it last time.
Debug.Assert(savedBuf.Length() < bodyLen);
if (savedBuf.Length() == 0)
{
// savedBuf is empty, entire body in buf.
int length = buf.Length();
int index = buf.Index();
buf.SetLength(index + bodyLen);
// handler.Packet(sender, buf);
session.SessionPacket(sender,buf);
buf.SetLength(length);
buf.SetIndex(index + bodyLen);
wantHeader = true;
}
else // body split across savedBuf and buf
{
// move just enough data from buf to savedBuf to have a body.
int needFromBuf = bodyLen - savedBuf.Length();
savedBuf.Put(buf, needFromBuf);
savedBuf.SetIndex(0);
// handler.Packet(sender, savedBuf);
session.SessionPacket(sender,savedBuf);
savedBuf.Reset();
wantHeader = true;
}
}
else // want body, but there's not enough to make it.
{
// save buf in savedBuf.
savedBuf.Put(buf);
}
}
// buf is now empty, and there's nothing else to do.
Debug.Assert(buf.Avail() == 0);
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using NBM.Plugin;
// 26/6/03
namespace NBM.OptionNodes
{
/// <summary>
/// Basic protocol options - stuff like username, password and server information
/// </summary>
public class BasicProtocolOptions : System.Windows.Forms.UserControl, IOptions
{
private ProtocolSettings settings;
private System.Windows.Forms.TextBox usernameTextBox;
private System.Windows.Forms.Label usernameLabel;
private System.Windows.Forms.Label passwordLabel;
private System.Windows.Forms.TextBox passwordTextBox;
private System.Windows.Forms.CheckBox savePasswordCheckBox;
private System.Windows.Forms.GroupBox authenticationGroupBox;
private System.Windows.Forms.GroupBox serverInfoGroupBox;
private System.Windows.Forms.Label portLabel;
private System.Windows.Forms.Label hostLabel;
private System.Windows.Forms.TextBox portTextBox;
private System.Windows.Forms.TextBox hostTextBox;
private System.Windows.Forms.CheckBox enableCheckBox;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
/// <summary>
/// Constructs a basic protocol options object.
/// </summary>
/// <param name="settings"></param>
public BasicProtocolOptions(ProtocolSettings settings)
{
this.settings = settings;
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
// load up defaults
this.enableCheckBox.Checked = settings.Enabled;
this.usernameTextBox.Text = settings.Username;
this.passwordTextBox.Text = settings.Password;
this.savePasswordCheckBox.Checked = settings.RememberPassword;
this.hostTextBox.Text = settings.ServerHost;
this.portTextBox.Text = settings.ServerPort.ToString();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
/// <summary>
/// Name of node
/// </summary>
public string NodeName
{
get { return "Basic"; }
}
/// <summary>
/// Saves the information from the form to the ProtocolSettings object.
/// </summary>
public void Save()
{
this.settings.Enabled = this.enableCheckBox.Checked;
this.settings.Username = this.usernameTextBox.Text;
this.settings.Password = this.passwordTextBox.Text;
this.settings.RememberPassword = this.savePasswordCheckBox.Checked;
this.settings.ServerHost = this.hostTextBox.Text;
this.settings.ServerPort = int.Parse(this.portTextBox.Text);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.authenticationGroupBox = new System.Windows.Forms.GroupBox();
this.savePasswordCheckBox = new System.Windows.Forms.CheckBox();
this.passwordLabel = new System.Windows.Forms.Label();
this.passwordTextBox = new System.Windows.Forms.TextBox();
this.usernameLabel = new System.Windows.Forms.Label();
this.usernameTextBox = new System.Windows.Forms.TextBox();
this.enableCheckBox = new System.Windows.Forms.CheckBox();
this.serverInfoGroupBox = new System.Windows.Forms.GroupBox();
this.portLabel = new System.Windows.Forms.Label();
this.portTextBox = new System.Windows.Forms.TextBox();
this.hostLabel = new System.Windows.Forms.Label();
this.hostTextBox = new System.Windows.Forms.TextBox();
this.authenticationGroupBox.SuspendLayout();
this.serverInfoGroupBox.SuspendLayout();
this.SuspendLayout();
//
// authenticationGroupBox
//
this.authenticationGroupBox.Controls.AddRange(new System.Windows.Forms.Control[] {
this.savePasswordCheckBox,
this.passwordLabel,
this.passwordTextBox,
this.usernameLabel,
this.usernameTextBox});
this.authenticationGroupBox.Location = new System.Drawing.Point(8, 32);
this.authenticationGroupBox.Name = "authenticationGroupBox";
this.authenticationGroupBox.Size = new System.Drawing.Size(384, 104);
this.authenticationGroupBox.TabIndex = 0;
this.authenticationGroupBox.TabStop = false;
this.authenticationGroupBox.Text = "Authentication";
//
// savePasswordCheckBox
//
this.savePasswordCheckBox.Location = new System.Drawing.Point(144, 80);
this.savePasswordCheckBox.Name = "savePasswordCheckBox";
this.savePasswordCheckBox.Size = new System.Drawing.Size(200, 16);
this.savePasswordCheckBox.TabIndex = 5;
this.savePasswordCheckBox.Text = "Save password";
//
// passwordLabel
//
this.passwordLabel.Location = new System.Drawing.Point(16, 48);
this.passwordLabel.Name = "passwordLabel";
this.passwordLabel.Size = new System.Drawing.Size(120, 16);
this.passwordLabel.TabIndex = 4;
this.passwordLabel.Text = "Password:";
this.passwordLabel.TextAlign = System.Drawing.ContentAlignment.BottomRight;
//
// passwordTextBox
//
this.passwordTextBox.Location = new System.Drawing.Point(144, 48);
this.passwordTextBox.Name = "passwordTextBox";
this.passwordTextBox.PasswordChar = '*';
this.passwordTextBox.Size = new System.Drawing.Size(200, 20);
this.passwordTextBox.TabIndex = 3;
this.passwordTextBox.Text = "";
//
// usernameLabel
//
this.usernameLabel.Location = new System.Drawing.Point(16, 24);
this.usernameLabel.Name = "usernameLabel";
this.usernameLabel.Size = new System.Drawing.Size(120, 16);
this.usernameLabel.TabIndex = 2;
this.usernameLabel.Text = "Username:";
this.usernameLabel.TextAlign = System.Drawing.ContentAlignment.BottomRight;
//
// usernameTextBox
//
this.usernameTextBox.Location = new System.Drawing.Point(144, 24);
this.usernameTextBox.Name = "usernameTextBox";
this.usernameTextBox.Size = new System.Drawing.Size(200, 20);
this.usernameTextBox.TabIndex = 1;
this.usernameTextBox.Text = "";
//
// enableCheckBox
//
this.enableCheckBox.BackColor = System.Drawing.SystemColors.Control;
this.enableCheckBox.Checked = true;
this.enableCheckBox.CheckState = System.Windows.Forms.CheckState.Checked;
this.enableCheckBox.Location = new System.Drawing.Point(8, 8);
this.enableCheckBox.Name = "enableCheckBox";
this.enableCheckBox.Size = new System.Drawing.Size(96, 16);
this.enableCheckBox.TabIndex = 1;
this.enableCheckBox.Text = " Enable";
this.enableCheckBox.CheckedChanged += new System.EventHandler(this.enableCheckBox_CheckedChanged);
//
// serverInfoGroupBox
//
this.serverInfoGroupBox.Controls.AddRange(new System.Windows.Forms.Control[] {
this.portLabel,
this.portTextBox,
this.hostLabel,
this.hostTextBox});
this.serverInfoGroupBox.Location = new System.Drawing.Point(8, 152);
this.serverInfoGroupBox.Name = "serverInfoGroupBox";
this.serverInfoGroupBox.Size = new System.Drawing.Size(384, 80);
this.serverInfoGroupBox.TabIndex = 14;
this.serverInfoGroupBox.TabStop = false;
this.serverInfoGroupBox.Text = "Server Information";
//
// portLabel
//
this.portLabel.Location = new System.Drawing.Point(16, 48);
this.portLabel.Name = "portLabel";
this.portLabel.Size = new System.Drawing.Size(120, 16);
this.portLabel.TabIndex = 17;
this.portLabel.Text = "Port:";
this.portLabel.TextAlign = System.Drawing.ContentAlignment.BottomRight;
//
// portTextBox
//
this.portTextBox.Location = new System.Drawing.Point(144, 48);
this.portTextBox.Name = "portTextBox";
this.portTextBox.Size = new System.Drawing.Size(200, 20);
this.portTextBox.TabIndex = 16;
this.portTextBox.Text = "";
//
// hostLabel
//
this.hostLabel.Location = new System.Drawing.Point(16, 24);
this.hostLabel.Name = "hostLabel";
this.hostLabel.Size = new System.Drawing.Size(120, 16);
this.hostLabel.TabIndex = 15;
this.hostLabel.Text = "Host:";
this.hostLabel.TextAlign = System.Drawing.ContentAlignment.BottomRight;
//
// hostTextBox
//
this.hostTextBox.Location = new System.Drawing.Point(144, 24);
this.hostTextBox.Name = "hostTextBox";
this.hostTextBox.Size = new System.Drawing.Size(200, 20);
this.hostTextBox.TabIndex = 14;
this.hostTextBox.Text = "";
//
// BasicProtocolOptions
//
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.serverInfoGroupBox,
this.enableCheckBox,
this.authenticationGroupBox});
this.Name = "BasicProtocolOptions";
this.Size = new System.Drawing.Size(400, 320);
this.authenticationGroupBox.ResumeLayout(false);
this.serverInfoGroupBox.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void enableCheckBox_CheckedChanged(object sender, System.EventArgs e)
{
this.authenticationGroupBox.Enabled =
this.serverInfoGroupBox.Enabled = this.enableCheckBox.Checked;
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2014 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.Globalization;
using System.Diagnostics;
using System.IO;
using System.Threading;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal.Execution;
#if !SILVERLIGHT && !NETCF && !PORTABLE
using System.Runtime.Remoting.Messaging;
using System.Security.Principal;
using NUnit.Framework.Compatibility;
#endif
namespace NUnit.Framework.Internal
{
/// <summary>
/// Helper class used to save and restore certain static or
/// singleton settings in the environment that affect tests
/// or which might be changed by the user tests.
///
/// An internal class is used to hold settings and a stack
/// of these objects is pushed and popped as Save and Restore
/// are called.
/// </summary>
public class TestExecutionContext
#if !SILVERLIGHT && !NETCF && !PORTABLE
: LongLivedMarshalByRefObject, ILogicalThreadAffinative
#endif
{
// NOTE: Be very careful when modifying this class. It uses
// conditional compilation extensively and you must give
// thought to whether any new features will be supported
// on each platform. In particular, instance fields,
// properties, initialization and restoration must all
// use the same conditions for each feature.
#region Instance Fields
/// <summary>
/// Link to a prior saved context
/// </summary>
private TestExecutionContext _priorContext;
/// <summary>
/// Indicates that a stop has been requested
/// </summary>
private TestExecutionStatus _executionStatus;
/// <summary>
/// The event listener currently receiving notifications
/// </summary>
private ITestListener _listener = TestListener.NULL;
/// <summary>
/// The number of assertions for the current test
/// </summary>
private int _assertCount;
private Randomizer _randomGenerator;
private IWorkItemDispatcher _dispatcher;
/// <summary>
/// The current culture
/// </summary>
private CultureInfo _currentCulture;
/// <summary>
/// The current UI culture
/// </summary>
private CultureInfo _currentUICulture;
/// <summary>
/// The current test result
/// </summary>
private TestResult _currentResult;
#if !NETCF && !SILVERLIGHT && !PORTABLE
/// <summary>
/// The current Principal.
/// </summary>
private IPrincipal _currentPrincipal;
#endif
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="TestExecutionContext"/> class.
/// </summary>
public TestExecutionContext()
{
_priorContext = null;
this.TestCaseTimeout = 0;
this.UpstreamActions = new List<ITestAction>();
_currentCulture = CultureInfo.CurrentCulture;
_currentUICulture = CultureInfo.CurrentUICulture;
#if !NETCF && !SILVERLIGHT && !PORTABLE
_currentPrincipal = Thread.CurrentPrincipal;
#endif
}
/// <summary>
/// Initializes a new instance of the <see cref="TestExecutionContext"/> class.
/// </summary>
/// <param name="other">An existing instance of TestExecutionContext.</param>
public TestExecutionContext(TestExecutionContext other)
{
_priorContext = other;
this.CurrentTest = other.CurrentTest;
this.CurrentResult = other.CurrentResult;
this.TestObject = other.TestObject;
this.WorkDirectory = other.WorkDirectory;
_listener = other._listener;
this.StopOnError = other.StopOnError;
this.TestCaseTimeout = other.TestCaseTimeout;
this.UpstreamActions = new List<ITestAction>(other.UpstreamActions);
_currentCulture = CultureInfo.CurrentCulture;
_currentUICulture = CultureInfo.CurrentUICulture;
#if !NETCF && !SILVERLIGHT && !PORTABLE
_currentPrincipal = other.CurrentPrincipal;
#endif
this.Dispatcher = other.Dispatcher;
this.ParallelScope = other.ParallelScope;
}
#endregion
#region Static Singleton Instance
/// <summary>
/// The current context, head of the list of saved contexts.
/// </summary>
#if SILVERLIGHT || PORTABLE
[ThreadStatic]
private static TestExecutionContext current;
#elif NETCF
private static LocalDataStoreSlot slotContext = Thread.AllocateDataSlot();
#else
private static readonly string CONTEXT_KEY = "NUnit.Framework.TestContext";
#endif
/// <summary>
/// Gets the current context.
/// </summary>
/// <value>The current context.</value>
public static TestExecutionContext CurrentContext
{
get
{
// If a user creates a thread then the current context
// will be null. This also happens when the compiler
// automatically creates threads for async methods.
// We create a new context, which is automatically
// populated with _values taken from the current thread.
#if SILVERLIGHT || PORTABLE
if (current == null)
current = new TestExecutionContext();
return current;
#elif NETCF
var current = (TestExecutionContext)Thread.GetData(slotContext);
if (current == null)
{
current = new TestExecutionContext();
Thread.SetData(slotContext, current);
}
return current;
#else
var context = GetTestExecutionContext();
if (context == null) // This can happen on Mono
{
context = new TestExecutionContext();
CallContext.SetData(CONTEXT_KEY, context);
}
return context;
#endif
}
private set
{
#if SILVERLIGHT || PORTABLE
current = value;
#elif NETCF
Thread.SetData(slotContext, value);
#else
if (value == null)
CallContext.FreeNamedDataSlot(CONTEXT_KEY);
else
CallContext.SetData(CONTEXT_KEY, value);
#endif
}
}
#if !SILVERLIGHT && !NETCF && !PORTABLE
/// <summary>
/// Get the current context or return null if none is found.
/// </summary>
public static TestExecutionContext GetTestExecutionContext()
{
return CallContext.GetData(CONTEXT_KEY) as TestExecutionContext;
}
#endif
/// <summary>
/// Clear the current context. This is provided to
/// prevent "leakage" of the CallContext containing
/// the current context back to any runners.
/// </summary>
public static void ClearCurrentContext()
{
CurrentContext = null;
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the current test
/// </summary>
public Test CurrentTest { get; set; }
/// <summary>
/// The time the current test started execution
/// </summary>
public DateTime StartTime { get; set; }
/// <summary>
/// The time the current test started in Ticks
/// </summary>
public long StartTicks { get; set; }
/// <summary>
/// Gets or sets the current test result
/// </summary>
public TestResult CurrentResult
{
get { return _currentResult; }
set
{
_currentResult = value;
if (value != null)
OutWriter = value.OutWriter;
}
}
/// <summary>
/// Gets a TextWriter that will send output to the current test result.
/// </summary>
public TextWriter OutWriter { get; private set; }
/// <summary>
/// The current test object - that is the user fixture
/// object on which tests are being executed.
/// </summary>
public object TestObject { get; set; }
/// <summary>
/// Get or set the working directory
/// </summary>
public string WorkDirectory { get; set; }
/// <summary>
/// Get or set indicator that run should stop on the first error
/// </summary>
public bool StopOnError { get; set; }
/// <summary>
/// Gets an enum indicating whether a stop has been requested.
/// </summary>
public TestExecutionStatus ExecutionStatus
{
get
{
// ExecutionStatus may have been set to StopRequested or AbortRequested
// in a prior context. If so, reflect the same setting in this context.
if (_executionStatus == TestExecutionStatus.Running && _priorContext != null)
_executionStatus = _priorContext.ExecutionStatus;
return _executionStatus;
}
set
{
_executionStatus = value;
// Push the same setting up to all prior contexts
if (_priorContext != null)
_priorContext.ExecutionStatus = value;
}
}
/// <summary>
/// The current test event listener
/// </summary>
internal ITestListener Listener
{
get { return _listener; }
set { _listener = value; }
}
/// <summary>
/// The current WorkItemDispatcher
/// </summary>
internal IWorkItemDispatcher Dispatcher
{
get
{
if (_dispatcher == null)
_dispatcher = new SimpleWorkItemDispatcher();
return _dispatcher;
}
set { _dispatcher = value; }
}
/// <summary>
/// The ParallelScope to be used by tests running in this context.
/// For builds with out the parallel feature, it has no effect.
/// </summary>
public ParallelScope ParallelScope { get; set; }
/// <summary>
/// Gets the RandomGenerator specific to this Test
/// </summary>
public Randomizer RandomGenerator
{
get
{
if (_randomGenerator == null)
_randomGenerator = new Randomizer(CurrentTest.Seed);
return _randomGenerator;
}
}
/// <summary>
/// Gets the assert count.
/// </summary>
/// <value>The assert count.</value>
internal int AssertCount
{
get { return _assertCount; }
}
/// <summary>
/// Gets or sets the test case timeout value
/// </summary>
public int TestCaseTimeout { get; set; }
/// <summary>
/// Gets a list of ITestActions set by upstream tests
/// </summary>
public List<ITestAction> UpstreamActions { get; private set; }
// TODO: Put in checks on all of these settings
// with side effects so we only change them
// if the value is different
/// <summary>
/// Saves or restores the CurrentCulture
/// </summary>
public CultureInfo CurrentCulture
{
get { return _currentCulture; }
set
{
_currentCulture = value;
#if !NETCF && !PORTABLE
Thread.CurrentThread.CurrentCulture = _currentCulture;
#endif
}
}
/// <summary>
/// Saves or restores the CurrentUICulture
/// </summary>
public CultureInfo CurrentUICulture
{
get { return _currentUICulture; }
set
{
_currentUICulture = value;
#if !NETCF && !PORTABLE
Thread.CurrentThread.CurrentUICulture = _currentUICulture;
#endif
}
}
#if !NETCF && !SILVERLIGHT && !PORTABLE
/// <summary>
/// Gets or sets the current <see cref="IPrincipal"/> for the Thread.
/// </summary>
public IPrincipal CurrentPrincipal
{
get { return _currentPrincipal; }
set
{
_currentPrincipal = value;
Thread.CurrentPrincipal = _currentPrincipal;
}
}
#endif
#endregion
#region Instance Methods
/// <summary>
/// Record any changes in the environment made by
/// the test code in the execution context so it
/// will be passed on to lower level tests.
/// </summary>
public void UpdateContextFromEnvironment()
{
_currentCulture = CultureInfo.CurrentCulture;
_currentUICulture = CultureInfo.CurrentUICulture;
#if !NETCF && !SILVERLIGHT && !PORTABLE
_currentPrincipal = Thread.CurrentPrincipal;
#endif
}
/// <summary>
/// Set up the execution environment to match a context.
/// Note that we may be running on the same thread where the
/// context was initially created or on a different thread.
/// </summary>
public void EstablishExecutionEnvironment()
{
#if !NETCF && !PORTABLE
Thread.CurrentThread.CurrentCulture = _currentCulture;
Thread.CurrentThread.CurrentUICulture = _currentUICulture;
#endif
#if !NETCF && !SILVERLIGHT && !PORTABLE
Thread.CurrentPrincipal = _currentPrincipal;
#endif
CurrentContext = this;
}
/// <summary>
/// Increments the assert count by one.
/// </summary>
public void IncrementAssertCount()
{
Interlocked.Increment(ref _assertCount);
}
/// <summary>
/// Increments the assert count by a specified amount.
/// </summary>
public void IncrementAssertCount(int count)
{
// TODO: Temporary implementation
while (count-- > 0)
Interlocked.Increment(ref _assertCount);
}
#endregion
#region InitializeLifetimeService
#if !SILVERLIGHT && !NETCF && !PORTABLE
/// <summary>
/// Obtain lifetime service object
/// </summary>
/// <returns></returns>
public override object InitializeLifetimeService()
{
return null;
}
#endif
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using Microsoft.Research.AbstractDomains.Numerical;
using System.Diagnostics.Contracts;
namespace Microsoft.Research.AbstractDomains
{
[ContractClass(typeof(IFactoryContracts<>))]
public interface IFactory<T>
{
IFactory<T> FactoryWithName(T name);
T IdentityForAnd { get; }
T IdentityForOr { get; }
T IdentityForAdd { get; }
T Null { get; }
T Constant(Int32 constant);
T Constant(Int64 constant);
T Constant(Rational constant);
T Constant(bool constant);
T Constant(double constant);
T Variable(object variable);
T Add(T left, T right);
T Sub(T left, T right);
T Mul(T left, T right);
T Div(T left, T right);
T EqualTo(T left, T right);
T NotEqualTo(T left, T right);
T LessThan(T left, T right);
T LessEqualThan(T left, T right);
T And(T left, T right);
T Or(T left, T right);
T ArrayIndex(T array, T index);
T ForAll(T inf, T sup, T body);
T Exists(T inf, T sup, T body);
bool TryGetName(out T name);
bool TryGetBoundVariable(out T boundVariable);
bool TryArrayLengthName(T array, out T name);
List<T> SplitAnd(T t);
}
#region Contracts
[ContractClassFor(typeof(IFactory<>))]
internal abstract class IFactoryContracts<T>
: IFactory<T>
{
#region IFactory<T> Members
public IFactory<T> FactoryWithName(T name)
{
Contract.Ensures(Contract.Result<IFactory<T>>() != null);
throw new NotImplementedException();
}
public T Constant(int constant)
{
throw new NotImplementedException();
}
public T Constant(long constant)
{
throw new NotImplementedException();
}
public T Constant(Rational constant)
{
throw new NotImplementedException();
}
public T Constant(bool constant)
{
throw new NotImplementedException();
}
public T Constant(double constant)
{
throw new NotImplementedException();
}
public T Variable(object variable)
{
throw new NotImplementedException();
}
public T Add(T left, T right)
{
throw new NotImplementedException();
}
public T Sub(T left, T right)
{
throw new NotImplementedException();
}
public T Mul(T left, T right)
{
throw new NotImplementedException();
}
public T Div(T left, T right)
{
throw new NotImplementedException();
}
public T EqualTo(T left, T right)
{
throw new NotImplementedException();
}
public T NotEqualTo(T left, T right)
{
throw new NotImplementedException();
}
public T LessThan(T left, T right)
{
throw new NotImplementedException();
}
public T LessEqualThan(T left, T right)
{
throw new NotImplementedException();
}
public T And(T left, T right)
{
throw new NotImplementedException();
}
public T Or(T left, T right)
{
throw new NotImplementedException();
}
public T IdentityForAnd
{
get { throw new NotImplementedException(); }
}
public T IdentityForOr
{
get { throw new NotImplementedException(); }
}
public T IdentityForAdd
{
get { throw new NotImplementedException(); }
}
public T ArrayIndex(T array, T Index)
{
throw new NotImplementedException();
}
public T ForAll(T inf, T sup, T body)
{
Contract.Requires(inf != null);
Contract.Requires(sup != null);
Contract.Requires(body != null);
throw new NotImplementedException();
}
public T Exists(T inf, T sup, T body)
{
Contract.Requires(inf != null);
Contract.Requires(sup != null);
Contract.Requires(body != null);
throw new NotImplementedException();
}
public bool TryGetName(out T name)
{
throw new NotImplementedException();
}
public bool TryArrayLengthName(T array, out T name)
{
throw new NotImplementedException();
}
public bool TryGetBoundVariable(out T name)
{
throw new NotImplementedException();
}
public List<T> SplitAnd(T t)
{
Contract.Ensures(Contract.Result<List<T>>() != null);
throw new NotImplementedException();
}
#endregion
#region IFactory<T> Members
public T Null
{
get { throw new NotImplementedException(); }
}
#endregion
}
#endregion
}
| |
/*
* UltraCart Rest API V2
*
* UltraCart REST API Version 2
*
* OpenAPI spec version: 2.0.0
* 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;
using SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter;
namespace com.ultracart.admin.v2.Model
{
/// <summary>
/// OrderBilling
/// </summary>
[DataContract]
public partial class OrderBilling : IEquatable<OrderBilling>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="OrderBilling" /> class.
/// </summary>
/// <param name="address1">Address line 1.</param>
/// <param name="address2">Address line 2.</param>
/// <param name="ccEmails">CC emails. Multiple allowed, but total length of all emails can not exceed 100 characters..</param>
/// <param name="city">City.</param>
/// <param name="company">Company.</param>
/// <param name="countryCode">ISO-3166 two letter country code.</param>
/// <param name="dayPhone">Day time phone.</param>
/// <param name="dayPhoneE164">Day time phone (E164 format).</param>
/// <param name="email">Email.</param>
/// <param name="eveningPhone">Evening phone.</param>
/// <param name="eveningPhoneE164">Evening phone (E164 format).</param>
/// <param name="firstName">First name.</param>
/// <param name="lastName">Last name.</param>
/// <param name="postalCode">Postal code.</param>
/// <param name="stateRegion">State for United States otherwise region or province for other countries.</param>
/// <param name="title">Title.</param>
public OrderBilling(string address1 = default(string), string address2 = default(string), List<string> ccEmails = default(List<string>), string city = default(string), string company = default(string), string countryCode = default(string), string dayPhone = default(string), string dayPhoneE164 = default(string), string email = default(string), string eveningPhone = default(string), string eveningPhoneE164 = default(string), string firstName = default(string), string lastName = default(string), string postalCode = default(string), string stateRegion = default(string), string title = default(string))
{
this.Address1 = address1;
this.Address2 = address2;
this.CcEmails = ccEmails;
this.City = city;
this.Company = company;
this.CountryCode = countryCode;
this.DayPhone = dayPhone;
this.DayPhoneE164 = dayPhoneE164;
this.Email = email;
this.EveningPhone = eveningPhone;
this.EveningPhoneE164 = eveningPhoneE164;
this.FirstName = firstName;
this.LastName = lastName;
this.PostalCode = postalCode;
this.StateRegion = stateRegion;
this.Title = title;
}
/// <summary>
/// Address line 1
/// </summary>
/// <value>Address line 1</value>
[DataMember(Name="address1", EmitDefaultValue=false)]
public string Address1 { get; set; }
/// <summary>
/// Address line 2
/// </summary>
/// <value>Address line 2</value>
[DataMember(Name="address2", EmitDefaultValue=false)]
public string Address2 { get; set; }
/// <summary>
/// CC emails. Multiple allowed, but total length of all emails can not exceed 100 characters.
/// </summary>
/// <value>CC emails. Multiple allowed, but total length of all emails can not exceed 100 characters.</value>
[DataMember(Name="cc_emails", EmitDefaultValue=false)]
public List<string> CcEmails { get; set; }
/// <summary>
/// City
/// </summary>
/// <value>City</value>
[DataMember(Name="city", EmitDefaultValue=false)]
public string City { get; set; }
/// <summary>
/// Company
/// </summary>
/// <value>Company</value>
[DataMember(Name="company", EmitDefaultValue=false)]
public string Company { get; set; }
/// <summary>
/// ISO-3166 two letter country code
/// </summary>
/// <value>ISO-3166 two letter country code</value>
[DataMember(Name="country_code", EmitDefaultValue=false)]
public string CountryCode { get; set; }
/// <summary>
/// Day time phone
/// </summary>
/// <value>Day time phone</value>
[DataMember(Name="day_phone", EmitDefaultValue=false)]
public string DayPhone { get; set; }
/// <summary>
/// Day time phone (E164 format)
/// </summary>
/// <value>Day time phone (E164 format)</value>
[DataMember(Name="day_phone_e164", EmitDefaultValue=false)]
public string DayPhoneE164 { get; set; }
/// <summary>
/// Email
/// </summary>
/// <value>Email</value>
[DataMember(Name="email", EmitDefaultValue=false)]
public string Email { get; set; }
/// <summary>
/// Evening phone
/// </summary>
/// <value>Evening phone</value>
[DataMember(Name="evening_phone", EmitDefaultValue=false)]
public string EveningPhone { get; set; }
/// <summary>
/// Evening phone (E164 format)
/// </summary>
/// <value>Evening phone (E164 format)</value>
[DataMember(Name="evening_phone_e164", EmitDefaultValue=false)]
public string EveningPhoneE164 { get; set; }
/// <summary>
/// First name
/// </summary>
/// <value>First name</value>
[DataMember(Name="first_name", EmitDefaultValue=false)]
public string FirstName { get; set; }
/// <summary>
/// Last name
/// </summary>
/// <value>Last name</value>
[DataMember(Name="last_name", EmitDefaultValue=false)]
public string LastName { get; set; }
/// <summary>
/// Postal code
/// </summary>
/// <value>Postal code</value>
[DataMember(Name="postal_code", EmitDefaultValue=false)]
public string PostalCode { get; set; }
/// <summary>
/// State for United States otherwise region or province for other countries
/// </summary>
/// <value>State for United States otherwise region or province for other countries</value>
[DataMember(Name="state_region", EmitDefaultValue=false)]
public string StateRegion { get; set; }
/// <summary>
/// Title
/// </summary>
/// <value>Title</value>
[DataMember(Name="title", EmitDefaultValue=false)]
public string Title { 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 OrderBilling {\n");
sb.Append(" Address1: ").Append(Address1).Append("\n");
sb.Append(" Address2: ").Append(Address2).Append("\n");
sb.Append(" CcEmails: ").Append(CcEmails).Append("\n");
sb.Append(" City: ").Append(City).Append("\n");
sb.Append(" Company: ").Append(Company).Append("\n");
sb.Append(" CountryCode: ").Append(CountryCode).Append("\n");
sb.Append(" DayPhone: ").Append(DayPhone).Append("\n");
sb.Append(" DayPhoneE164: ").Append(DayPhoneE164).Append("\n");
sb.Append(" Email: ").Append(Email).Append("\n");
sb.Append(" EveningPhone: ").Append(EveningPhone).Append("\n");
sb.Append(" EveningPhoneE164: ").Append(EveningPhoneE164).Append("\n");
sb.Append(" FirstName: ").Append(FirstName).Append("\n");
sb.Append(" LastName: ").Append(LastName).Append("\n");
sb.Append(" PostalCode: ").Append(PostalCode).Append("\n");
sb.Append(" StateRegion: ").Append(StateRegion).Append("\n");
sb.Append(" Title: ").Append(Title).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 virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as OrderBilling);
}
/// <summary>
/// Returns true if OrderBilling instances are equal
/// </summary>
/// <param name="input">Instance of OrderBilling to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(OrderBilling input)
{
if (input == null)
return false;
return
(
this.Address1 == input.Address1 ||
(this.Address1 != null &&
this.Address1.Equals(input.Address1))
) &&
(
this.Address2 == input.Address2 ||
(this.Address2 != null &&
this.Address2.Equals(input.Address2))
) &&
(
this.CcEmails == input.CcEmails ||
this.CcEmails != null &&
this.CcEmails.SequenceEqual(input.CcEmails)
) &&
(
this.City == input.City ||
(this.City != null &&
this.City.Equals(input.City))
) &&
(
this.Company == input.Company ||
(this.Company != null &&
this.Company.Equals(input.Company))
) &&
(
this.CountryCode == input.CountryCode ||
(this.CountryCode != null &&
this.CountryCode.Equals(input.CountryCode))
) &&
(
this.DayPhone == input.DayPhone ||
(this.DayPhone != null &&
this.DayPhone.Equals(input.DayPhone))
) &&
(
this.DayPhoneE164 == input.DayPhoneE164 ||
(this.DayPhoneE164 != null &&
this.DayPhoneE164.Equals(input.DayPhoneE164))
) &&
(
this.Email == input.Email ||
(this.Email != null &&
this.Email.Equals(input.Email))
) &&
(
this.EveningPhone == input.EveningPhone ||
(this.EveningPhone != null &&
this.EveningPhone.Equals(input.EveningPhone))
) &&
(
this.EveningPhoneE164 == input.EveningPhoneE164 ||
(this.EveningPhoneE164 != null &&
this.EveningPhoneE164.Equals(input.EveningPhoneE164))
) &&
(
this.FirstName == input.FirstName ||
(this.FirstName != null &&
this.FirstName.Equals(input.FirstName))
) &&
(
this.LastName == input.LastName ||
(this.LastName != null &&
this.LastName.Equals(input.LastName))
) &&
(
this.PostalCode == input.PostalCode ||
(this.PostalCode != null &&
this.PostalCode.Equals(input.PostalCode))
) &&
(
this.StateRegion == input.StateRegion ||
(this.StateRegion != null &&
this.StateRegion.Equals(input.StateRegion))
) &&
(
this.Title == input.Title ||
(this.Title != null &&
this.Title.Equals(input.Title))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Address1 != null)
hashCode = hashCode * 59 + this.Address1.GetHashCode();
if (this.Address2 != null)
hashCode = hashCode * 59 + this.Address2.GetHashCode();
if (this.CcEmails != null)
hashCode = hashCode * 59 + this.CcEmails.GetHashCode();
if (this.City != null)
hashCode = hashCode * 59 + this.City.GetHashCode();
if (this.Company != null)
hashCode = hashCode * 59 + this.Company.GetHashCode();
if (this.CountryCode != null)
hashCode = hashCode * 59 + this.CountryCode.GetHashCode();
if (this.DayPhone != null)
hashCode = hashCode * 59 + this.DayPhone.GetHashCode();
if (this.DayPhoneE164 != null)
hashCode = hashCode * 59 + this.DayPhoneE164.GetHashCode();
if (this.Email != null)
hashCode = hashCode * 59 + this.Email.GetHashCode();
if (this.EveningPhone != null)
hashCode = hashCode * 59 + this.EveningPhone.GetHashCode();
if (this.EveningPhoneE164 != null)
hashCode = hashCode * 59 + this.EveningPhoneE164.GetHashCode();
if (this.FirstName != null)
hashCode = hashCode * 59 + this.FirstName.GetHashCode();
if (this.LastName != null)
hashCode = hashCode * 59 + this.LastName.GetHashCode();
if (this.PostalCode != null)
hashCode = hashCode * 59 + this.PostalCode.GetHashCode();
if (this.StateRegion != null)
hashCode = hashCode * 59 + this.StateRegion.GetHashCode();
if (this.Title != null)
hashCode = hashCode * 59 + this.Title.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
// Address1 (string) maxLength
if(this.Address1 != null && this.Address1.Length > 50)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Address1, length must be less than 50.", new [] { "Address1" });
}
// Address2 (string) maxLength
if(this.Address2 != null && this.Address2.Length > 50)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Address2, length must be less than 50.", new [] { "Address2" });
}
// City (string) maxLength
if(this.City != null && this.City.Length > 32)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for City, length must be less than 32.", new [] { "City" });
}
// Company (string) maxLength
if(this.Company != null && this.Company.Length > 50)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Company, length must be less than 50.", new [] { "Company" });
}
// CountryCode (string) maxLength
if(this.CountryCode != null && this.CountryCode.Length > 2)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for CountryCode, length must be less than 2.", new [] { "CountryCode" });
}
// DayPhone (string) maxLength
if(this.DayPhone != null && this.DayPhone.Length > 25)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for DayPhone, length must be less than 25.", new [] { "DayPhone" });
}
// DayPhoneE164 (string) maxLength
if(this.DayPhoneE164 != null && this.DayPhoneE164.Length > 25)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for DayPhoneE164, length must be less than 25.", new [] { "DayPhoneE164" });
}
// Email (string) maxLength
if(this.Email != null && this.Email.Length > 100)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Email, length must be less than 100.", new [] { "Email" });
}
// EveningPhone (string) maxLength
if(this.EveningPhone != null && this.EveningPhone.Length > 25)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for EveningPhone, length must be less than 25.", new [] { "EveningPhone" });
}
// EveningPhoneE164 (string) maxLength
if(this.EveningPhoneE164 != null && this.EveningPhoneE164.Length > 25)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for EveningPhoneE164, length must be less than 25.", new [] { "EveningPhoneE164" });
}
// FirstName (string) maxLength
if(this.FirstName != null && this.FirstName.Length > 30)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for FirstName, length must be less than 30.", new [] { "FirstName" });
}
// LastName (string) maxLength
if(this.LastName != null && this.LastName.Length > 30)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for LastName, length must be less than 30.", new [] { "LastName" });
}
// PostalCode (string) maxLength
if(this.PostalCode != null && this.PostalCode.Length > 20)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for PostalCode, length must be less than 20.", new [] { "PostalCode" });
}
// StateRegion (string) maxLength
if(this.StateRegion != null && this.StateRegion.Length > 32)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for StateRegion, length must be less than 32.", new [] { "StateRegion" });
}
// Title (string) maxLength
if(this.Title != null && this.Title.Length > 50)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Title, length must be less than 50.", new [] { "Title" });
}
yield break;
}
}
}
| |
using System;
using System.Collections.Generic;
using Xunit;
using Xunit.Extensions;
namespace Bugsnag.Test
{
public class MetadataTests
{
[Fact]
public void Constructor_NewMetadataContainsEmptyDataStore()
{
// Arrange + Act
var testMetadata = new Metadata();
// Assert
Assert.NotNull(testMetadata.MetadataStore);
Assert.Equal(0, testMetadata.MetadataStore.Count);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void AddToTab_AddingTabEntryToNewMetadata(bool useDefaultTab)
{
// Arrange
var testMetadata = new Metadata();
var testTabObject = new Object();
var tabName = useDefaultTab ? Metadata.DefaultTabName : "Test Tab";
// Act
if (useDefaultTab)
testMetadata.AddToTab("Test Key", testTabObject);
else
testMetadata.AddToTab("Test Tab", "Test Key", testTabObject);
// Assert
var testStore = testMetadata.MetadataStore;
Assert.Equal(1, testStore.Count);
Assert.Equal(1, testStore[tabName].Count);
Assert.Equal(testTabObject, testStore[tabName]["Test Key"]);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void AddToTab_AddingMultipleDifferentTabEntrysToSingleTab(bool useDefaultTab)
{
// Arrange
var testMetadata = new Metadata();
var testTabObject1 = "Random String";
var testTabObject2 = 34;
var testTabObject3 = new Object[] { 23, 24, 25, "Rt" };
var tabName = useDefaultTab ? Metadata.DefaultTabName : "Test Tab";
// Act
if (useDefaultTab)
{
testMetadata.AddToTab("Test Key 1", testTabObject1);
testMetadata.AddToTab("Test Key 2", testTabObject2);
testMetadata.AddToTab("Test Key 3", testTabObject3);
}
else
{
testMetadata.AddToTab("Test Tab", "Test Key 1", testTabObject1);
testMetadata.AddToTab("Test Tab", "Test Key 2", testTabObject2);
testMetadata.AddToTab("Test Tab", "Test Key 3", testTabObject3);
}
// Assert
var testStore = testMetadata.MetadataStore;
Assert.Equal(1, testStore.Count);
Assert.Equal(3, testStore[tabName].Count);
Assert.Equal(testTabObject1, testStore[tabName]["Test Key 1"]);
Assert.Equal(testTabObject2, testStore[tabName]["Test Key 2"]);
Assert.Equal(testTabObject3, testStore[tabName]["Test Key 3"]);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void AddToTab_AddingMultipleDifferentTabsEntryToMultipleTabs(bool useDefaultTab)
{
// Arrange
var testMetadata = new Metadata();
var testTab1Object1 = new Object();
var testTab1Object2 = 5;
var testTab2Object1 = new[] { "a", "b", "c" };
var testTab3Object1 = "My test";
var testTab3Object2 = DateTime.Now;
var testTab3Object3 = new Object();
// If we using the default tab, only use it for the first tab
var firstTabName = useDefaultTab ? Metadata.DefaultTabName : "Test Tab 1";
// Act
if (useDefaultTab)
{
testMetadata.AddToTab("Test Key 1", testTab1Object1);
testMetadata.AddToTab("Test Key 2", testTab1Object2);
}
else
{
testMetadata.AddToTab("Test Tab 1", "Test Key 1", testTab1Object1);
testMetadata.AddToTab("Test Tab 1", "Test Key 2", testTab1Object2);
}
testMetadata.AddToTab("Test Tab 2", "Test Key 1", testTab2Object1);
testMetadata.AddToTab("Test Tab 3", "Test Key 1", testTab3Object1);
testMetadata.AddToTab("Test Tab 3", "Test Key 2", testTab3Object2);
testMetadata.AddToTab("Test Tab 3", "Test Key 3", testTab3Object3);
// Assert
var testStore = testMetadata.MetadataStore;
Assert.Equal(3, testStore.Count);
Assert.Equal(2, testStore[firstTabName].Count);
Assert.Equal(1, testStore["Test Tab 2"].Count);
Assert.Equal(3, testStore["Test Tab 3"].Count);
Assert.Equal(testTab1Object1, testStore[firstTabName]["Test Key 1"]);
Assert.Equal(testTab1Object2, testStore[firstTabName]["Test Key 2"]);
Assert.Equal(testTab2Object1, testStore["Test Tab 2"]["Test Key 1"]);
Assert.Equal(testTab3Object1, testStore["Test Tab 3"]["Test Key 1"]);
Assert.Equal(testTab3Object2, testStore["Test Tab 3"]["Test Key 2"]);
Assert.Equal(testTab3Object3, testStore["Test Tab 3"]["Test Key 3"]);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void AddToTab_AddingEntryWithSameKeyOverwritesPreviousEntry(bool useDefaultTab)
{
// Arrange
var testMetadata = new Metadata();
var testTabObject1 = 999999;
var testTabObject2 = "AAAAAAAA";
var testTabObject3 = new Object[] { testTabObject2 };
var tabName = useDefaultTab ? Metadata.DefaultTabName : "Test Tab";
// Act
if (useDefaultTab)
{
testMetadata.AddToTab("Test Key 1", testTabObject1);
testMetadata.AddToTab("Test Key 1", testTabObject2);
testMetadata.AddToTab("Test Key 1", testTabObject3);
}
else
{
testMetadata.AddToTab("Test Tab", "Test Key 1", testTabObject1);
testMetadata.AddToTab("Test Tab", "Test Key 1", testTabObject2);
testMetadata.AddToTab("Test Tab", "Test Key 1", testTabObject3);
}
// Assert
var testStore = testMetadata.MetadataStore;
Assert.Equal(1, testStore.Count);
Assert.Equal(1, testStore[tabName].Count);
Assert.Equal(testTabObject3, testStore[tabName]["Test Key 1"]);
}
[Theory]
[InlineData("Tab 4")]
[InlineData("Tab 5")]
[InlineData("Random Tab")]
[InlineData("")]
[InlineData(null)]
public void RemoveTab_RemoveTabWhenTabDoesntExistDoesNothing(string tabToRemove)
{
// Arrange
var testBlankMetadata = new Metadata();
var testFullMetadata = new Metadata();
testFullMetadata.MetadataStore.Add("Tab 1", new Dictionary<string, object>() { { "T1", "V1" } });
testFullMetadata.MetadataStore.Add("Tab 2", new Dictionary<string, object>() { { "T2", "V2" } });
testFullMetadata.MetadataStore.Add("Tab 3", new Dictionary<string, object>() { { "T3", "V3" } });
// Act
testBlankMetadata.RemoveTab(tabToRemove);
testFullMetadata.RemoveTab(tabToRemove);
// Assert
Assert.Equal(0, testBlankMetadata.MetadataStore.Count);
Assert.Equal(3, testFullMetadata.MetadataStore.Count);
Assert.Equal(1, testFullMetadata.MetadataStore["Tab 1"].Count);
Assert.Equal(1, testFullMetadata.MetadataStore["Tab 2"].Count);
Assert.Equal(1, testFullMetadata.MetadataStore["Tab 3"].Count);
Assert.Equal("V1", testFullMetadata.MetadataStore["Tab 1"]["T1"]);
Assert.Equal("V2", testFullMetadata.MetadataStore["Tab 2"]["T2"]);
Assert.Equal("V3", testFullMetadata.MetadataStore["Tab 3"]["T3"]);
}
[Fact]
public void RemoveTab_RemoveTabSuccessfullyFromMetadata()
{
// Arrange
var testMetadata = new Metadata();
var obj1_1 = new Object();
var obj2_1 = new Object();
var obj2_2 = new Object();
var obj3_1 = new Object();
var obj3_2 = new Object();
var obj3_3 = new Object();
testMetadata.MetadataStore.Add("Tab 1", new Dictionary<string, object>() { { "T1_1", obj1_1 } });
testMetadata.MetadataStore.Add("Tab 2", new Dictionary<string, object>() { { "T2_1", obj2_1 }, { "T2_2", obj2_2 } });
testMetadata.MetadataStore.Add("Tab 3", new Dictionary<string, object>() { { "T3_1", obj3_1 }, { "T3_2", obj3_2 }, { "T3_3", obj3_3 } });
// Act
testMetadata.RemoveTab("Tab 1");
// Assert
Assert.Equal(2, testMetadata.MetadataStore.Count);
Assert.Equal(2, testMetadata.MetadataStore["Tab 2"].Count);
Assert.Equal(3, testMetadata.MetadataStore["Tab 3"].Count);
Assert.Equal(obj2_1, testMetadata.MetadataStore["Tab 2"]["T2_1"]);
Assert.Equal(obj2_2, testMetadata.MetadataStore["Tab 2"]["T2_2"]);
Assert.Equal(obj3_1, testMetadata.MetadataStore["Tab 3"]["T3_1"]);
Assert.Equal(obj3_2, testMetadata.MetadataStore["Tab 3"]["T3_2"]);
Assert.Equal(obj3_3, testMetadata.MetadataStore["Tab 3"]["T3_3"]);
// Act
testMetadata.RemoveTab("Tab 2");
// Assert
Assert.Equal(1, testMetadata.MetadataStore.Count);
Assert.Equal(3, testMetadata.MetadataStore["Tab 3"].Count);
Assert.Equal(obj3_1, testMetadata.MetadataStore["Tab 3"]["T3_1"]);
Assert.Equal(obj3_2, testMetadata.MetadataStore["Tab 3"]["T3_2"]);
Assert.Equal(obj3_3, testMetadata.MetadataStore["Tab 3"]["T3_3"]);
// Act
testMetadata.RemoveTab("Tab 3");
// Assert
Assert.Equal(0, testMetadata.MetadataStore.Count);
}
[Theory]
[InlineData("Tab 4", "Entry 1")]
[InlineData("Tab 5", "T1")]
[InlineData("Random Tab", null)]
[InlineData("", "")]
[InlineData(null, null)]
[InlineData("Tab 1", "Random")]
[InlineData("Tab 2", "T3")]
[InlineData("Tab 3", null)]
[InlineData("Tab 2", "")]
public void RemoveTabEntry_RemoveTabEntryWhenTabOrEntryDoesntExistDoesNothing(string tab, string entryToRemove)
{
// Arrange
var testBlankMetadata = new Metadata();
var testFullMetadata = new Metadata();
testFullMetadata.MetadataStore.Add("Tab 1", new Dictionary<string, object>() { { "T1", "V1" } });
testFullMetadata.MetadataStore.Add("Tab 2", new Dictionary<string, object>() { { "T2", "V2" } });
testFullMetadata.MetadataStore.Add("Tab 3", new Dictionary<string, object>() { { "T3", "V3" } });
// Act
testBlankMetadata.RemoveTabEntry(tab, entryToRemove);
testFullMetadata.RemoveTabEntry(tab, entryToRemove);
// Assert
Assert.Equal(0, testBlankMetadata.MetadataStore.Count);
Assert.Equal(3, testFullMetadata.MetadataStore.Count);
Assert.Equal(1, testFullMetadata.MetadataStore["Tab 1"].Count);
Assert.Equal(1, testFullMetadata.MetadataStore["Tab 2"].Count);
Assert.Equal(1, testFullMetadata.MetadataStore["Tab 3"].Count);
Assert.Equal("V1", testFullMetadata.MetadataStore["Tab 1"]["T1"]);
Assert.Equal("V2", testFullMetadata.MetadataStore["Tab 2"]["T2"]);
Assert.Equal("V3", testFullMetadata.MetadataStore["Tab 3"]["T3"]);
}
[Fact]
public void RemoveTabEntry_RemoveTabEntrySuccessfullyFromMetadata()
{
// Arrange
var testMetadata = new Metadata();
var obj1_1 = new Object();
var obj2_1 = new Object();
var obj2_2 = new Object();
var obj3_1 = new Object();
var obj3_2 = new Object();
var obj3_3 = new Object();
testMetadata.MetadataStore.Add("Tab 1", new Dictionary<string, object>() { { "T1_1", obj1_1 } });
testMetadata.MetadataStore.Add("Tab 2", new Dictionary<string, object>() { { "T2_1", obj2_1 }, { "T2_2", obj2_2 } });
testMetadata.MetadataStore.Add("Tab 3", new Dictionary<string, object>() { { "T3_1", obj3_1 }, { "T3_2", obj3_2 }, { "T3_3", obj3_3 } });
// Act
testMetadata.RemoveTabEntry("Tab 2", "T2_1");
testMetadata.RemoveTabEntry("Tab 3", "T3_2");
// Assert
Assert.Equal(3, testMetadata.MetadataStore.Count);
Assert.Equal(1, testMetadata.MetadataStore["Tab 1"].Count);
Assert.Equal(1, testMetadata.MetadataStore["Tab 2"].Count);
Assert.Equal(2, testMetadata.MetadataStore["Tab 3"].Count);
Assert.Equal(obj1_1, testMetadata.MetadataStore["Tab 1"]["T1_1"]);
Assert.Equal(obj2_2, testMetadata.MetadataStore["Tab 2"]["T2_2"]);
Assert.Equal(obj3_1, testMetadata.MetadataStore["Tab 3"]["T3_1"]);
Assert.Equal(obj3_3, testMetadata.MetadataStore["Tab 3"]["T3_3"]);
}
[Fact]
public void RemoveTabEntry_RemovingLastEntryWillRemoveTab()
{
// Arrange
var testMetadata = new Metadata();
var obj1 = new Object();
var obj2 = new Object();
testMetadata.MetadataStore.Add("Tab 1", new Dictionary<string, object>() { { "T1", obj1 }, { "T2", obj2 } });
// Act
testMetadata.RemoveTabEntry("Tab 1", "T2");
// Assert
Assert.Equal(1, testMetadata.MetadataStore.Count);
Assert.Equal(1, testMetadata.MetadataStore["Tab 1"].Count);
Assert.Equal(obj1, testMetadata.MetadataStore["Tab 1"]["T1"]);
// Act
testMetadata.RemoveTabEntry("Tab 1", "T1");
// Assert
Assert.Equal(0, testMetadata.MetadataStore.Count);
}
[Fact]
public void FilterEntries_NullPredicateDoesNothingToMetadata()
{
// Arrange
var testMetadata = new Metadata();
var obj1 = new Object();
var obj2 = new Object();
testMetadata.MetadataStore.Add("Tab 1", new Dictionary<string, object>() { { "T1", obj1 }, { "T2", obj2 } });
// Act
testMetadata.FilterEntries(null);
// Assert
Assert.Equal(1, testMetadata.MetadataStore.Count);
Assert.Equal(2, testMetadata.MetadataStore["Tab 1"].Count);
Assert.Equal(obj1, testMetadata.MetadataStore["Tab 1"]["T1"]);
Assert.Equal(obj2, testMetadata.MetadataStore["Tab 1"]["T2"]);
}
[Fact]
public void FilterEntries_FiltersAllEntriesThatEndWithASpecificValue()
{
// Arrange
var testMetadata = new Metadata();
var obj1_1 = new Object();
var obj2_1 = new Object();
var obj2_2 = new Object();
var obj3_1 = new Object();
var obj3_2 = new Object();
var obj3_3 = new Object();
testMetadata.MetadataStore.Add("Tab 1", new Dictionary<string, object>() { { "T1_1", obj1_1 } });
testMetadata.MetadataStore.Add("Tab 2", new Dictionary<string, object>() { { "T2_1", obj2_1 }, { "T2_2", obj2_2 } });
testMetadata.MetadataStore.Add("Tab 3", new Dictionary<string, object>() { { "T3_1", obj3_1 }, { "T3_2", obj3_2 }, { "T3_3", obj3_3 } });
Func<string, bool> filter = (key) => key.EndsWith("2");
// Act
testMetadata.FilterEntries(filter);
// Assert
Assert.Equal(3, testMetadata.MetadataStore.Count);
Assert.Equal(1, testMetadata.MetadataStore["Tab 1"].Count);
Assert.Equal(2, testMetadata.MetadataStore["Tab 2"].Count);
Assert.Equal(3, testMetadata.MetadataStore["Tab 3"].Count);
Assert.Equal(obj1_1, testMetadata.MetadataStore["Tab 1"]["T1_1"]);
Assert.Equal(obj2_1, testMetadata.MetadataStore["Tab 2"]["T2_1"]);
Assert.Equal("[FILTERED]", testMetadata.MetadataStore["Tab 2"]["T2_2"]);
Assert.Equal(obj3_1, testMetadata.MetadataStore["Tab 3"]["T3_1"]);
Assert.Equal("[FILTERED]", testMetadata.MetadataStore["Tab 3"]["T3_2"]);
Assert.Equal(obj3_3, testMetadata.MetadataStore["Tab 3"]["T3_3"]);
}
[Fact]
public void FilterEntries_RecordExceptionInEntryIfPredicateThrowsException()
{
// Arrange
var testMetadata = new Metadata();
var obj1 = new Object();
var obj2 = new Object();
var obj3 = new Object();
testMetadata.MetadataStore.Add("Tab 1", new Dictionary<string, object>() { { "T1", obj1 }, { "T2", obj2 }, { "T3", obj3 } });
Func<string, bool> filter = (key) =>
{
if (key == "T1")
return false;
if (key == "T2")
throw new SystemException("System Test Error");
return true;
};
// Act
testMetadata.FilterEntries(filter);
// Assert
Assert.Equal(1, testMetadata.MetadataStore.Count);
Assert.Equal(3, testMetadata.MetadataStore["Tab 1"].Count);
Assert.Equal(obj1, testMetadata.MetadataStore["Tab 1"]["T1"]);
Assert.Equal("[FILTERED]", testMetadata.MetadataStore["Tab 1"]["T3"]);
var expEntry = testMetadata.MetadataStore["Tab 1"]["T2"] as string;
Assert.True(expEntry.StartsWith("[FILTER ERROR]"));
Assert.True(expEntry.Contains("System Test Error"));
}
[Fact]
public void CombineMetaData_CombiningNullAndEmptyMetadatasAlwaysReturnsAnEmptyMetadata()
{
// Act
var actData1 = Metadata.CombineMetadata();
var actData2 = Metadata.CombineMetadata(null);
var actData3 = Metadata.CombineMetadata(new Metadata());
var actData4 = Metadata.CombineMetadata(new Metadata(), null);
var actData5 = Metadata.CombineMetadata(null, new Metadata());
var actData6 = Metadata.CombineMetadata(null, null, null);
var actData7 = Metadata.CombineMetadata(new Metadata(), new Metadata(), new Metadata());
// Assert
Assert.Equal(0, actData1.MetadataStore.Count);
Assert.Equal(0, actData2.MetadataStore.Count);
Assert.Equal(0, actData3.MetadataStore.Count);
Assert.Equal(0, actData4.MetadataStore.Count);
Assert.Equal(0, actData5.MetadataStore.Count);
Assert.Equal(0, actData6.MetadataStore.Count);
Assert.Equal(0, actData7.MetadataStore.Count);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void CombineMetaData_CombineTwoMetadataObjectsSuccessfully(bool combine1with2)
{
// Arrange
var testMd1 = new Metadata();
var md1_obj1_1 = new Object();
var md1_obj1_2 = new Object();
var md1_shared_1 = new Object();
var md1_shared_2 = new Object();
testMd1.MetadataStore.Add("Tab 1", new Dictionary<string, object>() { { "DATA1_T1_1", md1_obj1_1 }, { "DATA1_T1_2", md1_obj1_2 } });
testMd1.MetadataStore.Add("Shared", new Dictionary<string, object>() { { "S_1", md1_shared_1 }, { "S_2", md1_shared_2 } });
var testMd2 = new Metadata();
var md2_obj2_1 = new Object();
var md2_obj2_2 = new Object();
var md2_shared_2 = new Object();
var md2_shared_3 = new Object();
testMd2.MetadataStore.Add("Tab 2", new Dictionary<string, object>() { { "DATA2_T2_1", md2_obj2_1 }, { "DATA2_T2_2", md2_obj2_2 } });
testMd2.MetadataStore.Add("Shared", new Dictionary<string, object>() { { "S_2", md2_shared_2 }, { "S_3", md2_shared_3 } });
// Act
Metadata actData;
if (combine1with2)
actData = Metadata.CombineMetadata(testMd1, testMd2);
else
actData = Metadata.CombineMetadata(testMd2, testMd1);
// Assert
Assert.Equal(3, actData.MetadataStore.Count);
Assert.Equal(2, actData.MetadataStore["Tab 1"].Count);
Assert.Equal(2, actData.MetadataStore["Tab 2"].Count);
Assert.Equal(3, actData.MetadataStore["Shared"].Count);
Assert.Equal(md1_obj1_1, actData.MetadataStore["Tab 1"]["DATA1_T1_1"]);
Assert.Equal(md1_obj1_2, actData.MetadataStore["Tab 1"]["DATA1_T1_2"]);
Assert.Equal(md2_obj2_1, actData.MetadataStore["Tab 2"]["DATA2_T2_1"]);
Assert.Equal(md2_obj2_2, actData.MetadataStore["Tab 2"]["DATA2_T2_2"]);
var expShared2 = combine1with2 ? md2_shared_2 : md1_shared_2;
Assert.Equal(md1_shared_1, actData.MetadataStore["Shared"]["S_1"]);
Assert.Equal(expShared2, actData.MetadataStore["Shared"]["S_2"]);
Assert.Equal(md2_shared_3, actData.MetadataStore["Shared"]["S_3"]);
}
}
}
| |
// Copyright 2011, 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)
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Net;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.Xml;
namespace Google.Api.Ads.Common.Lib {
/// <summary>
/// This class reads the configuration keys from App.config.
/// </summary>
public abstract class AppConfigBase : INotifyPropertyChanged, AppConfig {
/// <summary>
/// The short name to identify this assembly.
/// </summary>
private const string SHORT_NAME = "Common-Dotnet";
/// <summary>
/// Key name for proxyServer
/// </summary>
private const string PROXY_SERVER = "ProxyServer";
/// <summary>
/// Key name for proxyUser.
/// </summary>
private const string PROXY_USER = "ProxyUser";
/// <summary>
/// Key name for proxyPassword.
/// </summary>
private const string PROXY_PASSWORD = "ProxyPassword";
/// <summary>
/// Key name for proxyDomain.
/// </summary>
private const string PROXY_DOMAIN = "ProxyDomain";
/// <summary>
/// Key name for maskCredentials.
/// </summary>
private const string MASK_CREDENTIALS = "MaskCredentials";
/// <summary>
/// Key name for timeout.
/// </summary>
private const string TIMEOUT = "Timeout";
/// <summary>
/// Key name for retryCount.
/// </summary>
private const string RETRYCOUNT = "RetryCount";
/// <summary>
/// Key name for enableGzipCompression.
/// </summary>
private const string ENABLE_GZIP_COMPRESSION = "EnableGzipCompression";
/// <summary>
/// Key name for OAuth2 mode.
/// </summary>
private const string OAUTH2_MODE = "OAuth2Mode";
/// <summary>
/// Key name for OAuth2 client id.
/// </summary>
private const string OAUTH2_CLIENTID = "OAuth2ClientId";
/// <summary>
/// Key name for OAuth2 client secret.
/// </summary>
private const string OAUTH2_CLIENTSECRET = "OAuth2ClientSecret";
/// <summary>
/// Key name for OAuth2 access token.
/// </summary>
private const string OAUTH2_ACCESSTOKEN = "OAuth2AccessToken";
/// <summary>
/// Key name for OAuth2 refresh token.
/// </summary>
private const string OAUTH2_REFRESHTOKEN = "OAuth2RefreshToken";
/// <summary>
/// Key name for OAuth2 scope.
/// </summary>
private const string OAUTH2_SCOPE = "OAuth2Scope";
/// <summary>
/// Key name for redirect uri.
/// </summary>
private const string OAUTH2_REDIRECTURI = "OAuth2RedirectUri";
/// <summary>
/// Key name for service account email.
/// </summary>
private const string OAUTH2_SERVICEACCOUNT_EMAIL = "OAuth2ServiceAccountEmail";
/// <summary>
/// Key name for prn account email.
/// </summary>
private const string OAUTH2_PRN_EMAIL = "OAuth2PrnEmail";
/// <summary>
/// Key name for jwt certificate path.
/// </summary>
private const string OAUTH2_JWT_CERTIFICATE_PATH = "OAuth2JwtCertificatePath";
/// <summary>
/// Key name for jwt certificate password.
/// </summary>
private const string OAUTH2_JWT_CERTIFICATE_PASSWORD = "OAuth2JwtCertificatePassword";
/// <summary>
/// Key name for authToken.
/// </summary>
private const string AUTHTOKEN = "AuthToken";
/// <summary>
/// Key name for email.
/// </summary>
private const string EMAIL = "Email";
/// <summary>
/// Key name for password.
/// </summary>
private const string PASSWORD = "Password";
/// <summary>
/// Web proxy to be used with the services.
/// </summary>
private IWebProxy proxy;
/// <summary>
/// True, if the credentials in the log file should be masked.
/// </summary>
private bool maskCredentials;
/// <summary>
/// Timeout to be used for Ads services in milliseconds.
/// </summary>
private int timeout;
/// <summary>
/// Number of times to retry a call if an API call fails and can be retried.
/// </summary>
private int retryCount;
/// <summary>
/// True, if gzip compression should be turned on for SOAP requests and
/// responses.
/// </summary>
private bool enableGzipCompression;
/// <summary>
/// OAuth2 client id.
/// </summary>
private string oAuth2ClientId;
/// <summary>
/// OAuth2 client secret.
/// </summary>
private string oAuth2ClientSecret;
/// <summary>
/// OAuth2 access token.
/// </summary>
private string oAuth2AccessToken;
/// <summary>
/// OAuth2 refresh token.
/// </summary>
private string oAuth2RefreshToken;
/// <summary>
/// OAuth2 service account email.
/// </summary>
private string oAuth2ServiceAccountEmail;
/// <summary>
/// OAuth2 prn email.
/// </summary>
private string oAuth2PrnEmail;
/// <summary>
/// OAuth2 certificate path.
/// </summary>
private string oAuth2CertificatePath;
/// <summary>
/// OAuth2 certificate password.
/// </summary>
private string oAuth2CertificatePassword;
/// <summary>
/// OAuth2 scope.
/// </summary>
private string oAuth2Scope;
/// <summary>
/// Redirect uri.
/// </summary>
private string oAuth2RedirectUri;
/// <summary>
/// OAuth2 mode.
/// </summary>
private OAuth2Flow oAuth2Mode;
/// <summary>
/// Authtoken to be used in making API calls.
/// </summary>
private string authToken;
/// <summary>
/// Email to be used in getting AuthToken.
/// </summary>
private string email;
/// <summary>
/// Password to be used in getting AuthToken.
/// </summary>
private string password;
/// <summary>
/// Default value for number of times to retry a call if an API call fails
/// and can be retried.
/// </summary>
private const int DEFAULT_RETRYCOUNT = 0;
/// <summary>
/// Default value for timeout for Ads services.
/// </summary>
private const int DEFAULT_TIMEOUT = -1;
/// <summary>
/// Gets whether the credentials in the log file should be masked.
/// </summary>
public bool MaskCredentials {
get {
return maskCredentials;
}
protected set {
maskCredentials = value;
}
}
/// <summary>
/// Gets the web proxy to be used with the services.
/// </summary>
public IWebProxy Proxy {
get {
return proxy;
}
set {
SetPropertyField("Proxy", ref proxy, value);
}
}
/// <summary>
/// Gets or sets the timeout for Ads services in milliseconds.
/// </summary>
public int Timeout {
get {
return timeout;
}
set {
SetPropertyField("Timeout", ref timeout, value);
}
}
/// <summary>
/// Gets or sets the number of times to retry a call if an API call fails
/// and can be retried.
/// </summary>
public int RetryCount {
get {
return retryCount;
}
set {
SetPropertyField("RetryCount", ref retryCount, value);
}
}
/// <summary>
/// Gets or sets whether gzip compression should be turned on for SOAP
/// requests and responses.
/// </summary>
public bool EnableGzipCompression {
get {
return enableGzipCompression;
}
set {
SetPropertyField("EnableGzipCompression", ref enableGzipCompression, value);
}
}
/// <summary>
/// Gets or sets the OAuth2 client id.
/// </summary>
public string OAuth2ClientId {
get {
return oAuth2ClientId;
}
set {
SetPropertyField("OAuth2ClientId", ref oAuth2ClientId, value);
}
}
/// <summary>
/// Gets or sets the OAuth2 client secret.
/// </summary>
public string OAuth2ClientSecret {
get {
return oAuth2ClientSecret;
}
set {
SetPropertyField("OAuth2ClientSecret", ref oAuth2ClientSecret, value);
}
}
/// <summary>
/// Gets or sets the OAuth2 access token.
/// </summary>
public string OAuth2AccessToken {
get {
return oAuth2AccessToken;
}
set {
SetPropertyField("OAuth2AccessToken", ref oAuth2AccessToken, value);
}
}
/// <summary>
/// Gets or sets the OAuth2 refresh token.
/// </summary>
/// <remarks>This key is applicable only when using OAuth2 web / application
/// flow in offline mode.</remarks>
public string OAuth2RefreshToken {
get {
return oAuth2RefreshToken;
}
set {
SetPropertyField("OAuth2RefreshToken", ref oAuth2RefreshToken, value);
}
}
/// <summary>
/// Gets or sets the OAuth2 scope.
/// </summary>
public string OAuth2Scope {
get {
return oAuth2Scope;
}
set {
SetPropertyField("OAuth2Scope", ref oAuth2Scope, value);
}
}
/// <summary>
/// Gets or sets the OAuth2 redirect URI.
/// </summary>
/// <remarks>This key is applicable only when using OAuth2 web flow.
/// </remarks>
public string OAuth2RedirectUri {
get {
return oAuth2RedirectUri;
}
set {
SetPropertyField("OAuth2RedirectUri", ref oAuth2RedirectUri, value);
}
}
/// <summary>
/// Gets or sets the OAuth2 mode.
/// </summary>
public OAuth2Flow OAuth2Mode {
get {
return oAuth2Mode;
}
set {
SetPropertyField("OAuth2Mode", ref oAuth2Mode, value);
}
}
/// <summary>
/// Gets or sets the OAuth2 service account email.
/// </summary>
/// <remarks>This key is applicable only when using OAuth2 service accounts.
/// </remarks>
public string OAuth2ServiceAccountEmail {
get {
return oAuth2ServiceAccountEmail;
}
set {
SetPropertyField("OAuth2ServiceAccountEmail", ref oAuth2ServiceAccountEmail, value);
}
}
/// <summary>
/// Gets or sets the OAuth2 prn email.
/// </summary>
/// <remarks>This key is applicable only when using OAuth2 service accounts.
/// </remarks>
public string OAuth2PrnEmail {
get {
return oAuth2PrnEmail;
}
set {
SetPropertyField("OAuth2PrnEmail", ref oAuth2PrnEmail, value);
}
}
/// <summary>
/// Gets or sets the OAuth2 certificate path.
/// </summary>
/// <remarks>This key is applicable only when using OAuth2 service accounts.
/// </remarks>
public string OAuth2CertificatePath {
get {
return oAuth2CertificatePath;
}
set {
SetPropertyField("OAuth2CertificatePath", ref oAuth2CertificatePath, value);
}
}
/// <summary>
/// Gets or sets the OAuth2 certificate password.
/// </summary>
/// <remarks>This key is applicable only when using OAuth2 service accounts.
/// </remarks>
public string OAuth2CertificatePassword {
get {
return oAuth2CertificatePassword;
}
set {
SetPropertyField("OAuth2CertificatePassword", ref oAuth2CertificatePassword, value);
}
}
/// <summary>
/// Gets or sets the email to be used in getting AuthToken.
/// </summary>
public string Email {
get {
return email;
}
set {
SetPropertyField("Email", ref email, value);
}
}
/// <summary>
/// Gets or sets the password to be used in getting AuthToken.
/// </summary>
public string Password {
get {
return password;
}
set {
SetPropertyField("Password", ref password, value);
}
}
/// <summary>
/// Gets or sets the auth token to be used in SOAP headers.
/// </summary>
public string AuthToken {
get {
return authToken;
}
set {
SetPropertyField("AuthToken", ref authToken, value);
}
}
/// <summary>
/// Gets the default OAuth2 scope.
/// </summary>
public virtual string GetDefaultOAuth2Scope() {
return "";
}
/// <summary>
/// Gets the signature for this assembly, given a type derived from
/// AppConfigBase.
/// </summary>
/// <param name="type">Type of the class derived from AppConfigBase.</param>
/// <returns>The assembly signature.</returns>
/// <exception cref="ArgumentException">Thrown if type is not derived from
/// AppConfigBase.</exception>
private string GetAssemblySignatureFromAppConfigType(Type type) {
Type appConfigBaseType = typeof(AppConfigBase);
if (!(type.BaseType == appConfigBaseType || type == appConfigBaseType)) {
throw new ArgumentException(string.Format("{0} is not derived from {1}.",
type.FullName, appConfigBaseType.FullName));
}
Version version = type.Assembly.GetName().Version;
string shortName = (string) type.GetField("SHORT_NAME", BindingFlags.NonPublic |
BindingFlags.Static).GetValue(null);
return string.Format("{0}/{1}.{2}.{3}", shortName, version.Major, version.Minor,
version.Revision);
}
/// <summary>
/// Gets the signature for this library.
/// </summary>
public string Signature {
get {
return string.Format("{0}, {1}, .NET CLR/{2}",
GetAssemblySignatureFromAppConfigType(this.GetType()),
GetAssemblySignatureFromAppConfigType(this.GetType().BaseType), Environment.Version);
}
}
/// <summary>
/// Gets the number of seconds after Jan 1, 1970, 00:00:00
/// </summary>
public virtual long UnixTimestamp {
get {
TimeSpan unixTime = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0));
return (long) unixTime.TotalSeconds;
}
}
/// <summary>
/// Default constructor for the object.
/// </summary>
protected AppConfigBase() {
proxy = null;
maskCredentials = true;
timeout = DEFAULT_TIMEOUT;
enableGzipCompression = true;
oAuth2Mode = OAuth2Flow.APPLICATION;
oAuth2ClientId = "";
oAuth2ClientSecret = "";
oAuth2AccessToken = "";
oAuth2RefreshToken = "";
oAuth2Scope = "";
oAuth2RedirectUri = null;
oAuth2PrnEmail = "";
oAuth2ServiceAccountEmail = "";
authToken = "";
email = "";
password = "";
}
/// <summary>
/// Read all settings from App.config.
/// </summary>
/// <param name="settings">The parsed app.config settings.</param>
protected virtual void ReadSettings(Hashtable settings) {
// Common keys.
string proxyUrl = ReadSetting(settings, PROXY_SERVER, "");
if (!string.IsNullOrEmpty(proxyUrl)) {
WebProxy proxy = new WebProxy();
proxy.Address = new Uri(proxyUrl);
string proxyUser = ReadSetting(settings, PROXY_USER, "");
string proxyPassword = ReadSetting(settings, PROXY_PASSWORD, "");
string proxyDomain = ReadSetting(settings, PROXY_DOMAIN, "");
if (!string.IsNullOrEmpty(proxyUrl)) {
proxy.Credentials = new NetworkCredential(proxyUser,
proxyPassword, proxyDomain);
}
this.proxy = proxy;
} else {
// System.Net.WebRequest will find a proxy if needed.
this.proxy = null;
}
maskCredentials = bool.Parse(ReadSetting(settings, MASK_CREDENTIALS,
maskCredentials.ToString()));
try {
oAuth2Mode = (OAuth2Flow) Enum.Parse(typeof(OAuth2Flow), ReadSetting(settings, OAUTH2_MODE,
oAuth2Mode.ToString()));
} catch (Exception e) {
// No action.
}
oAuth2ClientId = ReadSetting(settings, OAUTH2_CLIENTID, oAuth2ClientId);
oAuth2ClientSecret = ReadSetting(settings, OAUTH2_CLIENTSECRET, oAuth2ClientSecret);
oAuth2AccessToken = ReadSetting(settings, OAUTH2_ACCESSTOKEN, oAuth2AccessToken);
oAuth2RefreshToken = ReadSetting(settings, OAUTH2_REFRESHTOKEN, oAuth2RefreshToken);
oAuth2Scope = ReadSetting(settings, OAUTH2_SCOPE, oAuth2Scope);
oAuth2RedirectUri = ReadSetting(settings, OAUTH2_REDIRECTURI, oAuth2RedirectUri);
oAuth2ServiceAccountEmail = ReadSetting(settings, OAUTH2_SERVICEACCOUNT_EMAIL,
oAuth2ServiceAccountEmail);
oAuth2PrnEmail = ReadSetting(settings, OAUTH2_PRN_EMAIL, oAuth2PrnEmail);
oAuth2CertificatePath = ReadSetting(settings, OAUTH2_JWT_CERTIFICATE_PATH,
oAuth2CertificatePath);
oAuth2CertificatePassword = ReadSetting(settings, OAUTH2_JWT_CERTIFICATE_PASSWORD,
oAuth2CertificatePassword);
email = ReadSetting(settings, EMAIL, email);
password = ReadSetting(settings, PASSWORD, password);
authToken = ReadSetting(settings, AUTHTOKEN, authToken);
int.TryParse(ReadSetting(settings, TIMEOUT, timeout.ToString()), out timeout);
int.TryParse(ReadSetting(settings, RETRYCOUNT, retryCount.ToString()), out retryCount);
bool.TryParse(ReadSetting(settings, ENABLE_GZIP_COMPRESSION,
enableGzipCompression.ToString()), out enableGzipCompression);
}
/// <summary>
/// Reads a setting from a given NameValueCollection, and sets
/// default value if the key is not available in the collection.
/// </summary>
/// <param name="settings">The settings collection from which the keys
/// are to be read.</param>
/// <param name="key">Key name to be read.</param>
/// <param name="defaultValue">Default value for the key.</param>
/// <returns>Actual value from settings, or defaultValue if settings
/// does not have this key.</returns>
protected static string ReadSetting(Hashtable settings, string key, string defaultValue) {
if (settings == null) {
return defaultValue;
} else {
return settings.ContainsKey(key) ? (string) settings[key] : defaultValue;
}
}
/// <summary>
/// Raises the <see cref="E:PropertyChanged"/> event.
/// </summary>
/// <param name="e">The <see cref="System.ComponentModel.PropertyChangedEventArgs"/>
/// instance containing the event data.</param>
protected void OnPropertyChanged(PropertyChangedEventArgs e) {
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) {
handler(this, e);
}
}
/// <summary>
/// Sets the specified property field.
/// </summary>
/// <typeparam name="T">Type of the property field to be set.</typeparam>
/// <param name="propertyName">Name of the property.</param>
/// <param name="field">The property field to be set.</param>
/// <param name="newValue">The new value to be set to the propery.</param>
protected void SetPropertyField<T>(string propertyName, ref T field, T newValue) {
if (!EqualityComparer<T>.Default.Equals(field, newValue)) {
field = newValue;
OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
}
}
/// <summary>
/// Occurs when a property value changes.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
// This file contains the IDN functions and implementation.
//
// This allows encoding of non-ASCII domain names in a "punycode" form,
// for example:
//
// \u5B89\u5BA4\u5948\u7F8E\u6075-with-SUPER-MONKEYS
//
// is encoded as:
//
// xn---with-SUPER-MONKEYS-pc58ag80a8qai00g7n9n
//
// Additional options are provided to allow unassigned IDN characters and
// to validate according to the Std3ASCII Rules (like DNS names).
//
// There are also rules regarding bidirectionality of text and the length
// of segments.
//
// For additional rules see also:
// RFC 3490 - Internationalizing Domain Names in Applications (IDNA)
// RFC 3491 - Nameprep: A Stringprep Profile for Internationalized Domain Names (IDN)
// RFC 3492 - Punycode: A Bootstring encoding of Unicode for Internationalized Domain Names in Applications (IDNA)
//
/*
The punycode implementation is based on the sample code in RFC 3492
Copyright (C) The Internet Society (2003). All Rights Reserved.
This document and translations of it may be copied and furnished to
others, and derivative works that comment on or otherwise explain it
or assist in its implementation may be prepared, copied, published
and distributed, in whole or in part, without restriction of any
kind, provided that the above copyright notice and this paragraph are
included on all such copies and derivative works. However, this
document itself may not be modified in any way, such as by removing
the copyright notice or references to the Internet Society or other
Internet organizations, except as needed for the purpose of
developing Internet standards in which case the procedures for
copyrights defined in the Internet Standards process must be
followed, or as required to translate it into languages other than
English.
The limited permissions granted above are perpetual and will not be
revoked by the Internet Society or its successors or assigns.
This document and the information contained herein is provided on an
"AS IS" basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING
TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING
BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION
HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
*/
namespace System.Globalization
{
using System;
using System.Security;
using System.Globalization;
using System.Text;
using System.Runtime.Versioning;
using System.Runtime.InteropServices;
using System.Diagnostics.Contracts;
// IdnMapping class used to map names to Punycode
public sealed class IdnMapping
{
// Legal name lengths for domain names
const int M_labelLimit = 63; // Not including dots
const int M_defaultNameLimit = 255; // Including dots
// IDNA prefix
const String M_strAcePrefix = "xn--";
// Legal "dot" seperators (i.e: . in www.microsoft.com)
static char[] M_Dots =
{
'.', '\u3002', '\uFF0E', '\uFF61'
};
bool m_bAllowUnassigned;
bool m_bUseStd3AsciiRules;
public IdnMapping()
{
}
public bool AllowUnassigned
{
get
{
return this.m_bAllowUnassigned;
}
set
{
this.m_bAllowUnassigned = value;
}
}
public bool UseStd3AsciiRules
{
get
{
return this.m_bUseStd3AsciiRules;
}
set
{
this.m_bUseStd3AsciiRules = value;
}
}
// Gets ASCII (Punycode) version of the string
public String GetAscii(String unicode)
{
return GetAscii(unicode, 0);
}
public String GetAscii(String unicode, int index)
{
if (unicode==null) throw new ArgumentNullException(nameof(unicode));
Contract.EndContractBlock();
return GetAscii(unicode, index, unicode.Length - index);
}
public String GetAscii(String unicode, int index, int count)
{
throw null;
}
[System.Security.SecuritySafeCritical]
private String GetAsciiUsingOS(String unicode)
{
if (unicode.Length == 0)
{
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadLabelSize"), nameof(unicode));
}
if (unicode[unicode.Length - 1] == 0)
{
throw new ArgumentException(
Environment.GetResourceString("Argument_InvalidCharSequence", unicode.Length - 1),
nameof(unicode));
}
uint flags = (uint) ((AllowUnassigned ? IDN_ALLOW_UNASSIGNED : 0) | (UseStd3AsciiRules ? IDN_USE_STD3_ASCII_RULES : 0));
int length = IdnToAscii(flags, unicode, unicode.Length, null, 0);
int lastError;
if (length == 0)
{
lastError = Marshal.GetLastWin32Error();
if (lastError == ERROR_INVALID_NAME)
{
throw new ArgumentException(Environment.GetResourceString("Argument_IdnIllegalName"), nameof(unicode));
}
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex"), nameof(unicode));
}
char [] output = new char[length];
length = IdnToAscii(flags, unicode, unicode.Length, output, length);
if (length == 0)
{
lastError = Marshal.GetLastWin32Error();
if (lastError == ERROR_INVALID_NAME)
{
throw new ArgumentException(Environment.GetResourceString("Argument_IdnIllegalName"), nameof(unicode));
}
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex"), nameof(unicode));
}
return new String(output, 0, length);
}
// Gets Unicode version of the string. Normalized and limited to IDNA characters.
public String GetUnicode(String ascii)
{
return GetUnicode(ascii, 0);
}
public String GetUnicode(String ascii, int index)
{
if (ascii==null) throw new ArgumentNullException(nameof(ascii));
Contract.EndContractBlock();
return GetUnicode(ascii, index, ascii.Length - index);
}
public String GetUnicode(String ascii, int index, int count)
{
if (ascii==null) throw new ArgumentNullException(nameof(ascii));
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index < 0) ? nameof(index) : nameof(count),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (index > ascii.Length)
throw new ArgumentOutOfRangeException("byteIndex",
Environment.GetResourceString("ArgumentOutOfRange_Index"));
if (index > ascii.Length - count)
throw new ArgumentOutOfRangeException(nameof(ascii),
Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
// This is a case (i.e. explicitly null-terminated input) where behavior in .NET and Win32 intentionally differ.
// The .NET APIs should (and did in v4.0 and earlier) throw an ArgumentException on input that includes a terminating null.
// The Win32 APIs fail on an embedded null, but not on a terminating null.
if (count > 0 && ascii[index + count - 1] == (char)0)
throw new ArgumentException(Environment.GetResourceString("Argument_IdnBadPunycode"),
nameof(ascii));
Contract.EndContractBlock();
// We're only using part of the string
ascii = ascii.Substring(index, count);
if (Environment.IsWindows8OrAbove)
{
return GetUnicodeUsingOS(ascii);
}
// Convert Punycode to Unicode
String strUnicode = punycode_decode(ascii);
// Output name MUST obey IDNA rules & round trip (casing differences are allowed)
if (!ascii.Equals(GetAscii(strUnicode), StringComparison.OrdinalIgnoreCase))
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnIllegalName"), nameof(ascii));
return strUnicode;
}
[System.Security.SecuritySafeCritical]
private string GetUnicodeUsingOS(string ascii)
{
uint flags = (uint)((AllowUnassigned ? IDN_ALLOW_UNASSIGNED : 0) | (UseStd3AsciiRules ? IDN_USE_STD3_ASCII_RULES : 0));
int length = IdnToUnicode(flags, ascii, ascii.Length, null, 0);
int lastError;
if (length == 0)
{
lastError = Marshal.GetLastWin32Error();
if (lastError == ERROR_INVALID_NAME)
{
throw new ArgumentException(Environment.GetResourceString("Argument_IdnIllegalName"), nameof(ascii));
}
throw new ArgumentException(Environment.GetResourceString("Argument_IdnBadPunycode"), nameof(ascii));
}
char [] output = new char[length];
length = IdnToUnicode(flags, ascii, ascii.Length, output, length);
if (length == 0)
{
lastError = Marshal.GetLastWin32Error();
if (lastError == ERROR_INVALID_NAME)
{
throw new ArgumentException(Environment.GetResourceString("Argument_IdnIllegalName"), nameof(ascii));
}
throw new ArgumentException(Environment.GetResourceString("Argument_IdnBadPunycode"), nameof(ascii));
}
return new String(output, 0, length);
}
public override bool Equals(Object obj)
{
IdnMapping that = obj as IdnMapping;
if (that != null)
{
return this.m_bAllowUnassigned == that.m_bAllowUnassigned &&
this.m_bUseStd3AsciiRules == that.m_bUseStd3AsciiRules;
}
return (false);
}
public override int GetHashCode()
{
return (this.m_bAllowUnassigned ? 100 : 200) + (this.m_bUseStd3AsciiRules ? 1000 : 2000);
}
// Helpers
static bool IsSupplementary(int cTest)
{
return cTest >= 0x10000;
}
// Is it a dot?
// are we U+002E (., full stop), U+3002 (ideographic full stop), U+FF0E (fullwidth full stop), or
// U+FF61 (halfwidth ideographic full stop).
// Note: IDNA Normalization gets rid of dots now, but testing for last dot is before normalization
static bool IsDot(char c)
{
return c == '.' || c == '\u3002' || c == '\uFF0E' || c == '\uFF61';
}
// See if we're only ASCII
static bool ValidateStd3AndAscii(string unicode, bool bUseStd3, bool bCheckAscii)
{
// If its empty, then its too small
if (unicode.Length == 0)
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadLabelSize"), nameof(unicode));
Contract.EndContractBlock();
int iLastDot = -1;
// Loop the whole string
for (int i = 0; i < unicode.Length; i++)
{
// Aren't allowing control chars (or 7f, but idn tables catch that, they don't catch \0 at end though)
if (unicode[i] <= 0x1f)
{
throw new ArgumentException(
Environment.GetResourceString("Argument_InvalidCharSequence", i ),
nameof(unicode));
}
// If its Unicode or a control character, return false (non-ascii)
if (bCheckAscii && unicode[i] >= 0x7f)
return false;
// Check for dots
if (IsDot(unicode[i]))
{
// Can't have 2 dots in a row
if (i == iLastDot + 1)
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadLabelSize"), nameof(unicode));
// If its too far between dots then fail
if (i - iLastDot > M_labelLimit + 1)
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadLabelSize"), nameof(unicode));
// If validating Std3, then char before dot can't be - char
if (bUseStd3 && i > 0)
ValidateStd3(unicode[i-1], true);
// Remember where the last dot is
iLastDot = i;
continue;
}
// If necessary, make sure its a valid std3 character
if (bUseStd3)
{
ValidateStd3(unicode[i], (i == iLastDot + 1));
}
}
// If we never had a dot, then we need to be shorter than the label limit
if (iLastDot == -1 && unicode.Length > M_labelLimit)
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadLabelSize"), nameof(unicode));
// Need to validate entire string length, 1 shorter if last char wasn't a dot
if (unicode.Length > M_defaultNameLimit - (IsDot(unicode[unicode.Length-1])? 0 : 1))
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadNameSize",
M_defaultNameLimit - (IsDot(unicode[unicode.Length-1]) ? 0 : 1)),
nameof(unicode));
// If last char wasn't a dot we need to check for trailing -
if (bUseStd3 && !IsDot(unicode[unicode.Length-1]))
ValidateStd3(unicode[unicode.Length-1], true);
return true;
}
// Validate Std3 rules for a character
static void ValidateStd3(char c, bool bNextToDot)
{
// Check for illegal characters
if ((c <= ',' || c == '/' || (c >= ':' && c <= '@') || // Lots of characters not allowed
(c >= '[' && c <= '`') || (c >= '{' && c <= (char)0x7F)) ||
(c == '-' && bNextToDot))
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadStd3", c), "Unicode");
}
//
// The following punycode implementation is ported from the sample punycode.c in RFC 3492
// Original sample code was written by Adam M. Costello.
//
// Return whether a punycode code point is flagged as being upper case.
static bool HasUpperCaseFlag(char punychar)
{
return (punychar >= 'A' && punychar <= 'Z');
}
/**********************************************************/
/* Implementation (would normally go in its own .c file): */
/*** Bootstring parameters for Punycode ***/
const int punycodeBase = 36;
const int tmin = 1;
const int tmax = 26;
const int skew = 38;
const int damp = 700;
const int initial_bias = 72;
const int initial_n = 0x80;
const char delimiter = '-';
/* basic(cp) tests whether cp is a basic code point: */
static bool basic(uint cp)
{
// Is it in ASCII range?
return cp < 0x80;
}
// decode_digit(cp) returns the numeric value of a basic code */
// point (for use in representing integers) in the range 0 to */
// punycodeBase-1, or <0 if cp is does not represent a value. */
static int decode_digit(char cp)
{
if (cp >= '0' && cp <= '9')
return cp - '0' + 26;
// Two flavors for case differences
if (cp >= 'a' && cp <= 'z')
return cp - 'a';
if (cp >= 'A' && cp <= 'Z')
return cp - 'A';
// Expected 0-9, A-Z or a-z, everything else is illegal
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadPunycode"), "ascii");
}
/* encode_digit(d,flag) returns the basic code point whose value */
/* (when used for representing integers) is d, which needs to be in */
/* the range 0 to punycodeBase-1. The lowercase form is used unless flag is */
/* true, in which case the uppercase form is used. */
static char encode_digit(int d)
{
Contract.Assert(d >= 0 && d < punycodeBase, "[IdnMapping.encode_digit]Expected 0 <= d < punycodeBase");
// 26-35 map to ASCII 0-9
if (d > 25) return (char)(d - 26 + '0');
// 0-25 map to a-z or A-Z
return (char)(d + 'a');
}
/* encode_basic(bcp,flag) forces a basic code point to lowercase */
/* if flag is false, uppercase if flag is true, and returns */
/* the resulting code point. The code point is unchanged if it */
/* is caseless. The behavior is undefined if bcp is not a basic */
/* code point. */
static char encode_basic(char bcp)
{
if (HasUpperCaseFlag(bcp))
bcp += (char)('a' - 'A');
return bcp;
}
/*** Platform-specific constants ***/
/* maxint is the maximum value of a uint variable: */
const int maxint = 0x7ffffff;
/*** Bias adaptation function ***/
static int adapt(
int delta, int numpoints, bool firsttime )
{
uint k;
delta = firsttime ? delta / damp : delta / 2;
Contract.Assert(numpoints != 0, "[IdnMapping.adapt]Expected non-zero numpoints.");
delta += delta / numpoints;
for (k = 0; delta > ((punycodeBase - tmin) * tmax) / 2; k += punycodeBase)
{
delta /= punycodeBase - tmin;
}
Contract.Assert(delta + skew != 0, "[IdnMapping.adapt]Expected non-zero delta+skew.");
return (int)(k + (punycodeBase - tmin + 1) * delta / (delta + skew));
}
/*** Main encode function ***/
/* punycode_encode() converts Unicode to Punycode. The input */
/* is represented as an array of Unicode code points (not code */
/* units; surrogate pairs are not allowed), and the output */
/* will be represented as an array of ASCII code points. The */
/* output string is *not* null-terminated; it will contain */
/* zeros if and only if the input contains zeros. (Of course */
/* the caller can leave room for a terminator and add one if */
/* needed.) The input_length is the number of code points in */
/* the input. The output_length is an in/out argument: the */
/* caller passes in the maximum number of code points that it */
/* can receive, and on successful return it will contain the */
/* number of code points actually output. The case_flags array */
/* holds input_length boolean values, where nonzero suggests that */
/* the corresponding Unicode character be forced to uppercase */
/* after being decoded (if possible), and zero suggests that */
/* it be forced to lowercase (if possible). ASCII code points */
/* are encoded literally, except that ASCII letters are forced */
/* to uppercase or lowercase according to the corresponding */
/* uppercase flags. If case_flags is a null pointer then ASCII */
/* letters are left as they are, and other code points are */
/* treated as if their uppercase flags were zero. The return */
/* value can be any of the punycode_status values defined above */
/* except punycode_bad_input; if not punycode_success, then */
/* output_size and output might contain garbage. */
static String punycode_encode(String unicode)
{
// 0 length strings aren't allowed
if (unicode.Length == 0)
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadLabelSize"), nameof(unicode));
Contract.EndContractBlock();
StringBuilder output = new StringBuilder(unicode.Length);
int iNextDot = 0;
int iAfterLastDot = 0;
int iOutputAfterLastDot = 0;
// Find the next dot
while (iNextDot < unicode.Length)
{
// Find end of this segment
iNextDot = unicode.IndexOfAny(M_Dots, iAfterLastDot);
Contract.Assert(iNextDot <= unicode.Length, "[IdnMapping.punycode_encode]IndexOfAny is broken");
if (iNextDot < 0)
iNextDot = unicode.Length;
// Only allowed to have empty . section at end (www.microsoft.com.)
if (iNextDot == iAfterLastDot)
{
// Only allowed to have empty sections as trailing .
if (iNextDot != unicode.Length)
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadLabelSize"), nameof(unicode));
// Last dot, stop
break;
}
// We'll need an Ace prefix
output.Append(M_strAcePrefix);
// Everything resets every segment.
bool bRightToLeft = false;
// Check for RTL. If right-to-left, then 1st & last chars must be RTL
BidiCategory eBidi = CharUnicodeInfo.GetBidiCategory(unicode, iAfterLastDot);
if (eBidi == BidiCategory.RightToLeft || eBidi == BidiCategory.RightToLeftArabic)
{
// It has to be right to left.
bRightToLeft = true;
// Check last char
int iTest = iNextDot - 1;
if (Char.IsLowSurrogate(unicode, iTest))
{
iTest--;
}
eBidi = CharUnicodeInfo.GetBidiCategory(unicode, iTest);
if (eBidi != BidiCategory.RightToLeft && eBidi != BidiCategory.RightToLeftArabic)
{
// Oops, last wasn't RTL, last should be RTL if first is RTL
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadBidi"), nameof(unicode));
}
}
// Handle the basic code points
int basicCount;
int numProcessed = 0; // Num code points that have been processed so far (this segment)
for (basicCount = iAfterLastDot; basicCount < iNextDot; basicCount++)
{
// Can't be lonely surrogate because it would've thrown in normalization
Contract.Assert(Char.IsLowSurrogate(unicode, basicCount) == false,
"[IdnMapping.punycode_encode]Unexpected low surrogate");
// Double check our bidi rules
BidiCategory testBidi = CharUnicodeInfo.GetBidiCategory(unicode, basicCount);
// If we're RTL, we can't have LTR chars
if (bRightToLeft && testBidi == BidiCategory.LeftToRight)
{
// Oops, throw error
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadBidi"), nameof(unicode));
}
// If we're not RTL we can't have RTL chars
if (!bRightToLeft && (testBidi == BidiCategory.RightToLeft ||
testBidi == BidiCategory.RightToLeftArabic))
{
// Oops, throw error
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadBidi"), nameof(unicode));
}
// If its basic then add it
if (basic(unicode[basicCount]))
{
output.Append(encode_basic(unicode[basicCount]));
numProcessed++;
}
// If its a surrogate, skip the next since our bidi category tester doesn't handle it.
else if (Char.IsSurrogatePair(unicode, basicCount))
basicCount++;
}
int numBasicCodePoints = numProcessed; // number of basic code points
// Stop if we ONLY had basic code points
if (numBasicCodePoints == iNextDot - iAfterLastDot)
{
// Get rid of xn-- and this segments done
output.Remove(iOutputAfterLastDot, M_strAcePrefix.Length);
}
else
{
// If it has some non-basic code points the input cannot start with xn--
if (unicode.Length - iAfterLastDot >= M_strAcePrefix.Length &&
unicode.Substring(iAfterLastDot, M_strAcePrefix.Length).Equals(
M_strAcePrefix, StringComparison.OrdinalIgnoreCase))
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadPunycode"), nameof(unicode));
// Need to do ACE encoding
int numSurrogatePairs = 0; // number of surrogate pairs so far
// Add a delimiter (-) if we had any basic code points (between basic and encoded pieces)
if (numBasicCodePoints > 0)
{
output.Append(delimiter);
}
// Initialize the state
int n = initial_n;
int delta = 0;
int bias = initial_bias;
// Main loop
while (numProcessed < (iNextDot - iAfterLastDot))
{
/* All non-basic code points < n have been */
/* handled already. Find the next larger one: */
int j;
int m;
int test = 0;
for (m = maxint, j = iAfterLastDot;
j < iNextDot;
j += IsSupplementary(test) ? 2 : 1)
{
test = Char.ConvertToUtf32(unicode, j);
if (test >= n && test < m) m = test;
}
/* Increase delta enough to advance the decoder's */
/* <n,i> state to <m,0>, but guard against overflow: */
delta += (int)((m - n) * ((numProcessed - numSurrogatePairs) + 1));
Contract.Assert(delta > 0, "[IdnMapping.cs]1 punycode_encode - delta overflowed int");
n = m;
for (j = iAfterLastDot; j < iNextDot; j+= IsSupplementary(test) ? 2 : 1)
{
// Make sure we're aware of surrogates
test = Char.ConvertToUtf32(unicode, j);
// Adjust for character position (only the chars in our string already, some
// haven't been processed.
if (test < n)
{
delta++;
Contract.Assert(delta > 0, "[IdnMapping.cs]2 punycode_encode - delta overflowed int");
}
if (test == n)
{
// Represent delta as a generalized variable-length integer:
int q, k;
for (q = delta, k = punycodeBase; ; k += punycodeBase)
{
int t = k <= bias ? tmin :
k >= bias + tmax ? tmax : k - bias;
if (q < t) break;
Contract.Assert(punycodeBase != t, "[IdnMapping.punycode_encode]Expected punycodeBase (36) to be != t");
output.Append(encode_digit(t + (q - t) % (punycodeBase - t)));
q = (q - t) / (punycodeBase - t);
}
output.Append(encode_digit(q));
bias = adapt(delta, (numProcessed - numSurrogatePairs) + 1, numProcessed == numBasicCodePoints);
delta = 0;
numProcessed++;
if (IsSupplementary(m))
{
numProcessed++;
numSurrogatePairs++;
}
}
}
++delta;
++n;
Contract.Assert(delta > 0, "[IdnMapping.cs]3 punycode_encode - delta overflowed int");
}
}
// Make sure its not too big
if (output.Length - iOutputAfterLastDot > M_labelLimit)
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadLabelSize"), nameof(unicode));
// Done with this segment, add dot if necessary
if (iNextDot != unicode.Length)
output.Append('.');
iAfterLastDot = iNextDot + 1;
iOutputAfterLastDot = output.Length;
}
// Throw if we're too long
if (output.Length > M_defaultNameLimit - (IsDot(unicode[unicode.Length-1]) ? 0 : 1))
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadNameSize",
M_defaultNameLimit - (IsDot(unicode[unicode.Length-1]) ? 0 : 1)),
nameof(unicode));
// Return our output string
return output.ToString();
}
/*** Main decode function ***/
/* punycode_decode() converts Punycode to Unicode. The input is */
/* represented as an array of ASCII code points, and the output */
/* will be represented as an array of Unicode code points. The */
/* input_length is the number of code points in the input. The */
/* output_length is an in/out argument: the caller passes in */
/* the maximum number of code points that it can receive, and */
/* on successful return it will contain the actual number of */
/* code points output. The case_flags array needs room for at */
/* least output_length values, or it can be a null pointer if the */
/* case information is not needed. A nonzero flag suggests that */
/* the corresponding Unicode character be forced to uppercase */
/* by the caller (if possible), while zero suggests that it be */
/* forced to lowercase (if possible). ASCII code points are */
/* output already in the proper case, but their flags will be set */
/* appropriately so that applying the flags would be harmless. */
/* The return value can be any of the punycode_status values */
/* defined above; if not punycode_success, then output_length, */
/* output, and case_flags might contain garbage. On success, the */
/* decoder will never need to write an output_length greater than */
/* input_length, because of how the encoding is defined. */
static String punycode_decode( String ascii )
{
// 0 length strings aren't allowed
if (ascii.Length == 0)
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadLabelSize"), nameof(ascii));
Contract.EndContractBlock();
// Throw if we're too long
if (ascii.Length > M_defaultNameLimit - (IsDot(ascii[ascii.Length-1]) ? 0 : 1))
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadNameSize",
M_defaultNameLimit - (IsDot(ascii[ascii.Length-1]) ? 0 : 1)), nameof(ascii));
// output stringbuilder
StringBuilder output = new StringBuilder(ascii.Length);
// Dot searching
int iNextDot = 0;
int iAfterLastDot = 0;
int iOutputAfterLastDot = 0;
while (iNextDot < ascii.Length)
{
// Find end of this segment
iNextDot = ascii.IndexOf('.', iAfterLastDot);
if (iNextDot < 0 || iNextDot > ascii.Length)
iNextDot = ascii.Length;
// Only allowed to have empty . section at end (www.microsoft.com.)
if (iNextDot == iAfterLastDot)
{
// Only allowed to have empty sections as trailing .
if (iNextDot != ascii.Length)
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadLabelSize"), nameof(ascii));
// Last dot, stop
break;
}
// In either case it can't be bigger than segment size
if (iNextDot - iAfterLastDot > M_labelLimit)
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadLabelSize"), nameof(ascii));
// See if this section's ASCII or ACE
if (ascii.Length < M_strAcePrefix.Length + iAfterLastDot ||
!ascii.Substring(iAfterLastDot, M_strAcePrefix.Length).Equals(
M_strAcePrefix, StringComparison.OrdinalIgnoreCase))
{
// Its supposed to be just ASCII
// Actually, for non xn-- stuff do we want to allow Unicode?
// for (int i = iAfterLastDot; i < iNextDot; i++)
// {
// // Only ASCII is allowed
// if (ascii[i] >= 0x80)
// throw new ArgumentException(Environment.GetResourceString(
// "Argument_IdnBadPunycode"), nameof(ascii));
// }
// Its ASCII, copy it
output.Append(ascii.Substring(iAfterLastDot, iNextDot - iAfterLastDot));
// ASCII doesn't have BIDI issues
}
else
{
// Not ASCII, bump up iAfterLastDot to be after ACE Prefix
iAfterLastDot += M_strAcePrefix.Length;
// Get number of basic code points (where delimiter is)
// numBasicCodePoints < 0 if there're no basic code points
int iTemp = ascii.LastIndexOf(delimiter, iNextDot - 1);
// Trailing - not allowed
if (iTemp == iNextDot - 1)
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadPunycode"), nameof(ascii));
int numBasicCodePoints;
if (iTemp <= iAfterLastDot)
numBasicCodePoints = 0;
else
{
numBasicCodePoints = iTemp - iAfterLastDot;
// Copy all the basic code points, making sure they're all in the allowed range,
// and losing the casing for all of them.
for (int copyAscii = iAfterLastDot;
copyAscii < iAfterLastDot + numBasicCodePoints;
copyAscii++)
{
// Make sure we don't allow unicode in the ascii part
if (ascii[copyAscii] > 0x7f)
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadPunycode"), nameof(ascii));
// When appending make sure they get lower cased
output.Append((char)(ascii[copyAscii] >= 'A' && ascii[copyAscii] <='Z' ?
ascii[copyAscii] - 'A' + 'a' :
ascii[copyAscii]));
}
}
// Get ready for main loop. Start at beginning if we didn't have any
// basic code points, otherwise start after the -.
// asciiIndex will be next character to read from ascii
int asciiIndex = iAfterLastDot +
( numBasicCodePoints > 0 ? numBasicCodePoints + 1 : 0);
// initialize our state
int n = initial_n;
int bias = initial_bias;
int i = 0;
int w, k;
// no Supplementary characters yet
int numSurrogatePairs = 0;
// Main loop, read rest of ascii
while (asciiIndex < iNextDot)
{
/* Decode a generalized variable-length integer into delta, */
/* which gets added to i. The overflow checking is easier */
/* if we increase i as we go, then subtract off its starting */
/* value at the end to obtain delta. */
int oldi = i;
for (w = 1, k = punycodeBase; ; k += punycodeBase)
{
// Check to make sure we aren't overrunning our ascii string
if (asciiIndex >= iNextDot)
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadPunycode"), nameof(ascii));
// decode the digit from the next char
int digit = decode_digit(ascii[asciiIndex++]);
Contract.Assert(w > 0, "[IdnMapping.punycode_decode]Expected w > 0");
if (digit > (maxint - i) / w)
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadPunycode"), nameof(ascii));
i += (int)(digit * w);
int t = k <= bias ? tmin :
k >= bias + tmax ? tmax : k - bias;
if (digit < t) break;
Contract.Assert(punycodeBase != t, "[IdnMapping.punycode_decode]Expected t != punycodeBase (36)");
if (w > maxint / (punycodeBase - t))
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadPunycode"), nameof(ascii));
w *= (punycodeBase - t);
}
bias = adapt(i - oldi,
(output.Length - iOutputAfterLastDot - numSurrogatePairs) + 1, oldi == 0);
/* i was supposed to wrap around from output.Length to 0, */
/* incrementing n each time, so we'll fix that now: */
Contract.Assert((output.Length - iOutputAfterLastDot - numSurrogatePairs) + 1 > 0,
"[IdnMapping.punycode_decode]Expected to have added > 0 characters this segment");
if (i / ((output.Length - iOutputAfterLastDot - numSurrogatePairs) + 1) > maxint - n)
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadPunycode"), nameof(ascii));
n += (int)(i / (output.Length - iOutputAfterLastDot - numSurrogatePairs + 1));
i %= (output.Length - iOutputAfterLastDot - numSurrogatePairs + 1);
// If it was flagged it needs to be capitalized
// if (HasUpperCaseFlag(ascii[asciiIndex - 1]))
// {
// /* Case of last character determines uppercase flag: */
// // Any casing stuff need to happen last.
// If we wanted to reverse the IDNA casing data
// n = MakeNUpperCase(n)
// }
// Make sure n is legal
if ((n < 0 || n > 0x10ffff) || (n >= 0xD800 && n <= 0xDFFF))
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadPunycode"), nameof(ascii));
// insert n at position i of the output: Really tricky if we have surrogates
int iUseInsertLocation;
String strTemp = Char.ConvertFromUtf32(n);
// If we have supplimentary characters
if (numSurrogatePairs > 0)
{
// Hard way, we have supplimentary characters
int iCount;
for (iCount = i, iUseInsertLocation = iOutputAfterLastDot;
iCount > 0;
iCount--, iUseInsertLocation++)
{
// If its a surrogate, we have to go one more
if (iUseInsertLocation >= output.Length)
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadPunycode"), nameof(ascii));
if (Char.IsSurrogate(output[iUseInsertLocation]))
iUseInsertLocation++;
}
}
else
{
// No Supplementary chars yet, just add i
iUseInsertLocation = iOutputAfterLastDot + i;
}
// Insert it
output.Insert(iUseInsertLocation, strTemp);
// If it was a surrogate increment our counter
if (IsSupplementary(n))
numSurrogatePairs++;
// Index gets updated
i++;
}
// Do BIDI testing
bool bRightToLeft = false;
// Check for RTL. If right-to-left, then 1st & last chars must be RTL
BidiCategory eBidi = CharUnicodeInfo.GetBidiCategory(output.ToString(), iOutputAfterLastDot);
if (eBidi == BidiCategory.RightToLeft || eBidi == BidiCategory.RightToLeftArabic)
{
// It has to be right to left.
bRightToLeft = true;
}
// Check the rest of them to make sure RTL/LTR is consistent
for (int iTest = iOutputAfterLastDot; iTest < output.Length; iTest++)
{
// This might happen if we run into a pair
if (Char.IsLowSurrogate(output.ToString(), iTest)) continue;
// Check to see if its LTR
eBidi = CharUnicodeInfo.GetBidiCategory(output.ToString(), iTest);
if ((bRightToLeft && eBidi == BidiCategory.LeftToRight) ||
(!bRightToLeft && (eBidi == BidiCategory.RightToLeft ||
eBidi == BidiCategory.RightToLeftArabic)))
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadBidi"), nameof(ascii));
// Make it lower case if we must (so we can test IsNormalized later)
// if (output[iTest] >= 'A' && output[iTest] <= 'Z')
// output[iTest] = (char)(output[iTest] + (char)('a' - 'A'));
}
// Its also a requirement that the last one be RTL if 1st is RTL
if (bRightToLeft && eBidi != BidiCategory.RightToLeft && eBidi != BidiCategory.RightToLeftArabic)
{
// Oops, last wasn't RTL, last should be RTL if first is RTL
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadBidi"), nameof(ascii));
}
}
// See if this label was too long
if (iNextDot - iAfterLastDot > M_labelLimit)
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadLabelSize"), nameof(ascii));
// Done with this segment, add dot if necessary
if (iNextDot != ascii.Length)
output.Append('.');
iAfterLastDot = iNextDot + 1;
iOutputAfterLastDot = output.Length;
}
// Throw if we're too long
if (output.Length > M_defaultNameLimit - (IsDot(output[output.Length-1]) ? 0 : 1))
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadNameSize",
M_defaultNameLimit -(IsDot(output[output.Length-1]) ? 0 : 1)), nameof(ascii));
// Return our output string
return output.ToString();
}
/*
The previous punycode implimentation is based on the sample code in RFC 3492
Full Copyright Statement
Copyright (C) The Internet Society (2003). All Rights Reserved.
This document and translations of it may be copied and furnished to
others, and derivative works that comment on or otherwise explain it
or assist in its implementation may be prepared, copied, published
and distributed, in whole or in part, without restriction of any
kind, provided that the above copyright notice and this paragraph are
included on all such copies and derivative works. However, this
document itself may not be modified in any way, such as by removing
the copyright notice or references to the Internet Society or other
Internet organizations, except as needed for the purpose of
developing Internet standards in which case the procedures for
copyrights defined in the Internet Standards process must be
followed, or as required to translate it into languages other than
English.
The limited permissions granted above are perpetual and will not be
revoked by the Internet Society or its successors or assigns.
This document and the information contained herein is provided on an
"AS IS" basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING
TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING
BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION
HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
*/
private const int IDN_ALLOW_UNASSIGNED = 0x1;
private const int IDN_USE_STD3_ASCII_RULES = 0x2;
private const int ERROR_INVALID_NAME = 123;
[System.Security.SecurityCritical]
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
private static extern int IdnToAscii(
uint dwFlags,
[InAttribute()]
[MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPWStr)]
String lpUnicodeCharStr,
int cchUnicodeChar,
[System.Runtime.InteropServices.OutAttribute()]
char [] lpASCIICharStr,
int cchASCIIChar);
[System.Security.SecurityCritical]
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
private static extern int IdnToUnicode(
uint dwFlags,
[InAttribute()]
[MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPWStr)]
string lpASCIICharStr,
int cchASCIIChar,
[System.Runtime.InteropServices.OutAttribute()]
char [] lpUnicodeCharStr,
int cchUnicodeChar);
}
}
| |
// 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.
//-----------------------------------------------------------------------------
//
// Description:
// This is a sub class of the abstract class for Package.
// This implementation is specific to Zip file format.
//
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Xml; //Required for Content Type File manipulation
using System.Diagnostics;
using System.IO.Compression;
namespace System.IO.Packaging
{
/// <summary>
/// ZipPackage is a specific implementation for the abstract Package
/// class, corresponding to the Zip file format.
/// This is a part of the Packaging Layer APIs.
/// </summary>
public sealed class ZipPackage : Package
{
//------------------------------------------------------
//
// Public Constructors
//
//------------------------------------------------------
// None
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
// None
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region Public Methods
#region PackagePart Methods
/// <summary>
/// This method is for custom implementation for the underlying file format
/// Adds a new item to the zip archive corresponding to the PackagePart in the package.
/// </summary>
/// <param name="partUri">PartName</param>
/// <param name="contentType">Content type of the part</param>
/// <param name="compressionOption">Compression option for this part</param>
/// <returns></returns>
/// <exception cref="ArgumentNullException">If partUri parameter is null</exception>
/// <exception cref="ArgumentNullException">If contentType parameter is null</exception>
/// <exception cref="ArgumentException">If partUri parameter does not conform to the valid partUri syntax</exception>
/// <exception cref="ArgumentOutOfRangeException">If CompressionOption enumeration [compressionOption] does not have one of the valid values</exception>
protected override PackagePart CreatePartCore(Uri partUri,
string contentType,
CompressionOption compressionOption)
{
//Validating the PartUri - this method will do the argument checking required for uri.
partUri = PackUriHelper.ValidatePartUri(partUri);
if (contentType == null)
throw new ArgumentNullException("contentType");
Package.ThrowIfCompressionOptionInvalid(compressionOption);
// Convert Metro CompressionOption to Zip CompressionMethodEnum.
CompressionLevel level;
GetZipCompressionMethodFromOpcCompressionOption(compressionOption,
out level);
// Create new Zip item.
// We need to remove the leading "/" character at the beginning of the part name.
// The partUri object must be a ValidatedPartUri
string zipItemName = ((PackUriHelper.ValidatedPartUri)partUri).PartUriString.Substring(1);
ZipArchiveEntry zipArchiveEntry = _zipArchive.CreateEntry(zipItemName, level);
//Store the content type of this part in the content types stream.
_contentTypeHelper.AddContentType((PackUriHelper.ValidatedPartUri)partUri, new ContentType(contentType), level);
return new ZipPackagePart(this, zipArchiveEntry.Archive, zipArchiveEntry, _zipStreamManager, (PackUriHelper.ValidatedPartUri)partUri, contentType, compressionOption);
}
/// <summary>
/// This method is for custom implementation specific to the file format.
/// Returns the part after reading the actual physical bits. The method
/// returns a null to indicate that the part corresponding to the specified
/// Uri was not found in the container.
/// This method does not throw an exception if a part does not exist.
/// </summary>
/// <param name="partUri"></param>
/// <returns></returns>
protected override PackagePart GetPartCore(Uri partUri)
{
//Currently the design has two aspects which makes it possible to return
//a null from this method -
// 1. All the parts are loaded at Package.Open time and as such, this
// method would not be invoked, unless the user is asking for -
// i. a part that does not exist - we can safely return null
// ii.a part(interleaved/non-interleaved) that was added to the
// underlying package by some other means, and the user wants to
// access the updated part. This is currently not possible as the
// underlying zip i/o layer does not allow for FileShare.ReadWrite.
// 2. Also, its not a straighforward task to determine if a new part was
// added as we need to look for atomic as well as interleaved parts and
// this has to be done in a case sensitive manner. So, effectively
// we will have to go through the entire list of zip items to determine
// if there are any updates.
// If ever the design changes, then this method must be updated accordingly
return null;
}
/// <summary>
/// This method is for custom implementation specific to the file format.
/// Deletes the part corresponding to the uri specified. Deleting a part that does not
/// exists is not an error and so we do not throw an exception in that case.
/// </summary>
/// <param name="partUri"></param>
/// <exception cref="ArgumentNullException">If partUri parameter is null</exception>
/// <exception cref="ArgumentException">If partUri parameter does not conform to the valid partUri syntax</exception>
protected override void DeletePartCore(Uri partUri)
{
//Validating the PartUri - this method will do the argument checking required for uri.
partUri = PackUriHelper.ValidatePartUri(partUri);
string partZipName = GetZipItemNameFromOpcName(PackUriHelper.GetStringForPartUri(partUri));
ZipArchiveEntry zipArchiveEntry = _zipArchive.GetEntry(partZipName);
if (zipArchiveEntry != null)
{
// Case of an atomic part.
zipArchiveEntry.Delete();
}
//Delete the content type for this part if it was specified as an override
_contentTypeHelper.DeleteContentType((PackUriHelper.ValidatedPartUri)partUri);
}
/// <summary>
/// This method is for custom implementation specific to the file format.
/// This is the method that knows how to get the actual parts from the underlying
/// zip archive.
/// </summary>
/// <remarks>
/// <para>
/// Some or all of the parts may be interleaved. The Part object for an interleaved part encapsulates
/// the Uri of the proper part name and the ZipFileInfo of the initial piece.
/// This function does not go through the extra work of checking piece naming validity
/// throughout the package.
/// </para>
/// <para>
/// This means that interleaved parts without an initial piece will be silently ignored.
/// Other naming anomalies get caught at the Stream level when an I/O operation involves
/// an anomalous or missing piece.
/// </para>
/// <para>
/// This function reads directly from the underlying IO layer and is supposed to be called
/// just once in the lifetime of a package (at init time).
/// </para>
/// </remarks>
/// <returns>An array of ZipPackagePart.</returns>
protected override PackagePart[] GetPartsCore()
{
List<PackagePart> parts = new List<PackagePart>(InitialPartListSize);
// The list of files has to be searched linearly (1) to identify the content type
// stream, and (2) to identify parts.
System.Collections.ObjectModel.ReadOnlyCollection<ZipArchiveEntry> zipArchiveEntries = _zipArchive.Entries;
// We have already identified the [ContentTypes].xml pieces if any are present during
// the initialization of ZipPackage object
// Record parts and ignored items.
foreach (ZipArchiveEntry zipArchiveEntry in zipArchiveEntries)
{
//Returns false if -
// a. its a content type item
// b. items that have either a leading or trailing slash.
if (IsZipItemValidOpcPartOrPiece(zipArchiveEntry.FullName))
{
Uri partUri = new Uri(GetOpcNameFromZipItemName(zipArchiveEntry.FullName), UriKind.Relative);
PackUriHelper.ValidatedPartUri validatedPartUri;
if (PackUriHelper.TryValidatePartUri(partUri, out validatedPartUri))
{
ContentType contentType = _contentTypeHelper.GetContentType(validatedPartUri);
if (contentType != null)
{
// In case there was some redundancy between pieces and/or the atomic
// part, it will be detected at this point because the part's Uri (which
// is independent of interleaving) will already be in the dictionary.
parts.Add(new ZipPackagePart(this, zipArchiveEntry.Archive, zipArchiveEntry,
_zipStreamManager, validatedPartUri, contentType.ToString(), GetCompressionOptionFromZipFileInfo(zipArchiveEntry)));
}
}
//If not valid part uri we can completely ignore this zip file item. Even if later someone adds
//a new part, the corresponding zip item can never map to one of these items
}
// If IsZipItemValidOpcPartOrPiece returns false, it implies that either the zip file Item
// starts or ends with a "/" and as such we can completely ignore this zip file item. Even if later
// a new part gets added, its corresponding zip item cannot map to one of these items.
}
return parts.ToArray();
}
#endregion PackagePart Methods
#region Other Methods
/// <summary>
/// This method is for custom implementation corresponding to the underlying zip file format.
/// </summary>
protected override void FlushCore()
{
//Save the content type file to the archive.
_contentTypeHelper.SaveToFile();
}
/// <summary>
/// Closes the underlying ZipArchive object for this container
/// </summary>
/// <param name="disposing">True if called during Dispose, false if called during Finalize</param>
protected override void Dispose(bool disposing)
{
try
{
if (disposing)
{
if (_contentTypeHelper != null)
{
_contentTypeHelper.SaveToFile();
}
if (_zipStreamManager != null)
{
_zipStreamManager.Dispose();
}
if (_zipArchive != null)
{
_zipArchive.Dispose();
}
// _containerStream may be opened given a file name, in which case it should be closed here.
// _containerStream may be passed into the constructor, in which case, it should not be closed here.
if (_shouldCloseContainerStream)
{
_containerStream.Dispose();
}
else
{
}
_containerStream = null;
}
}
finally
{
base.Dispose(disposing);
}
}
#endregion Other Methods
#endregion Public Methods
//------------------------------------------------------
//
// Public Events
//
//------------------------------------------------------
// None
//------------------------------------------------------
//
// Internal Constructors
//
//------------------------------------------------------
#region Internal Constructors
/// <summary>
/// Internal constructor that is called by the OpenOnFile static method.
/// </summary>
/// <param name="path">File path to the container.</param>
/// <param name="packageFileMode">Container is opened in the specified mode if possible</param>
/// <param name="packageFileAccess">Container is opened with the speficied access if possible</param>
/// <param name="share">Container is opened with the specified share if possible</param>
internal ZipPackage(string path, FileMode packageFileMode, FileAccess packageFileAccess, FileShare share)
: base(packageFileAccess)
{
ZipArchive zipArchive = null;
ContentTypeHelper contentTypeHelper = null;
_packageFileMode = packageFileMode;
_packageFileAccess = packageFileAccess;
try
{
_containerStream = new FileStream(path, _packageFileMode, _packageFileAccess, share);
_shouldCloseContainerStream = true;
ZipArchiveMode zipArchiveMode = ZipArchiveMode.Update;
if (packageFileAccess == FileAccess.Read)
zipArchiveMode = ZipArchiveMode.Read;
else if (packageFileAccess == FileAccess.Write)
zipArchiveMode = ZipArchiveMode.Create;
else if (packageFileAccess == FileAccess.ReadWrite)
zipArchiveMode = ZipArchiveMode.Update;
zipArchive = new ZipArchive(_containerStream, zipArchiveMode, true, Text.Encoding.UTF8);
_zipStreamManager = new ZipStreamManager(zipArchive, _packageFileMode, _packageFileAccess);
contentTypeHelper = new ContentTypeHelper(zipArchive, _packageFileMode, _packageFileAccess, _zipStreamManager);
}
catch
{
if (zipArchive != null)
{
zipArchive.Dispose();
}
throw;
}
_zipArchive = zipArchive;
_contentTypeHelper = contentTypeHelper;
}
/// <summary>
/// Internal constructor that is called by the Open(Stream) static methods.
/// </summary>
/// <param name="s"></param>
/// <param name="packageFileMode"></param>
/// <param name="packageFileAccess"></param>
internal ZipPackage(Stream s, FileMode packageFileMode, FileAccess packageFileAccess)
: base(packageFileAccess)
{
ZipArchive zipArchive = null;
ContentTypeHelper contentTypeHelper = null;
_packageFileMode = packageFileMode;
_packageFileAccess = packageFileAccess;
try
{
ZipArchiveMode zipArchiveMode = ZipArchiveMode.Update;
if (packageFileAccess == FileAccess.Read)
zipArchiveMode = ZipArchiveMode.Read;
else if (packageFileAccess == FileAccess.Write)
zipArchiveMode = ZipArchiveMode.Create;
else if (packageFileAccess == FileAccess.ReadWrite)
zipArchiveMode = ZipArchiveMode.Update;
zipArchive = new ZipArchive(s, zipArchiveMode, true, Text.Encoding.UTF8);
_zipStreamManager = new ZipStreamManager(zipArchive, packageFileMode, packageFileAccess);
contentTypeHelper = new ContentTypeHelper(zipArchive, packageFileMode, packageFileAccess, _zipStreamManager);
}
catch (InvalidDataException)
{
throw new FileFormatException("File contains corrupted data.");
}
catch
{
if (zipArchive != null)
{
zipArchive.Dispose();
}
throw;
}
_containerStream = s;
_shouldCloseContainerStream = false;
_zipArchive = zipArchive;
_contentTypeHelper = contentTypeHelper;
}
#endregion Internal Constructors
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Methods
// More generic function than GetZipItemNameFromPartName. In particular, it will handle piece names.
internal static string GetZipItemNameFromOpcName(string opcName)
{
Debug.Assert(opcName != null && opcName.Length > 0);
return opcName.Substring(1);
}
// More generic function than GetPartNameFromZipItemName. In particular, it will handle piece names.
internal static string GetOpcNameFromZipItemName(string zipItemName)
{
return String.Concat(ForwardSlashString, zipItemName);
}
// Convert from Metro CompressionOption to ZipFileInfo compression properties.
internal static void GetZipCompressionMethodFromOpcCompressionOption(
CompressionOption compressionOption,
out CompressionLevel compressionLevel)
{
switch (compressionOption)
{
case CompressionOption.NotCompressed:
{
compressionLevel = CompressionLevel.NoCompression;
}
break;
case CompressionOption.Normal:
{
compressionLevel = CompressionLevel.Optimal;
}
break;
case CompressionOption.Maximum:
{
compressionLevel = CompressionLevel.Optimal;
}
break;
case CompressionOption.Fast:
{
compressionLevel = CompressionLevel.Fastest;
}
break;
case CompressionOption.SuperFast:
{
compressionLevel = CompressionLevel.Fastest;
}
break;
// fall-through is not allowed
default:
{
Debug.Assert(false, "Encountered an invalid CompressionOption enum value");
goto case CompressionOption.NotCompressed;
}
}
}
#endregion Internal Methods
//------------------------------------------------------
//
// Internal Properties
//
//------------------------------------------------------
internal FileMode PackageFileMode
{
get
{
return _packageFileMode;
}
}
//------------------------------------------------------
//
// Internal Events
//
//------------------------------------------------------
// None
//------------------------------------------------------
//
// Private Methods
//
//------------------------------------------------------
#region Private Methods
//returns a boolean indicating if the underlying zip item is a valid metro part or piece
// This mainly excludes the content type item, as well as entries with leading or trailing
// slashes.
private bool IsZipItemValidOpcPartOrPiece(string zipItemName)
{
Debug.Assert(zipItemName != null, "The parameter zipItemName should not be null");
//check if the zip item is the Content type item -case sensitive comparison
// The following test will filter out an atomic content type file, with name
// "[Content_Types].xml", as well as an interleaved one, with piece names such as
// "[Content_Types].xml/[0].piece" or "[Content_Types].xml/[5].last.piece".
if (zipItemName.StartsWith(ContentTypeHelper.ContentTypeFileName, StringComparison.OrdinalIgnoreCase))
return false;
else
{
//Could be an empty zip folder
//We decided to ignore zip items that contain a "/" as this could be a folder in a zip archive
//Some of the tools support this and some dont. There is no way ensure that the zip item never have
//a leading "/", although this is a requirement we impose on items created through our API
//Therefore we ignore them at the packaging api level.
if (zipItemName.StartsWith(ForwardSlashString, StringComparison.Ordinal))
return false;
//This will ignore the folder entries found in the zip package created by some zip tool
//PartNames ending with a "/" slash is also invalid so we are skipping these entries,
//this will also prevent the PackUriHelper.CreatePartUri from throwing when it encounters a
// partname ending with a "/"
if (zipItemName.EndsWith(ForwardSlashString, StringComparison.Ordinal))
return false;
else
return true;
}
}
// convert from Zip CompressionMethodEnum and DeflateOptionEnum to Metro CompressionOption
static private CompressionOption GetCompressionOptionFromZipFileInfo(ZipArchiveEntry zipFileInfo)
{
// Note: we can't determine compression method / level from the ZipArchiveEntry.
CompressionOption result = CompressionOption.Normal;
return result;
}
#endregion Private Methods
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
#region Private Members
private const int InitialPartListSize = 50;
private const int InitialPieceNameListSize = 50;
private ZipArchive _zipArchive;
private Stream _containerStream; // stream we are opened in if Open(Stream) was called
private bool _shouldCloseContainerStream;
private ContentTypeHelper _contentTypeHelper; // manages the content types for all the parts in the container
private ZipStreamManager _zipStreamManager; // manages streams for all parts, avoiding opening streams multiple times
private FileAccess _packageFileAccess;
private FileMode _packageFileMode;
private const string ForwardSlashString = "/"; //Required for creating a part name from a zip item name
//IEqualityComparer for extensions
private static readonly ExtensionEqualityComparer s_extensionEqualityComparer = new ExtensionEqualityComparer();
#endregion Private Members
//------------------------------------------------------
//
// Private Types
//
//------------------------------------------------------
#region Private Class
/// <summary>
/// ExtensionComparer
/// The Extensions are stored in the Default Dicitonary in their original form,
/// however they are compared in a normalized manner.
/// Equivalence for extensions in the content type stream, should follow
/// the same rules as extensions of partnames. Also, by the time this code is invoked,
/// we have already validated, that the extension is in the correct format as per the
/// part name rules.So we are simplifying the logic here to just convert the extensions
/// to Upper invariant form and then compare them.
/// </summary>
private sealed class ExtensionEqualityComparer : IEqualityComparer<string>
{
bool IEqualityComparer<string>.Equals(string extensionA, string extensionB)
{
Debug.Assert(extensionA != null, "extenstion should not be null");
Debug.Assert(extensionB != null, "extenstion should not be null");
//Important Note: any change to this should be made in accordance
//with the rules for comparing/normalizing partnames.
//Refer to PackUriHelper.ValidatedPartUri.GetNormalizedPartUri method.
//Currently normalization just involves upper-casing ASCII and hence the simplification.
return (String.CompareOrdinal(extensionA.ToUpperInvariant(), extensionB.ToUpperInvariant()) == 0);
}
int IEqualityComparer<string>.GetHashCode(string extension)
{
Debug.Assert(extension != null, "extenstion should not be null");
//Important Note: any change to this should be made in accordance
//with the rules for comparing/normalizing partnames.
//Refer to PackUriHelper.ValidatedPartUri.GetNormalizedPartUri method.
//Currently normalization just involves upper-casing ASCII and hence the simplification.
return extension.ToUpperInvariant().GetHashCode();
}
}
#region ContentTypeHelper Class
/// <summary>
/// This is a helper class that maintains the Content Types File related to
/// this ZipPackage.
/// </summary>
private class ContentTypeHelper
{
#region Constructor
/// <summary>
/// Initialize the object without uploading any information from the package.
/// Complete initialization in read mode also involves calling ParseContentTypesFile
/// to deserialize content type information.
/// </summary>
internal ContentTypeHelper(ZipArchive zipArchive, FileMode packageFileMode, FileAccess packageFileAccess, ZipStreamManager zipStreamManager)
{
_zipArchive = zipArchive; //initialized in the ZipPackage constructor
_packageFileMode = packageFileMode;
_packageFileAccess = packageFileAccess;
_zipStreamManager = zipStreamManager; //initialized in the ZipPackage constructor
// The extensions are stored in the default Dictionary in their original form , but they are compared
// in a normalized manner using the ExtensionComparer.
_defaultDictionary = new Dictionary<string, ContentType>(s_defaultDictionaryInitialSize, s_extensionEqualityComparer);
// Identify the content type file or files before identifying parts and piece sequences.
// This is necessary because the name of the content type stream is not a part name and
// the information it contains is needed to recognize valid parts.
if (_zipArchive.Mode == ZipArchiveMode.Read || _zipArchive.Mode == ZipArchiveMode.Update)
ParseContentTypesFile(_zipArchive.Entries);
//No contents to persist to the disk -
_dirty = false; //by default
//Lazy initialize these members as required
//_overrideDictionary - Overrides should be rare
//_contentTypeFileInfo - We will either find an atomin part, or
//_contentTypeStreamPieces - an interleaved part
//_contentTypeStreamExists - defaults to false - not yet found
}
#endregion Constructor
#region Internal Properties
internal static string ContentTypeFileName
{
get
{
return s_contentTypesFile;
}
}
#endregion Internal Properties
#region Internal Methods
//Adds the Default entry if it is the first time we come across
//the extension for the partUri, does nothing if the content type
//corresponding to the default entry for the extension matches or
//adds a override corresponding to this part and content type.
//This call is made when a new part is being added to the package.
// This method assumes the partUri is valid.
internal void AddContentType(PackUriHelper.ValidatedPartUri partUri, ContentType contentType,
CompressionLevel compressionLevel)
{
//save the compressionOption and deflateOption that should be used
//to create the content type item later
if (!_contentTypeStreamExists)
{
_cachedCompressionLevel = compressionLevel;
}
// Figure out whether the mapping matches a default entry, can be made into a new
// default entry, or has to be entered as an override entry.
bool foundMatchingDefault = false;
string extension = partUri.PartUriExtension;
// Need to create an override entry?
if (extension.Length == 0
|| (_defaultDictionary.ContainsKey(extension)
&& !(foundMatchingDefault =
_defaultDictionary[extension].AreTypeAndSubTypeEqual(contentType))))
{
AddOverrideElement(partUri, contentType);
}
// Else, either there is already a mapping from extension to contentType,
// or one needs to be created.
else if (!foundMatchingDefault)
{
AddDefaultElement(extension, contentType);
}
}
//Returns the content type for the part, if present, else returns null.
internal ContentType GetContentType(PackUriHelper.ValidatedPartUri partUri)
{
//Step 1: Check if there is an override entry present corresponding to the
//partUri provided. Override takes precedence over the default entries
if (_overrideDictionary != null)
{
if (_overrideDictionary.ContainsKey(partUri))
return _overrideDictionary[partUri];
}
//Step 2: Check if there is a default entry corresponding to the
//extension of the partUri provided.
string extension = partUri.PartUriExtension;
if (_defaultDictionary.ContainsKey(extension))
return _defaultDictionary[extension];
//Step 3: If we did not find an entry in the override and the default
//dictionaries, this is an error condition
return null;
}
//Deletes the override entry corresponding to the partUri, if it exists
internal void DeleteContentType(PackUriHelper.ValidatedPartUri partUri)
{
if (_overrideDictionary != null)
{
if (_overrideDictionary.Remove(partUri))
_dirty = true;
}
}
internal void SaveToFile()
{
if (_dirty)
{
//Lazy init: Initialize when the first part is added.
if (!_contentTypeStreamExists)
{
_contentTypeZipArchiveEntry = _zipArchive.CreateEntry(s_contentTypesFile, _cachedCompressionLevel);
_contentTypeStreamExists = true;
}
// delete and re-create entry for content part. When writing this, the stream will not truncate the content
// if the XML is shorter than the existing content part.
var contentTypefullName = _contentTypeZipArchiveEntry.FullName;
var thisArchive = _contentTypeZipArchiveEntry.Archive;
_zipStreamManager.Close(_contentTypeZipArchiveEntry);
_contentTypeZipArchiveEntry.Delete();
_contentTypeZipArchiveEntry = thisArchive.CreateEntry(contentTypefullName);
using (Stream s = _zipStreamManager.Open(_contentTypeZipArchiveEntry, _packageFileMode, FileAccess.ReadWrite))
{
// use UTF-8 encoding by default
using (XmlWriter writer = XmlWriter.Create(s, new XmlWriterSettings { Encoding = System.Text.Encoding.UTF8 }))
{
writer.WriteStartDocument();
// write root element tag - Types
writer.WriteStartElement(s_typesTagName, s_typesNamespaceUri);
// for each default entry
foreach (string key in _defaultDictionary.Keys)
{
WriteDefaultElement(writer, key, _defaultDictionary[key]);
}
if (_overrideDictionary != null)
{
// for each override entry
foreach (PackUriHelper.ValidatedPartUri key in _overrideDictionary.Keys)
{
WriteOverrideElement(writer, key, _overrideDictionary[key]);
}
}
// end of Types tag
writer.WriteEndElement();
// close the document
writer.WriteEndDocument();
_dirty = false;
}
}
}
}
#endregion Internal Methods
#region Private Methods
private void EnsureOverrideDictionary()
{
// The part Uris are stored in the Override Dictionary in their original form , but they are compared
// in a normalized manner using the PartUriComparer
if (_overrideDictionary == null)
_overrideDictionary = new Dictionary<PackUriHelper.ValidatedPartUri, ContentType>(s_overrideDictionaryInitialSize);
}
private void ParseContentTypesFile(System.Collections.ObjectModel.ReadOnlyCollection<ZipArchiveEntry> zipFiles)
{
// Find the content type stream, allowing for interleaving. Naming collisions
// (as between an atomic and an interleaved part) will result in an exception being thrown.
Stream s = OpenContentTypeStream(zipFiles);
// Allow non-existent content type stream.
if (s == null)
return;
XmlReaderSettings xrs = new XmlReaderSettings();
xrs.IgnoreWhitespace = true;
using (s)
using (XmlReader reader = XmlReader.Create(s, xrs))
{
//This method expects the reader to be in ReadState.Initial.
//It will make the first read call.
PackagingUtilities.PerformInitialReadAndVerifyEncoding(reader);
//Note: After the previous method call the reader should be at the first tag in the markup.
//MoveToContent - Skips over the following - ProcessingInstruction, DocumentType, Comment, Whitespace, or SignificantWhitespace
//If the reader is currently at a content node then this function call is a no-op
reader.MoveToContent();
// look for our root tag and namespace pair - ignore others in case of version changes
// Make sure that the current node read is an Element
if ((reader.NodeType == XmlNodeType.Element)
&& (reader.Depth == 0)
&& (String.CompareOrdinal(reader.NamespaceURI, s_typesNamespaceUri) == 0)
&& (String.CompareOrdinal(reader.Name, s_typesTagName) == 0))
{
//There should be a namespace Attribute present at this level.
//Also any other attribute on the <Types> tag is an error including xml: and xsi: attributes
if (PackagingUtilities.GetNonXmlnsAttributeCount(reader) > 0)
{
throw new XmlException(SR.TypesTagHasExtraAttributes, null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
// start tag encountered
// now parse individual Default and Override tags
while (reader.Read())
{
//Skips over the following - ProcessingInstruction, DocumentType, Comment, Whitespace, or SignificantWhitespace
//If the reader is currently at a content node then this function call is a no-op
reader.MoveToContent();
//If MoveToContent() takes us to the end of the content
if (reader.NodeType == XmlNodeType.None)
continue;
// Make sure that the current node read is an element
// Currently we expect the Default and Override Tag at Depth 1
if (reader.NodeType == XmlNodeType.Element
&& reader.Depth == 1
&& (String.CompareOrdinal(reader.NamespaceURI, s_typesNamespaceUri) == 0)
&& (String.CompareOrdinal(reader.Name, s_defaultTagName) == 0))
{
ProcessDefaultTagAttributes(reader);
}
else
if (reader.NodeType == XmlNodeType.Element
&& reader.Depth == 1
&& (String.CompareOrdinal(reader.NamespaceURI, s_typesNamespaceUri) == 0)
&& (String.CompareOrdinal(reader.Name, s_overrideTagName) == 0))
{
ProcessOverrideTagAttributes(reader);
}
else
if (reader.NodeType == XmlNodeType.EndElement && reader.Depth == 0 && String.CompareOrdinal(reader.Name, s_typesTagName) == 0)
continue;
else
{
throw new XmlException(SR.TypesXmlDoesNotMatchSchema, null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
}
}
else
{
throw new XmlException(SR.TypesElementExpected, null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
}
}
/// <summary>
/// Find the content type stream, allowing for interleaving. Naming collisions
/// (as between an atomic and an interleaved part) will result in an exception being thrown.
/// Return null if no content type stream has been found.
/// </summary>
/// <remarks>
/// The input array is lexicographically sorted
/// </remarks>
private Stream OpenContentTypeStream(System.Collections.ObjectModel.ReadOnlyCollection<ZipArchiveEntry> zipFiles)
{
foreach (ZipArchiveEntry zipFileInfo in zipFiles)
{
if (zipFileInfo.Name.ToUpperInvariant().StartsWith(s_contentTypesFileUpperInvariant, StringComparison.Ordinal))
{
// Atomic name.
if (zipFileInfo.Name.Length == ContentTypeFileName.Length)
{
// Record the file info.
_contentTypeZipArchiveEntry = zipFileInfo;
}
}
}
// If an atomic file was found, open a stream on it.
if (_contentTypeZipArchiveEntry != null)
{
_contentTypeStreamExists = true;
return _zipStreamManager.Open(_contentTypeZipArchiveEntry, _packageFileMode, FileAccess.ReadWrite);
}
// No content type stream was found.
return null;
}
// Process the attributes for the Default tag
private void ProcessDefaultTagAttributes(XmlReader reader)
{
#region Default Tag
//There could be a namespace Attribute present at this level.
//Also any other attribute on the <Default> tag is an error including xml: and xsi: attributes
if (PackagingUtilities.GetNonXmlnsAttributeCount(reader) != 2)
throw new XmlException(SR.DefaultTagDoesNotMatchSchema, null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
// get the required Extension and ContentType attributes
string extensionAttributeValue = reader.GetAttribute(s_extensionAttributeName);
ValidateXmlAttribute(s_extensionAttributeName, extensionAttributeValue, s_defaultTagName, reader);
string contentTypeAttributeValue = reader.GetAttribute(s_contentTypeAttributeName);
ThrowIfXmlAttributeMissing(s_contentTypeAttributeName, contentTypeAttributeValue, s_defaultTagName, reader);
// The extensions are stored in the Default Dictionary in their original form , but they are compared
// in a normalized manner using the ExtensionComparer.
PackUriHelper.ValidatedPartUri temporaryUri = PackUriHelper.ValidatePartUri(
new Uri(s_temporaryPartNameWithoutExtension + extensionAttributeValue, UriKind.Relative));
_defaultDictionary.Add(temporaryUri.PartUriExtension, new ContentType(contentTypeAttributeValue));
//Skip the EndElement for Default Tag
if (!reader.IsEmptyElement)
ProcessEndElement(reader, s_defaultTagName);
#endregion Default Tag
}
// Process the attributes for the Default tag
private void ProcessOverrideTagAttributes(XmlReader reader)
{
#region Override Tag
//There could be a namespace Attribute present at this level.
//Also any other attribute on the <Override> tag is an error including xml: and xsi: attributes
if (PackagingUtilities.GetNonXmlnsAttributeCount(reader) != 2)
throw new XmlException(SR.OverrideTagDoesNotMatchSchema, null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
// get the required Extension and ContentType attributes
string partNameAttributeValue = reader.GetAttribute(s_partNameAttributeName);
ValidateXmlAttribute(s_partNameAttributeName, partNameAttributeValue, s_overrideTagName, reader);
string contentTypeAttributeValue = reader.GetAttribute(s_contentTypeAttributeName);
ThrowIfXmlAttributeMissing(s_contentTypeAttributeName, contentTypeAttributeValue, s_overrideTagName, reader);
PackUriHelper.ValidatedPartUri partUri = PackUriHelper.ValidatePartUri(new Uri(partNameAttributeValue, UriKind.Relative));
//Lazy initializing - ensure that the override dictionary has been initialized
EnsureOverrideDictionary();
// The part Uris are stored in the Override Dictionary in their original form , but they are compared
// in a normalized manner using PartUriComparer.
_overrideDictionary.Add(partUri, new ContentType(contentTypeAttributeValue));
//Skip the EndElement for Override Tag
if (!reader.IsEmptyElement)
ProcessEndElement(reader, s_overrideTagName);
#endregion Override Tag
}
//If End element is present for Relationship then we process it
private void ProcessEndElement(XmlReader reader, string elementName)
{
Debug.Assert(!reader.IsEmptyElement, "This method should only be called it the Relationship Element is not empty");
reader.Read();
//Skips over the following - ProcessingInstruction, DocumentType, Comment, Whitespace, or SignificantWhitespace
reader.MoveToContent();
if (reader.NodeType == XmlNodeType.EndElement && String.CompareOrdinal(elementName, reader.LocalName) == 0)
return;
else
throw new XmlException(SR.Format(SR.ElementIsNotEmptyElement, elementName), null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
private void AddOverrideElement(PackUriHelper.ValidatedPartUri partUri, ContentType contentType)
{
//Delete any entry corresponding in the Override dictionary
//corresponding to the PartUri for which the contentType is being added.
//This is to compensate for dead override entries in the content types file.
DeleteContentType(partUri);
//Lazy initializing - ensure that the override dictionary has been initialized
EnsureOverrideDictionary();
// The part Uris are stored in the Override Dictionary in their original form , but they are compared
// in a normalized manner using PartUriComparer.
_overrideDictionary.Add(partUri, contentType);
_dirty = true;
}
private void AddDefaultElement(string extension, ContentType contentType)
{
// The extensions are stored in the Default Dictionary in their original form , but they are compared
// in a normalized manner using the ExtensionComparer.
_defaultDictionary.Add(extension, contentType);
_dirty = true;
}
private void WriteOverrideElement(XmlWriter xmlWriter, PackUriHelper.ValidatedPartUri partUri, ContentType contentType)
{
xmlWriter.WriteStartElement(s_overrideTagName);
xmlWriter.WriteAttributeString(s_partNameAttributeName,
partUri.PartUriString);
xmlWriter.WriteAttributeString(s_contentTypeAttributeName, contentType.ToString());
xmlWriter.WriteEndElement();
}
private void WriteDefaultElement(XmlWriter xmlWriter, string extension, ContentType contentType)
{
xmlWriter.WriteStartElement(s_defaultTagName);
xmlWriter.WriteAttributeString(s_extensionAttributeName, extension);
xmlWriter.WriteAttributeString(s_contentTypeAttributeName, contentType.ToString());
xmlWriter.WriteEndElement();
}
//Validate if the required XML attribute is present and not an empty string
private void ValidateXmlAttribute(string attributeName, string attributeValue, string tagName, XmlReader reader)
{
ThrowIfXmlAttributeMissing(attributeName, attributeValue, tagName, reader);
//Checking for empty attribute
if (attributeValue == String.Empty)
throw new XmlException(SR.Format(SR.RequiredAttributeEmpty, tagName, attributeName), null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
//Validate if the required Content type XML attribute is present
//Content type of a part can be empty
private void ThrowIfXmlAttributeMissing(string attributeName, string attributeValue, string tagName, XmlReader reader)
{
if (attributeValue == null)
throw new XmlException(SR.Format(SR.RequiredAttributeMissing, tagName, attributeName), null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
#endregion Private Methods
#region Member Variables
private Dictionary<PackUriHelper.ValidatedPartUri, ContentType> _overrideDictionary;
private Dictionary<string, ContentType> _defaultDictionary;
private ZipArchive _zipArchive;
private FileMode _packageFileMode;
private FileAccess _packageFileAccess;
private ZipStreamManager _zipStreamManager;
private ZipArchiveEntry _contentTypeZipArchiveEntry;
private bool _contentTypeStreamExists;
private bool _dirty;
private CompressionLevel _cachedCompressionLevel;
private static readonly string s_contentTypesFile = "[Content_Types].xml";
private static readonly string s_contentTypesFileUpperInvariant = "[CONTENT_TYPES].XML";
private static readonly int s_defaultDictionaryInitialSize = 16;
private static readonly int s_overrideDictionaryInitialSize = 8;
//Xml tag specific strings for the Content Type file
private static readonly string s_typesNamespaceUri = "http://schemas.openxmlformats.org/package/2006/content-types";
private static readonly string s_typesTagName = "Types";
private static readonly string s_defaultTagName = "Default";
private static readonly string s_extensionAttributeName = "Extension";
private static readonly string s_contentTypeAttributeName = "ContentType";
private static readonly string s_overrideTagName = "Override";
private static readonly string s_partNameAttributeName = "PartName";
private static readonly string s_temporaryPartNameWithoutExtension = "/tempfiles/sample.";
#endregion Member Variables
}
#endregion ContentTypeHelper Class
#endregion Private Class
}
}
| |
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////namespace System
namespace System
{
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
[Serializable()]
[Clarity.ExportStub("System_Type.cpp")]
public abstract class Type : MemberInfo, IReflect
{
public extern override Type DeclaringType
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
}
public extern override Type ReflectedType
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
}
public static Type GetType(String typeName)
{
bool fVersion = false;
int[] ver = new int[4];
string assemblyString = String.Empty;
string assemblyName = "";
string name = ParseTypeName(typeName, ref assemblyString);
if (assemblyString.Length > 0)
{
assemblyName = Assembly.ParseAssemblyName( assemblyString, ref fVersion, ref ver );
}
return GetTypeInternal(name, assemblyName, fVersion, ver);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern Type GetTypeInternal(String typeName, string assemblyName, bool fVersion, int[] ver);
[Diagnostics.DebuggerStepThrough]
[Diagnostics.DebuggerHidden]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern Object InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args);
public abstract Assembly Assembly
{
get;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern static Type GetTypeFromHandle(RuntimeTypeHandle handle);
public abstract String FullName
{
get;
}
public abstract String AssemblyQualifiedName
{
get;
}
public abstract Type BaseType
{
get;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern ConstructorInfo GetConstructor(Type[] types);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern MethodInfo GetMethod(String name, Type[] types);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern MethodInfo GetMethod(String name, BindingFlags bindingAttr);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern MethodInfo GetMethod(String name);
// GetMethods
// This routine will return all the methods implemented by the class
public MethodInfo[] GetMethods()
{
return GetMethods(Type.DefaultLookup);
}
abstract public MethodInfo[] GetMethods(BindingFlags bindingAttr);
abstract public FieldInfo GetField(String name, BindingFlags bindingAttr);
public FieldInfo GetField(String name)
{
return GetField(name, Type.DefaultLookup);
}
public FieldInfo[] GetFields()
{
return GetFields(Type.DefaultLookup);
}
abstract public FieldInfo[] GetFields(BindingFlags bindingAttr);
// GetInterfaces
// This method will return all of the interfaces implemented by a
// class
abstract public Type[] GetInterfaces();
////////////////////////////////////////////////////////////////////////////////////
//////
////// Attributes
//////
////// The attributes are all treated as read-only properties on a class. Most of
////// these boolean properties have flag values defined in this class and act like
////// a bit mask of attributes. There are also a set of boolean properties that
////// relate to the classes relationship to other classes and to the state of the
////// class inside the runtime.
//////
////////////////////////////////////////////////////////////////////////////////////
public extern bool IsNotPublic
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
}
public extern bool IsPublic
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
}
public extern bool IsClass
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
}
public extern bool IsInterface
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
}
public extern bool IsValueType
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
}
public extern bool IsAbstract
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
}
public extern bool IsEnum
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
}
public extern bool IsSerializable
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
}
public extern bool IsArray
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
}
abstract public Type GetElementType();
public virtual bool IsSubclassOf(Type c)
{
Type p = this;
if (p == c)
return false;
while (p != null)
{
if (p == c)
return true;
p = p.BaseType;
}
return false;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern virtual bool IsInstanceOfType(Object o);
public override String ToString()
{
return this.FullName;
}
// private convenience data
private const BindingFlags DefaultLookup = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public;
//--//
private static string ParseTypeName(String typeName, ref String assemblyString)
{
// valid names are in the forms:
// 1) "Microsoft.SPOT.Hardware.Cpu.Pin" or
// 2) "Microsoft.SPOT.Hardware.Cpu.Pin, Microsoft.SPOT.Hardware" or
// 3) "Microsoft.SPOT.Hardware.Cpu.Pin, Microsoft.SPOT.Hardware, Version=1.2.3.4"
// 4) (FROM THE DEBUGGER) "Microsoft.SPOT.Hardware.Cpu.Pin, Microsoft.SPOT.Hardware, Version=1.2.3.4, Culture=neutral, PublicKeyToken=null[, ...]
int commaIdx;
string name;
// if there is no comma then we have an assembly name in the form with no version
if ((commaIdx = typeName.IndexOf(',')) != -1)
{
// we grab the type name, but we already know there is more
name = typeName.Substring(0, commaIdx);
// after the comma we need ONE (1) space only and then the assembly name
if(typeName.Length <= commaIdx + 2)
{
throw new ArgumentException();
}
// now we can grab the assemblyName
// at this point there could be also the Version appended to it
assemblyString = typeName.Substring(commaIdx + 2);
}
else
{
name = typeName;
assemblyString = "";
}
return name;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using TwitchBot.Utils;
namespace TwitchBot.Proxy
{
public class TwitchMessage
{
private const string UserMessageTypePrivateMsg = "PRIVMSG";
private const string UserMessageTypeJoinChannel = "JOIN";
private const string UserMessageTypeLeaveChannel = "PART";
private const string TwitchNotificationMessage = ":irc.twitch.tv";
private const string UserActionMessageRegexString = @"^(:)(.*?)(!)(.*?)(tmi.twitch.tv)\b";
private const string UserNameExtractionRegexString = @"(:)(.*?)(!)";
private const string PongMessageRegexString = @"^(PONG)(.*?)";
private const string ServerMessageRegexString = @"^(.tmi.twitch.tv)(.*?)";
private const string ServerUserMessageRegexString = @"^(:)(.*?)(.tmi.twitch.tv)(.*?)";
private const string NumberRegexString = @"^\d+$";
private static readonly Regex UserActionMessageRegex = new Regex(UserActionMessageRegexString);
private static readonly Regex UserNameExtractionRegex = new Regex(UserNameExtractionRegexString);
private static readonly Regex PongMessageRegex = new Regex(PongMessageRegexString);
private static readonly Regex ServerMessageRegex = new Regex(ServerMessageRegexString);
private static readonly Regex ServerUserMessageRegex = new Regex(ServerUserMessageRegexString);
private static readonly Regex IsNumberRegex = new Regex(NumberRegexString);
protected TwitchMessage()
{
}
public TwitchMessageType Type { get; private set; }
public string Message { get; set; }
public string Command { get; set; }
public string UserName { get; set; }
public string LongUserIdentifier { get; set; }
public string Channel { get; set; }
public string FullMessage { get; set; }
public int Code { get; set; }
public static TwitchMessage FromString(string message)
{
var resultMessage = new TwitchMessage();
var tokens = message.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
if (tokens.Length == 0)
{
resultMessage.Type = TwitchMessageType.Empty;
resultMessage.FullMessage = message;
return resultMessage;
}
if (UserActionMessageRegex.IsMatch(message) && tokens.Length >= 3)
{
resultMessage = ParseUserActionMessage(tokens, message);
return resultMessage;
}
if (PongMessageRegex.IsMatch(message))
{
resultMessage.Type = TwitchMessageType.PingPong;
resultMessage.FullMessage = message;
return resultMessage;
}
if (ServerMessageRegex.IsMatch(message))
{
resultMessage.FullMessage = message;
if (IsNumberRegex.IsMatch(tokens[1]))
{
resultMessage.Code = int.Parse(tokens[1]);
resultMessage.UserName = tokens[2];
resultMessage.Type = TwitchMessageType.ServerCodeMessage;
}
else
{
resultMessage.Code = -1;
resultMessage.Command = tokens[1];
resultMessage.Message = string.Join(" ", tokens.ToList().GetRange(2, tokens.Length - 2));
resultMessage.Type = TwitchMessageType.ServerCommandMessage;
}
return resultMessage;
}
if (ServerUserMessageRegex.IsMatch(message))
{
resultMessage.FullMessage = message;
resultMessage.UserName = tokens[2];
resultMessage.Code = int.Parse(tokens[1]);
resultMessage.Type = TwitchMessageType.ServerCodeMessage;
return resultMessage;
}
resultMessage.Type = TwitchMessageType.Uncategorized;
resultMessage.FullMessage = message;
return resultMessage;
}
private static TwitchMessage ParseUserActionMessage(string[] tokens, string message)
{
var resultMessage = new TwitchMessage {FullMessage = message};
switch (tokens[1])
{
case UserMessageTypePrivateMsg:
resultMessage.Type = TwitchMessageType.ChatMessage;
resultMessage.LongUserIdentifier = tokens[0];
resultMessage.UserName = GetUsernameFromLongIdentifier(tokens[0]);
resultMessage.Channel = tokens[2];
resultMessage.Message = message.Substring(message.IndexOf(tokens[2], StringComparison.InvariantCultureIgnoreCase) + tokens[2].Length + 2);
return resultMessage;
case UserMessageTypeJoinChannel:
resultMessage.Type = TwitchMessageType.JoinMessage;
resultMessage.LongUserIdentifier = tokens[0];
resultMessage.UserName = GetUsernameFromLongIdentifier(tokens[0]);
resultMessage.Channel = tokens[2];
return resultMessage;
case UserMessageTypeLeaveChannel:
resultMessage.Type = TwitchMessageType.PartMessage;
resultMessage.LongUserIdentifier = tokens[0];
resultMessage.UserName = GetUsernameFromLongIdentifier(tokens[0]);
resultMessage.Channel = tokens[2];
return resultMessage;
default:
resultMessage.Type = TwitchMessageType.UnknownUserMessage;
resultMessage.LongUserIdentifier = tokens[0];
resultMessage.UserName = GetUsernameFromLongIdentifier(tokens[0]);
resultMessage.Channel = tokens[2];
return resultMessage;
}
}
private static string GetUsernameFromLongIdentifier(string longIdentifier)
{
var match = UserNameExtractionRegex.Match(longIdentifier);
if (match.Success && match.Groups.Count > 0)
{
var usernameLong = match.Groups[0].Value;
var username = usernameLong.Substring(1, usernameLong.Length - 2);
return username;
}
return "@@NO_USER@@";
}
}
public static class MessageFactory
{
private static List<Type> MessageTypes { get; set; }
static MessageFactory()
{
MessageTypes = ReflectiveEnumerator.GetEnumerableOfType<Message>().ToList();
}
public static Message CreateMessageFromString(string strMessage)
{
var possibleResults = new List<Message>();
foreach (var messageType in MessageTypes)
{
var messageInstance = messageType.GetConstructor(null)?.Invoke(null) as Message;
if (messageInstance != null && messageInstance.RepresentsMessageType(strMessage))
{
messageInstance.ParseMessage(strMessage);
possibleResults.Add(messageInstance);
}
}
return possibleResults.FirstOrDefault();
}
}
public abstract class Message
{
public List<Token> Tokens { get; }
private const string GlobalSeparator = ":";
public string OriginalMessage { get; private set; }
protected Message()
{
Tokens = new List<Token>();
}
public void ParseMessage(string message)
{
OriginalMessage = message;
var sTokens = message.Split(new[] { GlobalSeparator }, StringSplitOptions.None);
var index = 0;
foreach (var sToken in sTokens)
{
Tokens.Add(CreateToken(sToken, index++));
}
}
public abstract bool RepresentsMessageType(string message);
protected abstract Token CreateToken(string token, int index);
public override string ToString()
{
return string.Join(GlobalSeparator, Tokens.Select(item => item.ToString()));
}
}
public abstract class Token
{
public List<IDataItem> DataItems { get; }
public int Index { get; }
public string OriginalToken { get; }
protected abstract string Separator { get; }
public Message ParentMessage { get; }
protected Token(Message parrentMessage, string token, int index)
{
DataItems = new List<IDataItem>();
ParentMessage = parrentMessage;
Index = index;
OriginalToken = token;
Initialize();
}
protected void Initialize()
{
if (Separator == null)
{
var dataItem = CreateDataItem(OriginalToken, 0);
DataItems.Add(dataItem);
return;
}
var items = OriginalToken.Split(new [] {Separator}, StringSplitOptions.RemoveEmptyEntries);
var index = 0;
foreach (var item in items)
{
var dataItem = CreateDataItem(item, index++);
DataItems.Add(dataItem);
}
}
protected abstract IDataItem CreateDataItem(string item, int index);
public override string ToString()
{
return string.Join(Separator, DataItems.Select(item => item.ToString()));
}
}
public interface IDataItem
{
string Value { get; }
string Key { get; }
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="TangoInspector.cs" company="Google">
//
// Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// </copyright>
//-----------------------------------------------------------------------
using System.Collections;
using Tango;
using UnityEditor;
using UnityEngine;
/// <summary>
/// Custom editor for the TangoApplication.
/// </summary>
[CustomEditor(typeof(TangoApplication))]
public class TangoInspector : Editor
{
private TangoApplication m_tangoApplication;
/// <summary>
/// Raises the inspector GUI event.
/// </summary>
public override void OnInspectorGUI()
{
m_tangoApplication.m_autoConnectToService = EditorGUILayout.Toggle("Auto-connect to Service",
m_tangoApplication.m_autoConnectToService);
if (m_tangoApplication.m_autoConnectToService && m_tangoApplication.m_enableAreaDescriptions &&
!m_tangoApplication.m_enableDriftCorrection)
{
EditorGUILayout.HelpBox("Note that auto-connect does not supply a chance "
+ "to specify an Area Description.", MessageType.Warning);
}
EditorGUILayout.Space();
_DrawMotionTrackingOptions(m_tangoApplication);
_DrawAreaDescriptionOptions(m_tangoApplication);
_DrawDepthOptions(m_tangoApplication);
_DrawVideoOverlayOptions(m_tangoApplication);
_Draw3DReconstructionOptions(m_tangoApplication);
_DrawPerformanceOptions(m_tangoApplication);
_DrawEmulationOptions(m_tangoApplication);
_DrawDevelopmentOptions(m_tangoApplication);
if (GUI.changed)
{
EditorUtility.SetDirty(m_tangoApplication);
}
}
/// <summary>
/// Raises the enable event.
/// </summary>
private void OnEnable()
{
m_tangoApplication = (TangoApplication)target;
// Fixup the old state of TangoApplication before there were two checkboxes. If only m_enableVideoOverlay was
// set, then that meant to use the Byte Buffer method.
if (m_tangoApplication.m_enableVideoOverlay && !m_tangoApplication.m_videoOverlayUseTextureMethod
&& !m_tangoApplication.m_videoOverlayUseYUVTextureIdMethod
&& !m_tangoApplication.m_videoOverlayUseByteBufferMethod)
{
m_tangoApplication.m_videoOverlayUseByteBufferMethod = true;
}
}
/// <summary>
/// Draw motion tracking options.
/// </summary>
/// <param name="tangoApplication">Tango application.</param>
private void _DrawMotionTrackingOptions(TangoApplication tangoApplication)
{
tangoApplication.m_enableMotionTracking = EditorGUILayout.Toggle(
"Enable Motion Tracking", tangoApplication.m_enableMotionTracking);
if (tangoApplication.m_enableMotionTracking)
{
++EditorGUI.indentLevel;
tangoApplication.m_motionTrackingAutoReset = EditorGUILayout.Toggle(
"Auto Reset", tangoApplication.m_motionTrackingAutoReset);
--EditorGUI.indentLevel;
}
EditorGUILayout.Space();
}
/// <summary>
/// Draw area description options.
/// </summary>
/// <param name="tangoApplication">Tango application.</param>
private void _DrawAreaDescriptionOptions(TangoApplication tangoApplication)
{
string[] options = new string[]
{
"Motion Tracking",
"Motion Tracking (with Drift Correction)",
"Local Area Description (Load Existing)",
"Local Area Description (Learning)",
"Cloud Area Description"
};
int selectedOption = 0;
if (tangoApplication.m_enableDriftCorrection)
{
selectedOption = 1;
}
else if (tangoApplication.m_enableAreaDescriptions)
{
if (tangoApplication.m_areaDescriptionLearningMode)
{
selectedOption = 3;
}
else if (tangoApplication.m_enableCloudADF)
{
selectedOption = 4;
}
else
{
selectedOption = 2;
}
}
switch (EditorGUILayout.Popup("Pose Mode", selectedOption, options))
{
case 1: // motion tracking with drift correction
tangoApplication.m_enableDriftCorrection = true;
tangoApplication.m_enableAreaDescriptions = false;
tangoApplication.m_areaDescriptionLearningMode = false;
tangoApplication.m_enableCloudADF = false;
break;
case 2: // area learning, load existing local
tangoApplication.m_enableDriftCorrection = false;
tangoApplication.m_enableAreaDescriptions = true;
tangoApplication.m_areaDescriptionLearningMode = false;
tangoApplication.m_enableCloudADF = false;
break;
case 3: // area learning, local learning mode
tangoApplication.m_enableDriftCorrection = false;
tangoApplication.m_enableAreaDescriptions = true;
tangoApplication.m_areaDescriptionLearningMode = true;
tangoApplication.m_enableCloudADF = false;
break;
case 4: // area learning, cloud mode
tangoApplication.m_enableDriftCorrection = false;
tangoApplication.m_enableAreaDescriptions = true;
tangoApplication.m_areaDescriptionLearningMode = false;
tangoApplication.m_enableCloudADF = true;
break;
default: // case 0, motion tracking
tangoApplication.m_enableDriftCorrection = false;
tangoApplication.m_enableAreaDescriptions = false;
tangoApplication.m_areaDescriptionLearningMode = false;
tangoApplication.m_enableCloudADF = false;
break;
}
if (m_tangoApplication.m_enableDriftCorrection)
{
EditorGUILayout.HelpBox("Drift correction mode is experimental.", MessageType.Warning);
}
if (m_tangoApplication.m_enableCloudADF)
{
EditorGUILayout.HelpBox("Cloud Area Descriptions is experimental.", MessageType.Warning);
}
EditorGUILayout.Space();
}
/// <summary>
/// Draw depth options.
/// </summary>
/// <param name="tangoApplication">Tango application.</param>
private void _DrawDepthOptions(TangoApplication tangoApplication)
{
tangoApplication.m_enableDepth = EditorGUILayout.Toggle("Enable Depth", tangoApplication.m_enableDepth);
EditorGUILayout.Space();
}
/// <summary>
/// Draw video overlay options.
/// </summary>
/// <param name="tangoApplication">Tango application.</param>
private void _DrawVideoOverlayOptions(TangoApplication tangoApplication)
{
tangoApplication.m_enableVideoOverlay = EditorGUILayout.Toggle(
"Enable Video Overlay", tangoApplication.m_enableVideoOverlay);
if (tangoApplication.m_enableVideoOverlay)
{
EditorGUI.indentLevel++;
string[] options = new string[]
{
"Texture (ITangoCameraTexture)",
"YUV Texture (IExperimentalTangoVideoOverlay)",
"Raw Bytes (ITangoVideoOverlay)",
"Texture and Raw Bytes",
"YUV Texture and Raw Bytes",
"Texture and YUV Texture",
"All",
};
int selectedOption;
if (tangoApplication.m_videoOverlayUseTextureMethod
&& tangoApplication.m_videoOverlayUseYUVTextureIdMethod
&& tangoApplication.m_videoOverlayUseByteBufferMethod)
{
selectedOption = 6;
}
else if (tangoApplication.m_videoOverlayUseTextureMethod
&& tangoApplication.m_videoOverlayUseYUVTextureIdMethod)
{
selectedOption = 5;
}
else if (tangoApplication.m_videoOverlayUseYUVTextureIdMethod
&& tangoApplication.m_videoOverlayUseByteBufferMethod)
{
selectedOption = 4;
}
else if (tangoApplication.m_videoOverlayUseTextureMethod
&& tangoApplication.m_videoOverlayUseByteBufferMethod)
{
selectedOption = 3;
}
else if (tangoApplication.m_videoOverlayUseByteBufferMethod)
{
selectedOption = 2;
}
else if (tangoApplication.m_videoOverlayUseYUVTextureIdMethod)
{
selectedOption = 1;
}
else
{
selectedOption = 0;
}
switch (EditorGUILayout.Popup("Method", selectedOption, options))
{
case 0:
tangoApplication.m_videoOverlayUseTextureMethod = true;
tangoApplication.m_videoOverlayUseYUVTextureIdMethod = false;
tangoApplication.m_videoOverlayUseByteBufferMethod = false;
break;
case 1:
tangoApplication.m_videoOverlayUseTextureMethod = false;
tangoApplication.m_videoOverlayUseYUVTextureIdMethod = true;
tangoApplication.m_videoOverlayUseByteBufferMethod = false;
break;
case 2:
tangoApplication.m_videoOverlayUseTextureMethod = false;
tangoApplication.m_videoOverlayUseYUVTextureIdMethod = false;
tangoApplication.m_videoOverlayUseByteBufferMethod = true;
break;
case 3:
tangoApplication.m_videoOverlayUseTextureMethod = true;
tangoApplication.m_videoOverlayUseYUVTextureIdMethod = false;
tangoApplication.m_videoOverlayUseByteBufferMethod = true;
break;
case 4:
tangoApplication.m_videoOverlayUseTextureMethod = false;
tangoApplication.m_videoOverlayUseYUVTextureIdMethod = true;
tangoApplication.m_videoOverlayUseByteBufferMethod = true;
break;
case 5:
tangoApplication.m_videoOverlayUseTextureMethod = true;
tangoApplication.m_videoOverlayUseYUVTextureIdMethod = true;
tangoApplication.m_videoOverlayUseByteBufferMethod = false;
break;
case 6:
tangoApplication.m_videoOverlayUseTextureMethod = true;
tangoApplication.m_videoOverlayUseYUVTextureIdMethod = true;
tangoApplication.m_videoOverlayUseByteBufferMethod = true;
break;
default:
tangoApplication.m_videoOverlayUseTextureMethod = true;
tangoApplication.m_videoOverlayUseYUVTextureIdMethod = false;
tangoApplication.m_videoOverlayUseByteBufferMethod = false;
break;
}
EditorGUI.indentLevel--;
}
else
{
tangoApplication.m_videoOverlayUseTextureMethod = true;
tangoApplication.m_videoOverlayUseYUVTextureIdMethod = false;
tangoApplication.m_videoOverlayUseByteBufferMethod = false;
}
EditorGUILayout.Space();
}
/// <summary>
/// Draw motion tracking options.
/// </summary>
/// <param name="tangoApplication">Tango application.</param>
private void _Draw3DReconstructionOptions(TangoApplication tangoApplication)
{
GUILayout.Label("Enable 3D Reconstruction", GUILayout.ExpandWidth(true));
tangoApplication.m_enable3DReconstruction = EditorGUILayout.Toggle("(Experimental)",
tangoApplication.m_enable3DReconstruction);
if (tangoApplication.m_enable3DReconstruction)
{
if (!tangoApplication.m_enableMotionTracking)
{
EditorGUILayout.HelpBox("Motion tracking is required for 3D Reconstruction.", MessageType.Warning);
}
if (!tangoApplication.m_enableDepth)
{
EditorGUILayout.HelpBox("Depth is required for 3D Reconstruction.", MessageType.Warning);
}
EditorGUI.indentLevel++;
tangoApplication.m_3drResolutionMeters = EditorGUILayout.FloatField(
"Resolution (meters)", tangoApplication.m_3drResolutionMeters);
tangoApplication.m_3drResolutionMeters = Mathf.Max(tangoApplication.m_3drResolutionMeters, 0.001f);
tangoApplication.m_3drGenerateColor = EditorGUILayout.Toggle(
"Generate Color", tangoApplication.m_3drGenerateColor);
if (tangoApplication.m_3drGenerateColor
&& (!tangoApplication.m_enableVideoOverlay || !tangoApplication.m_videoOverlayUseByteBufferMethod))
{
EditorGUILayout.HelpBox("To use 3D reconstruction with color, you must enable Video Overlay and"
+ " set it to \"Raw Bytes\", \"Texture and Raw Bytes\", or "
+ " \"YUV Texture and Raw Bytes\".", MessageType.Warning);
}
tangoApplication.m_3drGenerateNormal = EditorGUILayout.Toggle(
"Generate Normals", tangoApplication.m_3drGenerateNormal);
tangoApplication.m_3drGenerateTexCoord = EditorGUILayout.Toggle(
"Generate UVs", tangoApplication.m_3drGenerateTexCoord);
tangoApplication.m_3drSpaceClearing = EditorGUILayout.Toggle(
"Space Clearing", tangoApplication.m_3drSpaceClearing);
tangoApplication.m_3drUpdateMethod = (Tango3DReconstruction.UpdateMethod)EditorGUILayout.EnumPopup(
"Update Method", tangoApplication.m_3drUpdateMethod);
string tooltip = "If non-zero, any mesh that has less than this number of vertices is assumed to be "
+ "noise and will not be generated.";
int newMinNumVertices = EditorGUILayout.IntField(new GUIContent("Mesh Min Vertices", tooltip),
tangoApplication.m_3drMinNumVertices);
tangoApplication.m_3drMinNumVertices = Mathf.Max(newMinNumVertices, 0);
tangoApplication.m_3drUseAreaDescriptionPose = EditorGUILayout.Toggle(
"Use Area Description Pose", tangoApplication.m_3drUseAreaDescriptionPose);
if (tangoApplication.m_3drUseAreaDescriptionPose && !tangoApplication.m_enableAreaDescriptions)
{
EditorGUILayout.HelpBox("Area Descriptions must be enabled in order for "
+ "3D Reconstruction to use them.", MessageType.Warning);
}
else if (!tangoApplication.m_3drUseAreaDescriptionPose && tangoApplication.m_enableAreaDescriptions)
{
EditorGUILayout.HelpBox("Area Descriptions are enabled, but \"Use Area Description Pose\" is disabled "
+ "for 3D Reconstruction.\n\nIf left as-is, 3D Reconstruction will use the Start of "
+ "Service pose, even if an area description is loaded and/or area learning is enabled.",
MessageType.Warning);
}
EditorGUI.indentLevel--;
}
EditorGUILayout.Space();
}
/// <summary>
/// Draws options for performance management.
/// </summary>
/// <param name="tangoApplication">Tango application.</param>
private void _DrawPerformanceOptions(TangoApplication tangoApplication)
{
tangoApplication.m_showPerformanceOptionsInInspector =
EditorGUILayout.Foldout(tangoApplication.m_showPerformanceOptionsInInspector, "Performance Options");
if (tangoApplication.m_showPerformanceOptionsInInspector)
{
EditorGUI.indentLevel++;
m_tangoApplication.m_initialPointCloudMaxPoints = EditorGUILayout.IntField(
new GUIContent("Point Cloud Max Points",
"Set an upper limit on the number of points in the point cloud. If value is 0, no limit is imposed."),
m_tangoApplication.m_initialPointCloudMaxPoints);
tangoApplication.m_keepScreenAwake = EditorGUILayout.Toggle("Keep Screen Awake", tangoApplication.m_keepScreenAwake);
tangoApplication.m_adjustScreenResolution = EditorGUILayout.Toggle(
new GUIContent("Reduce Resolution",
"Whether to adjust the size of the application's main render buffer for performance reasons"),
tangoApplication.m_adjustScreenResolution);
EditorGUI.indentLevel++;
GUI.enabled = tangoApplication.m_adjustScreenResolution;
tangoApplication.m_targetResolution = EditorGUILayout.IntField(
new GUIContent("Target Resolution",
"Target resolution to reduce resolution to when m_adjustScreenResolution is enabled."),
tangoApplication.m_targetResolution);
string oversizedResolutionTooltip = "If true, resolution adjustment will allow adjusting to a resolution " +
"larger than the display of the current device. This is generally discouraged.";
tangoApplication.m_allowOversizedScreenResolutions = EditorGUILayout.Toggle(
new GUIContent("Allow Oversized", oversizedResolutionTooltip), tangoApplication.m_allowOversizedScreenResolutions);
GUI.enabled = true;
if (!tangoApplication.m_adjustScreenResolution)
{
EditorGUILayout.HelpBox("Some Tango devices have very high-resolution displays.\n\n" +
"Consider limiting application resolution here or elsewhere in your application.", MessageType.Warning);
}
EditorGUI.indentLevel--;
EditorGUI.indentLevel--;
}
}
/// <summary>
/// Draws development options.
///
/// These should only be set while in development.
/// </summary>
/// <param name="tangoApplication">Tango application.</param>
private void _DrawDevelopmentOptions(TangoApplication tangoApplication)
{
GUILayout.Label("Development Options (Disable these before publishing)", GUILayout.ExpandWidth(true));
EditorGUI.indentLevel++;
tangoApplication.m_allowOutOfDateTangoAPI = EditorGUILayout.Toggle(
"Allow out of date API", m_tangoApplication.m_allowOutOfDateTangoAPI);
EditorGUI.indentLevel--;
EditorGUILayout.Space();
}
/// <summary>
/// Draws editor emulation options.
///
/// These will only have any effect while in the Unity Editor.
/// </summary>
/// <param name="tangoApplication">Tango application.</param>
private void _DrawEmulationOptions(TangoApplication tangoApplication)
{
tangoApplication.m_showEmulationOptionsInInspector =
EditorGUILayout.Foldout(tangoApplication.m_showEmulationOptionsInInspector, "Editor Emulation");
if (tangoApplication.m_showEmulationOptionsInInspector)
{
EditorGUI.indentLevel++;
tangoApplication.m_doSlowEmulation = EditorGUILayout.Toggle(
new GUIContent("Depth and Video",
"Simulate depth and color camera data based on a specified mesh. Disable for editor performance."),
tangoApplication.m_doSlowEmulation);
if (tangoApplication.m_doSlowEmulation)
{
EditorGUI.indentLevel++;
tangoApplication.m_emulationEnvironment = (Mesh)EditorGUILayout.ObjectField(
new GUIContent("Mesh For Emulation", "Mesh to use as the world when simulating color camera and depth data."),
m_tangoApplication.m_emulationEnvironment, typeof(Mesh), false);
tangoApplication.m_emulationEnvironmentTexture = (Texture)EditorGUILayout.ObjectField(
new GUIContent("Texture for Emulation", "(Optional) Texture to use on emulated environment mesh."),
m_tangoApplication.m_emulationEnvironmentTexture, typeof(Texture), false);
m_tangoApplication.m_emulationVideoOverlaySimpleLighting = EditorGUILayout.Toggle(
new GUIContent("Simulate Lighting", "Use simple lighting in simulating camera feed"),
m_tangoApplication.m_emulationVideoOverlaySimpleLighting);
EditorGUI.indentLevel--;
EditorGUILayout.Space();
}
tangoApplication.m_emulatedAreaDescriptionStartOffset = EditorGUILayout.Vector3Field(
new GUIContent("Area Description Offset",
"Simulate difference between Start of Service and Area Description origins with a simple positional offset"),
tangoApplication.m_emulatedAreaDescriptionStartOffset);
EditorGUI.indentLevel--;
}
}
}
| |
//
// ListView_Rendering.cs
//
// Author:
// Aaron Bockover <[email protected]>
//
// Copyright (C) 2007-2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using Gtk;
using Gdk;
using Hyena.Gui;
using Hyena.Gui.Theming;
using Hyena.Gui.Canvas;
using GtkColorClass=Hyena.Gui.Theming.GtkColorClass;
namespace Hyena.Data.Gui
{
public delegate int ListViewRowHeightHandler (Widget widget);
public partial class ListView<T> : ListViewBase
{
private Cairo.Context cairo_context;
private CellContext cell_context;
private Pango.Layout pango_layout;
public override Pango.Layout PangoLayout {
get {
if (pango_layout == null && GdkWindow != null && IsRealized) {
using (var cr = Gdk.CairoHelper.Create (GdkWindow)) {
pango_layout = CairoExtensions.CreateLayout (this, cr);
cell_context.FontDescription = pango_layout.FontDescription;
cell_context.Layout = pango_layout;
}
}
return pango_layout;
}
}
public override Pango.FontDescription FontDescription {
get { return cell_context.FontDescription; }
}
private List<int> selected_rows = new List<int> ();
private Theme theme;
protected Theme Theme {
get { return theme; }
}
// Using an auto-property here makes the build fail with mono 1.9.1 (bnc#396633)
private bool do_not_render_null_model;
public bool DoNotRenderNullModel {
get { return do_not_render_null_model; }
set { do_not_render_null_model = value; }
}
private bool changing_style = false;
protected override void OnStyleSet (Style old_style)
{
if (changing_style) {
return;
}
changing_style = true;
GtkUtilities.AdaptGtkRcStyle (this, typeof (TreeView));
changing_style = false;
base.OnStyleSet (old_style);
// FIXME: legacy list foo
if (ViewLayout == null) {
OnInvalidateMeasure ();
}
theme = Hyena.Gui.Theming.ThemeEngine.CreateTheme (this);
// Save the drawable so we can reuse it
Gdk.Drawable drawable = cell_context != null ? cell_context.Drawable : null;
if (pango_layout != null) {
cell_context.FontDescription.Dispose ();
pango_layout.Dispose ();
pango_layout = null;
cell_context.Layout = null;
cell_context.FontDescription = null;
}
cell_context = new CellContext ();
cell_context.Theme = theme;
cell_context.Widget = this;
cell_context.Drawable = drawable;
SetDirection ();
}
private void SetDirection ()
{
var dir = Direction;
if (dir == Gtk.TextDirection.None) {
dir = Gtk.Widget.DefaultDirection;
}
if (cell_context != null) {
cell_context.IsRtl = dir == Gtk.TextDirection.Rtl;
}
}
protected override bool OnExposeEvent (EventExpose evnt)
{
if (DoNotRenderNullModel && Model == null) {
return true;
}
var damage = new Rectangle ();
foreach (Rectangle rect in evnt.Region.GetRectangles ()) {
damage = damage.Union (rect);
}
cairo_context = CairoHelper.Create (evnt.Window);
cell_context.Layout = PangoLayout;
cell_context.Context = cairo_context;
// FIXME: legacy list foo
if (ViewLayout == null) {
OnMeasure ();
}
Theme.DrawFrameBackground (cairo_context, Allocation, true);
// FIXME: ViewLayout will never be null in the future but we'll need
// to deterministically render a header somehow...
if (header_visible && ViewLayout == null && column_controller != null) {
PaintHeader (damage);
}
if (Model != null) {
// FIXME: ViewLayout will never be null in
// the future, PaintList will go away
if (ViewLayout == null) {
PaintList (damage);
} else {
PaintView ((Rect)damage);
}
}
Theme.DrawFrameBorder (cairo_context, Allocation);
PaintDraggingColumn (damage);
CairoExtensions.DisposeContext (cairo_context);
return true;
}
#region Header Rendering
private void PaintHeader (Rectangle clip)
{
Rectangle rect = header_rendering_alloc;
rect.Height += Theme.BorderWidth;
clip.Intersect (rect);
cairo_context.Rectangle (clip.X, clip.Y, clip.Width, clip.Height);
cairo_context.Clip ();
Theme.DrawHeaderBackground (cairo_context, header_rendering_alloc);
Rectangle cell_area = new Rectangle ();
cell_area.Y = header_rendering_alloc.Y;
cell_area.Height = header_rendering_alloc.Height;
cell_context.Clip = clip;
cell_context.Opaque = true;
cell_context.TextAsForeground = true;
bool have_drawn_separator = false;
for (int ci = 0; ci < column_cache.Length; ci++) {
if (pressed_column_is_dragging && pressed_column_index == ci) {
continue;
}
cell_area.X = column_cache[ci].X1 + Theme.TotalBorderWidth + header_rendering_alloc.X - HadjustmentValue;
cell_area.Width = column_cache[ci].Width;
PaintHeaderCell (cell_area, ci, false, ref have_drawn_separator);
}
if (pressed_column_is_dragging && pressed_column_index >= 0) {
cell_area.X = pressed_column_x_drag + Allocation.X - HadjustmentValue;
cell_area.Width = column_cache[pressed_column_index].Width;
PaintHeaderCell (cell_area, pressed_column_index, true, ref have_drawn_separator);
}
cairo_context.ResetClip ();
}
private void PaintHeaderCell (Rectangle area, int ci, bool dragging, ref bool have_drawn_separator)
{
if (ci < 0 || column_cache.Length <= ci)
return;
if (ci == ActiveColumn && HasFocus && HeaderFocused) {
Theme.DrawColumnHeaderFocus (cairo_context, area);
}
if (dragging) {
Theme.DrawColumnHighlight (cairo_context, area,
CairoExtensions.ColorShade (Theme.Colors.GetWidgetColor (GtkColorClass.Dark, StateType.Normal), 0.9));
Cairo.Color stroke_color = CairoExtensions.ColorShade (Theme.Colors.GetWidgetColor (
GtkColorClass.Base, StateType.Normal), 0.0);
stroke_color.A = 0.3;
cairo_context.SetSourceColor (stroke_color);
cairo_context.MoveTo (area.X + 0.5, area.Y + 1.0);
cairo_context.LineTo (area.X + 0.5, area.Bottom);
cairo_context.MoveTo (area.Right - 0.5, area.Y + 1.0);
cairo_context.LineTo (area.Right - 0.5, area.Bottom);
cairo_context.Stroke ();
}
ColumnCell cell = column_cache[ci].Column.HeaderCell;
if (cell != null) {
cairo_context.Save ();
cairo_context.Translate (area.X, area.Y);
cell_context.Area = area;
cell_context.State = StateType.Normal;
cell.Render (cell_context, area.Width, area.Height);
cairo_context.Restore ();
}
if (!dragging && ci < column_cache.Length - 1 && (have_drawn_separator ||
column_cache[ci].MaxWidth != column_cache[ci].MinWidth)) {
have_drawn_separator = true;
Theme.DrawHeaderSeparator (cairo_context, area, area.Right);
}
}
#endregion
#region List Rendering
void RenderDarkBackgroundInSortedColumn ()
{
if (pressed_column_is_dragging && pressed_column_index == sort_column_index) {
return;
}
CachedColumn col = column_cache [sort_column_index];
Theme.DrawRowRule (cairo_context,
list_rendering_alloc.X + col.X1 - HadjustmentValue,
header_rendering_alloc.Bottom + Theme.BorderWidth,
col.Width,
list_rendering_alloc.Height + Theme.InnerBorderWidth * 2);
}
private void PaintList (Rectangle clip)
{
if (ChildSize.Height <= 0) {
return;
}
if (sort_column_index != -1) {
RenderDarkBackgroundInSortedColumn ();
}
clip.Intersect (list_rendering_alloc);
cairo_context.Rectangle (clip.X, clip.Y, clip.Width, clip.Height);
cairo_context.Clip ();
cell_context.Clip = clip;
cell_context.TextAsForeground = false;
int vadjustment_value = VadjustmentValue;
int first_row = vadjustment_value / ChildSize.Height;
int last_row = Math.Min (model.Count, first_row + RowsInView);
int offset = list_rendering_alloc.Y - vadjustment_value % ChildSize.Height;
Rectangle selected_focus_alloc = Rectangle.Zero;
Rectangle single_list_alloc = new Rectangle ();
single_list_alloc.X = list_rendering_alloc.X - HadjustmentValue;
single_list_alloc.Y = offset;
single_list_alloc.Width = list_rendering_alloc.Width + HadjustmentValue;
single_list_alloc.Height = ChildSize.Height;
int selection_height = 0;
int selection_y = 0;
selected_rows.Clear ();
for (int ri = first_row; ri < last_row; ri++) {
if (Selection != null && Selection.Contains (ri)) {
if (selection_height == 0) {
selection_y = single_list_alloc.Y;
}
selection_height += single_list_alloc.Height;
selected_rows.Add (ri);
if (Selection.FocusedIndex == ri) {
selected_focus_alloc = single_list_alloc;
}
} else {
if (rules_hint && ri % 2 != 0) {
Theme.DrawRowRule (cairo_context, single_list_alloc.X, single_list_alloc.Y,
single_list_alloc.Width, single_list_alloc.Height);
}
PaintReorderLine (ri, single_list_alloc);
if (Selection != null && Selection.FocusedIndex == ri && !Selection.Contains (ri) && HasFocus) {
CairoCorners corners = CairoCorners.All;
if (Selection.Contains (ri - 1)) {
corners &= ~(CairoCorners.TopLeft | CairoCorners.TopRight);
}
if (Selection.Contains (ri + 1)) {
corners &= ~(CairoCorners.BottomLeft | CairoCorners.BottomRight);
}
if (HasFocus && !HeaderFocused) // Cursor out of selection.
Theme.DrawRowCursor (cairo_context, single_list_alloc.X, single_list_alloc.Y,
single_list_alloc.Width, single_list_alloc.Height,
CairoExtensions.ColorShade (Theme.Colors.GetWidgetColor (GtkColorClass.Background, StateType.Selected), 0.85));
}
if (selection_height > 0) {
Cairo.Color selection_color = Theme.Colors.GetWidgetColor (GtkColorClass.Background, StateType.Selected);
if (!HasFocus || HeaderFocused)
selection_color = CairoExtensions.ColorShade (selection_color, 1.1);
Theme.DrawRowSelection (cairo_context, list_rendering_alloc.X, selection_y, list_rendering_alloc.Width, selection_height,
true, true, selection_color, CairoCorners.All);
selection_height = 0;
}
PaintRow (ri, single_list_alloc, StateType.Normal);
}
single_list_alloc.Y += single_list_alloc.Height;
}
// In case the user is dragging to the end of the list
PaintReorderLine (last_row, single_list_alloc);
if (selection_height > 0) {
Theme.DrawRowSelection (cairo_context, list_rendering_alloc.X, selection_y,
list_rendering_alloc.Width, selection_height);
}
if (Selection != null && Selection.Count > 1 &&
!selected_focus_alloc.Equals (Rectangle.Zero) &&
HasFocus && !HeaderFocused) { // Cursor inside selection.
Theme.DrawRowCursor (cairo_context, selected_focus_alloc.X, selected_focus_alloc.Y,
selected_focus_alloc.Width, selected_focus_alloc.Height,
Theme.Colors.GetWidgetColor (GtkColorClass.Text, StateType.Selected));
}
foreach (int ri in selected_rows) {
single_list_alloc.Y = offset + ((ri - first_row) * single_list_alloc.Height);
PaintRow (ri, single_list_alloc, StateType.Selected);
}
cairo_context.ResetClip ();
}
private void PaintReorderLine (int row_index, Rectangle single_list_alloc)
{
if (row_index == drag_reorder_row_index && IsReorderable) {
cairo_context.Save ();
cairo_context.LineWidth = 1.0;
cairo_context.Antialias = Cairo.Antialias.None;
cairo_context.MoveTo (single_list_alloc.Left, single_list_alloc.Top);
cairo_context.LineTo (single_list_alloc.Right, single_list_alloc.Top);
cairo_context.SetSourceColor (Theme.Colors.GetWidgetColor (GtkColorClass.Text, StateType.Normal));
cairo_context.Stroke ();
cairo_context.Restore ();
}
}
private void PaintRow (int row_index, Rectangle area, StateType state)
{
if (column_cache == null) {
return;
}
object item = model[row_index];
bool opaque = IsRowOpaque (item);
bool bold = IsRowBold (item);
Rectangle cell_area = new Rectangle ();
cell_area.Height = ChildSize.Height;
cell_area.Y = area.Y;
cell_context.ViewRowIndex = cell_context.ModelRowIndex = row_index;
for (int ci = 0; ci < column_cache.Length; ci++) {
cell_context.ViewColumnIndex = ci;
if (pressed_column_is_dragging && pressed_column_index == ci) {
continue;
}
cell_area.Width = column_cache[ci].Width;
cell_area.X = column_cache[ci].X1 + area.X;
PaintCell (item, ci, row_index, cell_area, opaque, bold, state, false);
}
if (pressed_column_is_dragging && pressed_column_index >= 0) {
cell_area.Width = column_cache[pressed_column_index].Width;
cell_area.X = pressed_column_x_drag + list_rendering_alloc.X -
list_interaction_alloc.X - HadjustmentValue;
PaintCell (item, pressed_column_index, row_index, cell_area, opaque, bold, state, true);
}
}
private void PaintCell (object item, int column_index, int row_index, Rectangle area, bool opaque, bool bold,
StateType state, bool dragging)
{
ColumnCell cell = column_cache[column_index].Column.GetCell (0);
cell.Bind (item);
cell.Manager = manager;
ColumnCellDataProvider (cell, item);
ITextCell text_cell = cell as ITextCell;
if (text_cell != null) {
text_cell.FontWeight = bold ? Pango.Weight.Bold : Pango.Weight.Normal;
}
if (dragging) {
Cairo.Color fill_color = Theme.Colors.GetWidgetColor (GtkColorClass.Base, StateType.Normal);
fill_color.A = 0.5;
cairo_context.SetSourceColor (fill_color);
cairo_context.Rectangle (area.X, area.Y, area.Width, area.Height);
cairo_context.Fill ();
}
cairo_context.Save ();
cairo_context.Translate (area.X, area.Y);
cell_context.Area = area;
cell_context.Opaque = opaque;
cell_context.State = dragging ? StateType.Normal : state;
cell.Render (cell_context, area.Width, area.Height);
cairo_context.Restore ();
AccessibleCellRedrawn (column_index, row_index);
}
private void PaintDraggingColumn (Rectangle clip)
{
if (!pressed_column_is_dragging || pressed_column_index < 0) {
return;
}
CachedColumn column = column_cache[pressed_column_index];
int x = pressed_column_x_drag + Allocation.X + 1 - HadjustmentValue;
Cairo.Color fill_color = Theme.Colors.GetWidgetColor (GtkColorClass.Base, StateType.Normal);
fill_color.A = 0.45;
Cairo.Color stroke_color = CairoExtensions.ColorShade (Theme.Colors.GetWidgetColor (
GtkColorClass.Base, StateType.Normal), 0.0);
stroke_color.A = 0.3;
cairo_context.Rectangle (x, header_rendering_alloc.Bottom + 1, column.Width - 2,
list_rendering_alloc.Bottom - header_rendering_alloc.Bottom - 1);
cairo_context.SetSourceColor (fill_color);
cairo_context.Fill ();
cairo_context.MoveTo (x - 0.5, header_rendering_alloc.Bottom + 0.5);
cairo_context.LineTo (x - 0.5, list_rendering_alloc.Bottom + 0.5);
cairo_context.LineTo (x + column.Width - 1.5, list_rendering_alloc.Bottom + 0.5);
cairo_context.LineTo (x + column.Width - 1.5, header_rendering_alloc.Bottom + 0.5);
cairo_context.SetSourceColor (stroke_color);
cairo_context.LineWidth = 1.0;
cairo_context.Stroke ();
}
#endregion
#region View Layout Rendering
private void PaintView (Rect clip)
{
clip.Intersect ((Rect)list_rendering_alloc);
cairo_context.Rectangle ((Cairo.Rectangle)clip);
cairo_context.Clip ();
cell_context.Clip = (Gdk.Rectangle)clip;
cell_context.TextAsForeground = false;
selected_rows.Clear ();
for (int layout_index = 0; layout_index < ViewLayout.ChildCount; layout_index++) {
var layout_child = ViewLayout[layout_index];
var child_allocation = layout_child.Allocation;
if (!child_allocation.IntersectsWith (clip) || ViewLayout.GetModelIndex (layout_child) >= Model.Count) {
continue;
}
if (Selection != null && Selection.Contains (ViewLayout.GetModelIndex (layout_child))) {
selected_rows.Add (ViewLayout.GetModelIndex (layout_child));
var selection_color = Theme.Colors.GetWidgetColor (GtkColorClass.Background, StateType.Selected);
if (!HasFocus || HeaderFocused) {
selection_color = CairoExtensions.ColorShade (selection_color, 1.1);
}
Theme.DrawRowSelection (cairo_context,
(int)child_allocation.X, (int)child_allocation.Y,
(int)child_allocation.Width, (int)child_allocation.Height,
true, true, selection_color, CairoCorners.All);
cell_context.State = StateType.Selected;
} else {
cell_context.State = StateType.Normal;
}
//cairo_context.Save ();
//cairo_context.Translate (child_allocation.X, child_allocation.Y);
//cairo_context.Rectangle (0, 0, child_allocation.Width, child_allocation.Height);
//cairo_context.Clip ();
layout_child.Render (cell_context);
//cairo_context.Restore ();
}
cairo_context.ResetClip ();
}
#endregion
protected void InvalidateList ()
{
if (IsRealized) {
QueueDirtyRegion (list_rendering_alloc);
}
}
private void InvalidateHeader ()
{
if (IsRealized) {
QueueDirtyRegion (header_rendering_alloc);
}
}
protected void QueueDirtyRegion ()
{
QueueDirtyRegion (list_rendering_alloc);
}
protected virtual void ColumnCellDataProvider (ColumnCell cell, object boundItem)
{
}
private bool rules_hint = false;
public bool RulesHint {
get { return rules_hint; }
set {
rules_hint = value;
InvalidateList ();
}
}
// FIXME: Obsolete all this measure stuff on the view since it's in the layout
#region Measuring
private Gdk.Size child_size = Gdk.Size.Empty;
public Gdk.Size ChildSize {
get {
return ViewLayout != null
? new Gdk.Size ((int)ViewLayout.ChildSize.Width, (int)ViewLayout.ChildSize.Height)
: child_size;
}
}
private bool measure_pending;
protected virtual void OnInvalidateMeasure ()
{
measure_pending = true;
if (IsMapped && IsRealized) {
QueueDirtyRegion ();
}
}
protected virtual Gdk.Size OnMeasureChild ()
{
return ViewLayout != null
? new Gdk.Size ((int)ViewLayout.ChildSize.Width, (int)ViewLayout.ChildSize.Height)
: new Gdk.Size (0, ColumnCellText.ComputeRowHeight (this));
}
private void OnMeasure ()
{
if (!measure_pending) {
return;
}
measure_pending = false;
header_height = 0;
child_size = OnMeasureChild ();
UpdateAdjustments ();
}
#endregion
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <[email protected]>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
#if !NET_CF && !SILVERLIGHT
namespace NLog.Targets
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using NLog.Config;
/// <summary>
/// Writes log messages to the console with customizable coloring.
/// </summary>
/// <seealso href="http://nlog-project.org/wiki/ColoredConsole_target">Documentation on NLog Wiki</seealso>
[Target("ColoredConsole")]
public sealed class ColoredConsoleTarget : TargetWithLayoutHeaderAndFooter
{
private static readonly IList<ConsoleRowHighlightingRule> defaultConsoleRowHighlightingRules = new List<ConsoleRowHighlightingRule>()
{
new ConsoleRowHighlightingRule("level == LogLevel.Fatal", ConsoleOutputColor.Red, ConsoleOutputColor.NoChange),
new ConsoleRowHighlightingRule("level == LogLevel.Error", ConsoleOutputColor.Yellow, ConsoleOutputColor.NoChange),
new ConsoleRowHighlightingRule("level == LogLevel.Warn", ConsoleOutputColor.Magenta, ConsoleOutputColor.NoChange),
new ConsoleRowHighlightingRule("level == LogLevel.Info", ConsoleOutputColor.White, ConsoleOutputColor.NoChange),
new ConsoleRowHighlightingRule("level == LogLevel.Debug", ConsoleOutputColor.Gray, ConsoleOutputColor.NoChange),
new ConsoleRowHighlightingRule("level == LogLevel.Trace", ConsoleOutputColor.DarkGray, ConsoleOutputColor.NoChange),
};
/// <summary>
/// Initializes a new instance of the <see cref="ColoredConsoleTarget" /> class.
/// </summary>
/// <remarks>
/// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message}</code>
/// </remarks>
public ColoredConsoleTarget()
{
this.WordHighlightingRules = new List<ConsoleWordHighlightingRule>();
this.RowHighlightingRules = new List<ConsoleRowHighlightingRule>();
this.UseDefaultRowHighlightingRules = true;
}
/// <summary>
/// Gets or sets a value indicating whether the error stream (stderr) should be used instead of the output stream (stdout).
/// </summary>
/// <docgen category='Output Options' order='10' />
[DefaultValue(false)]
public bool ErrorStream { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to use default row highlighting rules.
/// </summary>
/// <remarks>
/// The default rules are:
/// <table>
/// <tr>
/// <th>Condition</th>
/// <th>Foreground Color</th>
/// <th>Background Color</th>
/// </tr>
/// <tr>
/// <td>level == LogLevel.Fatal</td>
/// <td>Red</td>
/// <td>NoChange</td>
/// </tr>
/// <tr>
/// <td>level == LogLevel.Error</td>
/// <td>Yellow</td>
/// <td>NoChange</td>
/// </tr>
/// <tr>
/// <td>level == LogLevel.Warn</td>
/// <td>Magenta</td>
/// <td>NoChange</td>
/// </tr>
/// <tr>
/// <td>level == LogLevel.Info</td>
/// <td>White</td>
/// <td>NoChange</td>
/// </tr>
/// <tr>
/// <td>level == LogLevel.Debug</td>
/// <td>Gray</td>
/// <td>NoChange</td>
/// </tr>
/// <tr>
/// <td>level == LogLevel.Trace</td>
/// <td>DarkGray</td>
/// <td>NoChange</td>
/// </tr>
/// </table>
/// </remarks>
/// <docgen category='Highlighting Rules' order='9' />
[DefaultValue(true)]
public bool UseDefaultRowHighlightingRules { get; set; }
/// <summary>
/// Gets the row highlighting rules.
/// </summary>
/// <docgen category='Highlighting Rules' order='10' />
[ArrayParameter(typeof(ConsoleRowHighlightingRule), "highlight-row")]
public IList<ConsoleRowHighlightingRule> RowHighlightingRules { get; private set; }
/// <summary>
/// Gets the word highlighting rules.
/// </summary>
/// <docgen category='Highlighting Rules' order='11' />
[ArrayParameter(typeof(ConsoleWordHighlightingRule), "highlight-word")]
public IList<ConsoleWordHighlightingRule> WordHighlightingRules { get; private set; }
/// <summary>
/// Initializes the target.
/// </summary>
protected override void InitializeTarget()
{
base.InitializeTarget();
if (Header != null)
{
LogEventInfo lei = LogEventInfo.CreateNullEvent();
this.Output(lei, Header.Render(lei));
}
}
/// <summary>
/// Closes the target and releases any unmanaged resources.
/// </summary>
protected override void CloseTarget()
{
if (Footer != null)
{
LogEventInfo lei = LogEventInfo.CreateNullEvent();
this.Output(lei, Footer.Render(lei));
}
base.CloseTarget();
}
/// <summary>
/// Writes the specified log event to the console highlighting entries
/// and words based on a set of defined rules.
/// </summary>
/// <param name="logEvent">Log event.</param>
protected override void Write(LogEventInfo logEvent)
{
this.Output(logEvent, this.Layout.Render(logEvent));
}
private static void ColorizeEscapeSequences(
TextWriter output,
string message,
ColorPair startingColor,
ColorPair defaultColor)
{
var colorStack = new Stack<ColorPair>();
colorStack.Push(startingColor);
int p0 = 0;
while (p0 < message.Length)
{
int p1 = p0;
while (p1 < message.Length && message[p1] >= 32)
{
p1++;
}
// text
if (p1 != p0)
{
output.Write(message.Substring(p0, p1 - p0));
}
if (p1 >= message.Length)
{
p0 = p1;
break;
}
// control characters
char c1 = message[p1];
char c2 = (char)0;
if (p1 + 1 < message.Length)
{
c2 = message[p1 + 1];
}
if (c1 == '\a' && c2 == '\a')
{
output.Write('\a');
p0 = p1 + 2;
continue;
}
if (c1 == '\r' || c1 == '\n')
{
Console.ForegroundColor = defaultColor.ForegroundColor;
Console.BackgroundColor = defaultColor.BackgroundColor;
output.Write(c1);
Console.ForegroundColor = colorStack.Peek().ForegroundColor;
Console.BackgroundColor = colorStack.Peek().BackgroundColor;
p0 = p1 + 1;
continue;
}
if (c1 == '\a')
{
if (c2 == 'X')
{
colorStack.Pop();
Console.ForegroundColor = colorStack.Peek().ForegroundColor;
Console.BackgroundColor = colorStack.Peek().BackgroundColor;
p0 = p1 + 2;
continue;
}
var foreground = (ConsoleOutputColor)(c2 - 'A');
var background = (ConsoleOutputColor)(message[p1 + 2] - 'A');
if (foreground != ConsoleOutputColor.NoChange)
{
Console.ForegroundColor = (ConsoleColor)foreground;
}
if (background != ConsoleOutputColor.NoChange)
{
Console.BackgroundColor = (ConsoleColor)background;
}
colorStack.Push(new ColorPair(Console.ForegroundColor, Console.BackgroundColor));
p0 = p1 + 3;
continue;
}
output.Write(c1);
p0 = p1 + 1;
}
if (p0 < message.Length)
{
output.Write(message.Substring(p0));
}
}
private void Output(LogEventInfo logEvent, string message)
{
ConsoleColor oldForegroundColor = Console.ForegroundColor;
ConsoleColor oldBackgroundColor = Console.BackgroundColor;
try
{
ConsoleRowHighlightingRule matchingRule = null;
foreach (ConsoleRowHighlightingRule cr in this.RowHighlightingRules)
{
if (cr.CheckCondition(logEvent))
{
matchingRule = cr;
break;
}
}
if (this.UseDefaultRowHighlightingRules && matchingRule == null)
{
foreach (ConsoleRowHighlightingRule cr in defaultConsoleRowHighlightingRules)
{
if (cr.CheckCondition(logEvent))
{
matchingRule = cr;
break;
}
}
}
if (matchingRule == null)
{
matchingRule = ConsoleRowHighlightingRule.Default;
}
if (matchingRule.ForegroundColor != ConsoleOutputColor.NoChange)
{
Console.ForegroundColor = (ConsoleColor)matchingRule.ForegroundColor;
}
if (matchingRule.BackgroundColor != ConsoleOutputColor.NoChange)
{
Console.BackgroundColor = (ConsoleColor)matchingRule.BackgroundColor;
}
message = message.Replace("\a", "\a\a");
foreach (ConsoleWordHighlightingRule hl in this.WordHighlightingRules)
{
message = hl.ReplaceWithEscapeSequences(message);
}
ColorizeEscapeSequences(this.ErrorStream ? Console.Error : Console.Out, message, new ColorPair(Console.ForegroundColor, Console.BackgroundColor), new ColorPair(oldForegroundColor, oldBackgroundColor));
}
finally
{
Console.ForegroundColor = oldForegroundColor;
Console.BackgroundColor = oldBackgroundColor;
}
if (this.ErrorStream)
{
Console.Error.WriteLine();
}
else
{
Console.WriteLine();
}
}
/// <summary>
/// Color pair (foreground and background).
/// </summary>
internal struct ColorPair
{
private readonly ConsoleColor foregroundColor;
private readonly ConsoleColor backgroundColor;
internal ColorPair(ConsoleColor foregroundColor, ConsoleColor backgroundColor)
{
this.foregroundColor = foregroundColor;
this.backgroundColor = backgroundColor;
}
internal ConsoleColor BackgroundColor
{
get { return this.backgroundColor; }
}
internal ConsoleColor ForegroundColor
{
get { return this.foregroundColor; }
}
}
}
}
#endif
| |
// <copyright file="SvdTests.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
using System;
using MathNet.Numerics.LinearAlgebra;
using MathNet.Numerics.LinearAlgebra.Complex;
using NUnit.Framework;
namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Complex.Factorization
{
#if NOSYSNUMERICS
using Complex = Numerics.Complex;
#else
using Complex = System.Numerics.Complex;
#endif
/// <summary>
/// Svd factorization tests for a dense matrix.
/// </summary>
[TestFixture, Category("LAFactorization")]
public class SvdTests
{
/// <summary>
/// Can factorize identity matrix.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(10)]
[TestCase(100)]
public void CanFactorizeIdentity(int order)
{
var matrixI = DenseMatrix.CreateIdentity(order);
var factorSvd = matrixI.Svd();
var u = factorSvd.U;
var vt = factorSvd.VT;
var w = factorSvd.W;
Assert.AreEqual(matrixI.RowCount, u.RowCount);
Assert.AreEqual(matrixI.RowCount, u.ColumnCount);
Assert.AreEqual(matrixI.ColumnCount, vt.RowCount);
Assert.AreEqual(matrixI.ColumnCount, vt.ColumnCount);
Assert.AreEqual(matrixI.RowCount, w.RowCount);
Assert.AreEqual(matrixI.ColumnCount, w.ColumnCount);
for (var i = 0; i < w.RowCount; i++)
{
for (var j = 0; j < w.ColumnCount; j++)
{
Assert.AreEqual(i == j ? Complex.One : Complex.Zero, w[i, j]);
}
}
}
/// <summary>
/// Can factorize a random matrix.
/// </summary>
/// <param name="row">Matrix row number.</param>
/// <param name="column">Matrix column number.</param>
[TestCase(1, 1)]
[TestCase(2, 2)]
[TestCase(5, 5)]
[TestCase(10, 6)]
[TestCase(50, 48)]
[TestCase(100, 98)]
public void CanFactorizeRandomMatrix(int row, int column)
{
var matrixA = Matrix<Complex>.Build.Random(row, column, 1);
var factorSvd = matrixA.Svd();
var u = factorSvd.U;
var vt = factorSvd.VT;
var w = factorSvd.W;
// Make sure the U has the right dimensions.
Assert.AreEqual(row, u.RowCount);
Assert.AreEqual(row, u.ColumnCount);
// Make sure the VT has the right dimensions.
Assert.AreEqual(column, vt.RowCount);
Assert.AreEqual(column, vt.ColumnCount);
// Make sure the W has the right dimensions.
Assert.AreEqual(row, w.RowCount);
Assert.AreEqual(column, w.ColumnCount);
// Make sure the U*W*VT is the original matrix.
var matrix = u*w*vt;
for (var i = 0; i < matrix.RowCount; i++)
{
for (var j = 0; j < matrix.ColumnCount; j++)
{
AssertHelpers.AlmostEqualRelative(matrixA[i, j], matrix[i, j], 9);
}
}
}
/// <summary>
/// Can check rank of a non-square matrix.
/// </summary>
/// <param name="row">Matrix row number.</param>
/// <param name="column">Matrix column number.</param>
[TestCase(10, 8)]
[TestCase(48, 52)]
[TestCase(100, 93)]
public void CanCheckRankOfNonSquare(int row, int column)
{
var matrixA = Matrix<Complex>.Build.Random(row, column, 1);
var factorSvd = matrixA.Svd();
var mn = Math.Min(row, column);
Assert.AreEqual(factorSvd.Rank, mn);
}
/// <summary>
/// Can check rank of a square matrix.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(2)]
[TestCase(5)]
[TestCase(9)]
[TestCase(50)]
[TestCase(90)]
public void CanCheckRankSquare(int order)
{
var matrixA = Matrix<Complex>.Build.Random(order, order, 1);
var factorSvd = matrixA.Svd();
if (factorSvd.Determinant != 0)
{
Assert.AreEqual(factorSvd.Rank, order);
}
else
{
Assert.AreEqual(factorSvd.Rank, order - 1);
}
}
/// <summary>
/// Can check rank of a square singular matrix.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(10)]
[TestCase(50)]
[TestCase(100)]
public void CanCheckRankOfSquareSingular(int order)
{
var matrixA = new DenseMatrix(order, order);
matrixA[0, 0] = 1;
matrixA[order - 1, order - 1] = 1;
for (var i = 1; i < order - 1; i++)
{
matrixA[i, i - 1] = 1;
matrixA[i, i + 1] = 1;
matrixA[i - 1, i] = 1;
matrixA[i + 1, i] = 1;
}
var factorSvd = matrixA.Svd();
Assert.AreEqual(factorSvd.Determinant, Complex.Zero);
Assert.AreEqual(factorSvd.Rank, order - 1);
}
/// <summary>
/// Solve for matrix if vectors are not computed throws <c>InvalidOperationException</c>.
/// </summary>
[Test]
public void SolveMatrixIfVectorsNotComputedThrowsInvalidOperationException()
{
var matrixA = Matrix<Complex>.Build.Random(10, 9, 1);
var factorSvd = matrixA.Svd(false);
var matrixB = Matrix<Complex>.Build.Random(10, 9, 1);
Assert.That(() => factorSvd.Solve(matrixB), Throws.InvalidOperationException);
}
/// <summary>
/// Solve for vector if vectors are not computed throws <c>InvalidOperationException</c>.
/// </summary>
[Test]
public void SolveVectorIfVectorsNotComputedThrowsInvalidOperationException()
{
var matrixA = Matrix<Complex>.Build.Random(10, 9, 1);
var factorSvd = matrixA.Svd(false);
var vectorb = Vector<Complex>.Build.Random(9, 1);
Assert.That(() => factorSvd.Solve(vectorb), Throws.InvalidOperationException);
}
/// <summary>
/// Can solve a system of linear equations for a random vector (Ax=b).
/// </summary>
/// <param name="row">Matrix row number.</param>
/// <param name="column">Matrix column number.</param>
[TestCase(1, 1)]
[TestCase(2, 2)]
[TestCase(5, 5)]
[TestCase(9, 10)]
[TestCase(50, 50)]
[TestCase(90, 100)]
public void CanSolveForRandomVector(int row, int column)
{
var matrixA = Matrix<Complex>.Build.Random(row, column, 1);
var matrixACopy = matrixA.Clone();
var factorSvd = matrixA.Svd();
var vectorb = Vector<Complex>.Build.Random(row, 1);
var resultx = factorSvd.Solve(vectorb);
Assert.AreEqual(matrixA.ColumnCount, resultx.Count);
var matrixBReconstruct = matrixA*resultx;
// Check the reconstruction.
for (var i = 0; i < vectorb.Count; i++)
{
AssertHelpers.AlmostEqual(vectorb[i], matrixBReconstruct[i], 10);
}
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
}
/// <summary>
/// Can solve a system of linear equations for a random matrix (AX=B).
/// </summary>
/// <param name="row">Matrix row number.</param>
/// <param name="column">Matrix column number.</param>
[TestCase(1, 1)]
[TestCase(4, 4)]
[TestCase(7, 8)]
[TestCase(10, 10)]
[TestCase(45, 50)]
[TestCase(80, 100)]
public void CanSolveForRandomMatrix(int row, int column)
{
var matrixA = Matrix<Complex>.Build.Random(row, column, 1);
var matrixACopy = matrixA.Clone();
var factorSvd = matrixA.Svd();
var matrixB = Matrix<Complex>.Build.Random(row, column, 1);
var matrixX = factorSvd.Solve(matrixB);
// The solution X row dimension is equal to the column dimension of A
Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount);
// The solution X has the same number of columns as B
Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount);
var matrixBReconstruct = matrixA*matrixX;
// Check the reconstruction.
for (var i = 0; i < matrixB.RowCount; i++)
{
for (var j = 0; j < matrixB.ColumnCount; j++)
{
AssertHelpers.AlmostEqual(matrixB[i, j], matrixBReconstruct[i, j], 10);
}
}
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
}
/// <summary>
/// Can solve for a random vector into a result vector.
/// </summary>
/// <param name="row">Matrix row number.</param>
/// <param name="column">Matrix column number.</param>
[TestCase(1, 1)]
[TestCase(2, 2)]
[TestCase(5, 5)]
[TestCase(9, 10)]
[TestCase(50, 50)]
[TestCase(90, 100)]
public void CanSolveForRandomVectorWhenResultVectorGiven(int row, int column)
{
var matrixA = Matrix<Complex>.Build.Random(row, column, 1);
var matrixACopy = matrixA.Clone();
var factorSvd = matrixA.Svd();
var vectorb = Vector<Complex>.Build.Random(row, 1);
var vectorbCopy = vectorb.Clone();
var resultx = new DenseVector(column);
factorSvd.Solve(vectorb, resultx);
var matrixBReconstruct = matrixA*resultx;
// Check the reconstruction.
for (var i = 0; i < vectorb.Count; i++)
{
AssertHelpers.AlmostEqual(vectorb[i], matrixBReconstruct[i], 10);
}
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
// Make sure b didn't change.
for (var i = 0; i < vectorb.Count; i++)
{
Assert.AreEqual(vectorbCopy[i], vectorb[i]);
}
}
/// <summary>
/// Can solve a system of linear equations for a random matrix (AX=B) into a result matrix.
/// </summary>
/// <param name="row">Matrix row number.</param>
/// <param name="column">Matrix column number.</param>
[TestCase(1, 1)]
[TestCase(4, 4)]
[TestCase(7, 8)]
[TestCase(10, 10)]
[TestCase(45, 50)]
[TestCase(80, 100)]
public void CanSolveForRandomMatrixWhenResultMatrixGiven(int row, int column)
{
var matrixA = Matrix<Complex>.Build.Random(row, column, 1);
var matrixACopy = matrixA.Clone();
var factorSvd = matrixA.Svd();
var matrixB = Matrix<Complex>.Build.Random(row, column, 1);
var matrixBCopy = matrixB.Clone();
var matrixX = new DenseMatrix(column, column);
factorSvd.Solve(matrixB, matrixX);
// The solution X row dimension is equal to the column dimension of A
Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount);
// The solution X has the same number of columns as B
Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount);
var matrixBReconstruct = matrixA*matrixX;
// Check the reconstruction.
for (var i = 0; i < matrixB.RowCount; i++)
{
for (var j = 0; j < matrixB.ColumnCount; j++)
{
AssertHelpers.AlmostEqual(matrixB[i, j], matrixBReconstruct[i, j], 10);
}
}
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
// Make sure B didn't change.
for (var i = 0; i < matrixB.RowCount; i++)
{
for (var j = 0; j < matrixB.ColumnCount; j++)
{
Assert.AreEqual(matrixBCopy[i, j], matrixB[i, j]);
}
}
}
}
}
| |
using System;
using System.Linq;
using System.Runtime.InteropServices;
using Torque6.Engine.SimObjects;
using Torque6.Engine.SimObjects.Scene;
using Torque6.Engine.Namespaces;
using Torque6.Utility;
namespace Torque6.Engine.SimObjects.GuiControls
{
public unsafe class DbgFileView : GuiArrayCtrl
{
public DbgFileView()
{
ObjectPtr = Sim.WrapObject(InternalUnsafeMethods.DbgFileViewCreateInstance());
}
public DbgFileView(uint pId) : base(pId)
{
}
public DbgFileView(string pName) : base(pName)
{
}
public DbgFileView(IntPtr pObjPtr) : base(pObjPtr)
{
}
public DbgFileView(Sim.SimObjectPtr* pObjPtr) : base(pObjPtr)
{
}
public DbgFileView(SimObject pObj) : base(pObj)
{
}
#region UnsafeNativeMethods
new internal struct InternalUnsafeMethods
{
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate IntPtr _DbgFileViewCreateInstance();
private static _DbgFileViewCreateInstance _DbgFileViewCreateInstanceFunc;
internal static IntPtr DbgFileViewCreateInstance()
{
if (_DbgFileViewCreateInstanceFunc == null)
{
_DbgFileViewCreateInstanceFunc =
(_DbgFileViewCreateInstance)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"DbgFileViewCreateInstance"), typeof(_DbgFileViewCreateInstance));
}
return _DbgFileViewCreateInstanceFunc();
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _DbgFileViewSetCurrentLine(IntPtr view, int line, bool selected);
private static _DbgFileViewSetCurrentLine _DbgFileViewSetCurrentLineFunc;
internal static void DbgFileViewSetCurrentLine(IntPtr view, int line, bool selected)
{
if (_DbgFileViewSetCurrentLineFunc == null)
{
_DbgFileViewSetCurrentLineFunc =
(_DbgFileViewSetCurrentLine)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"DbgFileViewSetCurrentLine"), typeof(_DbgFileViewSetCurrentLine));
}
_DbgFileViewSetCurrentLineFunc(view, line, selected);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate IntPtr _DbgFileViewGetCurrentLine(IntPtr view, int line, bool selected);
private static _DbgFileViewGetCurrentLine _DbgFileViewGetCurrentLineFunc;
internal static IntPtr DbgFileViewGetCurrentLine(IntPtr view, int line, bool selected)
{
if (_DbgFileViewGetCurrentLineFunc == null)
{
_DbgFileViewGetCurrentLineFunc =
(_DbgFileViewGetCurrentLine)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"DbgFileViewGetCurrentLine"), typeof(_DbgFileViewGetCurrentLine));
}
return _DbgFileViewGetCurrentLineFunc(view, line, selected);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate bool _DbgFileViewOpen(IntPtr view, string fileName);
private static _DbgFileViewOpen _DbgFileViewOpenFunc;
internal static bool DbgFileViewOpen(IntPtr view, string fileName)
{
if (_DbgFileViewOpenFunc == null)
{
_DbgFileViewOpenFunc =
(_DbgFileViewOpen)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"DbgFileViewOpen"), typeof(_DbgFileViewOpen));
}
return _DbgFileViewOpenFunc(view, fileName);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _DbgFileViewClearBreakPositions(IntPtr view);
private static _DbgFileViewClearBreakPositions _DbgFileViewClearBreakPositionsFunc;
internal static void DbgFileViewClearBreakPositions(IntPtr view)
{
if (_DbgFileViewClearBreakPositionsFunc == null)
{
_DbgFileViewClearBreakPositionsFunc =
(_DbgFileViewClearBreakPositions)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"DbgFileViewClearBreakPositions"), typeof(_DbgFileViewClearBreakPositions));
}
_DbgFileViewClearBreakPositionsFunc(view);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _DbgFileViewSetBreakPosition(IntPtr view, int line);
private static _DbgFileViewSetBreakPosition _DbgFileViewSetBreakPositionFunc;
internal static void DbgFileViewSetBreakPosition(IntPtr view, int line)
{
if (_DbgFileViewSetBreakPositionFunc == null)
{
_DbgFileViewSetBreakPositionFunc =
(_DbgFileViewSetBreakPosition)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"DbgFileViewSetBreakPosition"), typeof(_DbgFileViewSetBreakPosition));
}
_DbgFileViewSetBreakPositionFunc(view, line);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _DbgFileViewSetBreak(IntPtr view, int line);
private static _DbgFileViewSetBreak _DbgFileViewSetBreakFunc;
internal static void DbgFileViewSetBreak(IntPtr view, int line)
{
if (_DbgFileViewSetBreakFunc == null)
{
_DbgFileViewSetBreakFunc =
(_DbgFileViewSetBreak)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"DbgFileViewSetBreak"), typeof(_DbgFileViewSetBreak));
}
_DbgFileViewSetBreakFunc(view, line);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _DbgFileViewRemoveBreak(IntPtr view, int line);
private static _DbgFileViewRemoveBreak _DbgFileViewRemoveBreakFunc;
internal static void DbgFileViewRemoveBreak(IntPtr view, int line)
{
if (_DbgFileViewRemoveBreakFunc == null)
{
_DbgFileViewRemoveBreakFunc =
(_DbgFileViewRemoveBreak)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"DbgFileViewRemoveBreak"), typeof(_DbgFileViewRemoveBreak));
}
_DbgFileViewRemoveBreakFunc(view, line);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate bool _DbgFileViewFindString(IntPtr view, string findThis);
private static _DbgFileViewFindString _DbgFileViewFindStringFunc;
internal static bool DbgFileViewFindString(IntPtr view, string findThis)
{
if (_DbgFileViewFindStringFunc == null)
{
_DbgFileViewFindStringFunc =
(_DbgFileViewFindString)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"DbgFileViewFindString"), typeof(_DbgFileViewFindString));
}
return _DbgFileViewFindStringFunc(view, findThis);
}
}
#endregion
#region Properties
#endregion
#region Methods
public void SetCurrentLine(int line, bool selected)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.DbgFileViewSetCurrentLine(ObjectPtr->ObjPtr, line, selected);
}
public string GetCurrentLine(int line, bool selected)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return Marshal.PtrToStringAnsi(InternalUnsafeMethods.DbgFileViewGetCurrentLine(ObjectPtr->ObjPtr, line, selected));
}
public bool Open(string fileName)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return InternalUnsafeMethods.DbgFileViewOpen(ObjectPtr->ObjPtr, fileName);
}
public void ClearBreakPositions()
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.DbgFileViewClearBreakPositions(ObjectPtr->ObjPtr);
}
public void SetBreakPosition(int line)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.DbgFileViewSetBreakPosition(ObjectPtr->ObjPtr, line);
}
public void SetBreak(int line)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.DbgFileViewSetBreak(ObjectPtr->ObjPtr, line);
}
public void RemoveBreak(int line)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.DbgFileViewRemoveBreak(ObjectPtr->ObjPtr, line);
}
public bool FindString(string findThis)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return InternalUnsafeMethods.DbgFileViewFindString(ObjectPtr->ObjPtr, findThis);
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
namespace System.Data.SqlClient.SNI
{
/// <summary>
/// TCP connection handle
/// </summary>
internal class SNITCPHandle : SNIHandle
{
private readonly string _targetServer;
private readonly object _callbackObject;
private readonly Socket _socket;
private NetworkStream _tcpStream;
private readonly TaskScheduler _writeScheduler;
private readonly TaskFactory _writeTaskFactory;
private Stream _stream;
private SslStream _sslStream;
private SslOverTdsStream _sslOverTdsStream;
private SNIAsyncCallback _receiveCallback;
private SNIAsyncCallback _sendCallback;
private bool _validateCert = true;
private int _bufferSize = TdsEnums.DEFAULT_LOGIN_PACKET_SIZE;
private uint _status = TdsEnums.SNI_UNINITIALIZED;
private Guid _connectionId = Guid.NewGuid();
private const int MaxParallelIpAddresses = 64;
/// <summary>
/// Dispose object
/// </summary>
public override void Dispose()
{
lock (this)
{
if (_sslOverTdsStream != null)
{
_sslOverTdsStream.Dispose();
_sslOverTdsStream = null;
}
if (_sslStream != null)
{
_sslStream.Dispose();
_sslStream = null;
}
if (_tcpStream != null)
{
_tcpStream.Dispose();
_tcpStream = null;
}
//Release any references held by _stream.
_stream = null;
}
}
/// <summary>
/// Connection ID
/// </summary>
public override Guid ConnectionId
{
get
{
return _connectionId;
}
}
/// <summary>
/// Connection status
/// </summary>
public override uint Status
{
get
{
return _status;
}
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="serverName">Server name</param>
/// <param name="port">TCP port number</param>
/// <param name="timerExpire">Connection timer expiration</param>
/// <param name="callbackObject">Callback object</param>
public SNITCPHandle(string serverName, int port, long timerExpire, object callbackObject, bool parallel)
{
_writeScheduler = new ConcurrentExclusiveSchedulerPair().ExclusiveScheduler;
_writeTaskFactory = new TaskFactory(_writeScheduler);
_callbackObject = callbackObject;
_targetServer = serverName;
try
{
TimeSpan ts = default(TimeSpan);
// In case the Timeout is Infinite, we will receive the max value of Int64 as the tick count
// The infinite Timeout is a function of ConnectionString Timeout=0
bool isInfiniteTimeOut = long.MaxValue == timerExpire;
if (!isInfiniteTimeOut)
{
ts = DateTime.FromFileTime(timerExpire) - DateTime.Now;
ts = ts.Ticks < 0 ? TimeSpan.FromTicks(0) : ts;
}
Task<Socket> connectTask;
if (parallel)
{
Task<IPAddress[]> serverAddrTask = Dns.GetHostAddressesAsync(serverName);
serverAddrTask.Wait(ts);
IPAddress[] serverAddresses = serverAddrTask.Result;
if (serverAddresses.Length > MaxParallelIpAddresses)
{
// Fail if above 64 to match legacy behavior
ReportTcpSNIError(0, SNICommon.MultiSubnetFailoverWithMoreThan64IPs, string.Empty);
return;
}
connectTask = ParallelConnectAsync(serverAddresses, port);
}
else
{
connectTask = ConnectAsync(serverName, port);
}
if (!(isInfiniteTimeOut ? connectTask.Wait(-1) : connectTask.Wait(ts)))
{
ReportTcpSNIError(0, SNICommon.ConnOpenFailedError, string.Empty);
return;
}
_socket = connectTask.Result;
if (_socket == null || !_socket.Connected)
{
if (_socket != null)
{
_socket.Dispose();
_socket = null;
}
ReportTcpSNIError(0, SNICommon.ConnOpenFailedError, string.Empty);
return;
}
_socket.NoDelay = true;
_tcpStream = new NetworkStream(_socket, true);
_sslOverTdsStream = new SslOverTdsStream(_tcpStream);
_sslStream = new SslStream(_sslOverTdsStream, true, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
}
catch (SocketException se)
{
ReportTcpSNIError(se);
return;
}
catch (Exception e)
{
ReportTcpSNIError(e);
return;
}
_stream = _tcpStream;
_status = TdsEnums.SNI_SUCCESS;
}
private static async Task<Socket> ConnectAsync(string serverName, int port)
{
IPAddress[] addresses = await Dns.GetHostAddressesAsync(serverName).ConfigureAwait(false);
IPAddress targetAddrV4 = Array.Find(addresses, addr => (addr.AddressFamily == AddressFamily.InterNetwork));
IPAddress targetAddrV6 = Array.Find(addresses, addr => (addr.AddressFamily == AddressFamily.InterNetworkV6));
if (targetAddrV4 != null && targetAddrV6 != null)
{
return await ParallelConnectAsync(new IPAddress[] { targetAddrV4, targetAddrV6 }, port).ConfigureAwait(false);
}
else
{
IPAddress targetAddr = (targetAddrV4 != null) ? targetAddrV4 : targetAddrV6;
var socket = new Socket(targetAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
try
{
await socket.ConnectAsync(targetAddr, port).ConfigureAwait(false);
}
catch
{
socket.Dispose();
throw;
}
return socket;
}
}
private static Task<Socket> ParallelConnectAsync(IPAddress[] serverAddresses, int port)
{
if (serverAddresses == null)
{
throw new ArgumentNullException(nameof(serverAddresses));
}
if (serverAddresses.Length == 0)
{
throw new ArgumentOutOfRangeException(nameof(serverAddresses));
}
var sockets = new List<Socket>(serverAddresses.Length);
var connectTasks = new List<Task>(serverAddresses.Length);
var tcs = new TaskCompletionSource<Socket>();
var lastError = new StrongBox<Exception>();
var pendingCompleteCount = new StrongBox<int>(serverAddresses.Length);
foreach (IPAddress address in serverAddresses)
{
var socket = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
sockets.Add(socket);
// Start all connection tasks now, to prevent possible race conditions with
// calling ConnectAsync on disposed sockets.
try
{
connectTasks.Add(socket.ConnectAsync(address, port));
}
catch (Exception e)
{
connectTasks.Add(Task.FromException(e));
}
}
for (int i = 0; i < sockets.Count; i++)
{
ParallelConnectHelper(sockets[i], connectTasks[i], tcs, pendingCompleteCount, lastError, sockets);
}
return tcs.Task;
}
private static async void ParallelConnectHelper(
Socket socket,
Task connectTask,
TaskCompletionSource<Socket> tcs,
StrongBox<int> pendingCompleteCount,
StrongBox<Exception> lastError,
List<Socket> sockets)
{
bool success = false;
try
{
// Try to connect. If we're successful, store this task into the result task.
await connectTask.ConfigureAwait(false);
success = tcs.TrySetResult(socket);
if (success)
{
// Whichever connection completes the return task is responsible for disposing
// all of the sockets (except for whichever one is stored into the result task).
// This ensures that only one thread will attempt to dispose of a socket.
// This is also the closest thing we have to canceling connect attempts.
foreach (Socket otherSocket in sockets)
{
if (otherSocket != socket)
{
otherSocket.Dispose();
}
}
}
}
catch (Exception e)
{
// Store an exception to be published if no connection succeeds
Interlocked.Exchange(ref lastError.Value, e);
}
finally
{
// If we didn't successfully transition the result task to completed,
// then someone else did and they would have cleaned up, so there's nothing
// more to do. Otherwise, no one completed it yet or we failed; either way,
// see if we're the last outstanding connection, and if we are, try to complete
// the task, and if we're successful, it's our responsibility to dispose all of the sockets.
if (!success && Interlocked.Decrement(ref pendingCompleteCount.Value) == 0)
{
if (lastError.Value != null)
{
tcs.TrySetException(lastError.Value);
}
else
{
tcs.TrySetCanceled();
}
foreach (Socket s in sockets)
{
s.Dispose();
}
}
}
}
/// <summary>
/// Enable SSL
/// </summary>
public override uint EnableSsl(uint options)
{
_validateCert = (options & TdsEnums.SNI_SSL_VALIDATE_CERTIFICATE) != 0;
try
{
_sslStream.AuthenticateAsClientAsync(_targetServer).GetAwaiter().GetResult();
_sslOverTdsStream.FinishHandshake();
}
catch (AuthenticationException aue)
{
return ReportTcpSNIError(aue);
}
catch (InvalidOperationException ioe)
{
return ReportTcpSNIError(ioe);
}
_stream = _sslStream;
return TdsEnums.SNI_SUCCESS;
}
/// <summary>
/// Disable SSL
/// </summary>
public override void DisableSsl()
{
_sslStream.Dispose();
_sslStream = null;
_sslOverTdsStream.Dispose();
_sslOverTdsStream = null;
_stream = _tcpStream;
}
/// <summary>
/// Validate server certificate callback
/// </summary>
/// <param name="sender">Sender object</param>
/// <param name="cert">X.509 certificate</param>
/// <param name="chain">X.509 chain</param>
/// <param name="policyErrors">Policy errors</param>
/// <returns>True if certificate is valid</returns>
private bool ValidateServerCertificate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors policyErrors)
{
if (!_validateCert)
{
return true;
}
return SNICommon.ValidateSslServerCertificate(_targetServer, sender, cert, chain, policyErrors);
}
/// <summary>
/// Set buffer size
/// </summary>
/// <param name="bufferSize">Buffer size</param>
public override void SetBufferSize(int bufferSize)
{
_bufferSize = bufferSize;
_socket.SendBufferSize = bufferSize;
_socket.ReceiveBufferSize = bufferSize;
}
/// <summary>
/// Send a packet synchronously
/// </summary>
/// <param name="packet">SNI packet</param>
/// <returns>SNI error code</returns>
public override uint Send(SNIPacket packet)
{
lock (this)
{
try
{
packet.WriteToStream(_stream);
return TdsEnums.SNI_SUCCESS;
}
catch (ObjectDisposedException ode)
{
return ReportTcpSNIError(ode);
}
catch (SocketException se)
{
return ReportTcpSNIError(se);
}
catch (IOException ioe)
{
return ReportTcpSNIError(ioe);
}
}
}
/// <summary>
/// Receive a packet synchronously
/// </summary>
/// <param name="packet">SNI packet</param>
/// <param name="timeoutInMilliseconds">Timeout in Milliseconds</param>
/// <returns>SNI error code</returns>
public override uint Receive(out SNIPacket packet, int timeoutInMilliseconds)
{
lock (this)
{
packet = null;
try
{
if (timeoutInMilliseconds > 0)
{
_socket.ReceiveTimeout = timeoutInMilliseconds;
}
else if (timeoutInMilliseconds == -1)
{ // SqlCient internally represents infinite timeout by -1, and for TcpClient this is translated to a timeout of 0
_socket.ReceiveTimeout = 0;
}
else
{
// otherwise it is timeout for 0 or less than -1
ReportTcpSNIError(0, SNICommon.ConnTimeoutError, string.Empty);
return TdsEnums.SNI_WAIT_TIMEOUT;
}
packet = new SNIPacket(null);
packet.Allocate(_bufferSize);
packet.ReadFromStream(_stream);
if (packet.Length == 0)
{
var e = new Win32Exception();
return ReportErrorAndReleasePacket(packet, (uint)e.NativeErrorCode, 0, e.Message);
}
return TdsEnums.SNI_SUCCESS;
}
catch (ObjectDisposedException ode)
{
return ReportErrorAndReleasePacket(packet, ode);
}
catch (SocketException se)
{
return ReportErrorAndReleasePacket(packet, se);
}
catch (IOException ioe)
{
uint errorCode = ReportErrorAndReleasePacket(packet, ioe);
if (ioe.InnerException is SocketException && ((SocketException)(ioe.InnerException)).SocketErrorCode == SocketError.TimedOut)
{
errorCode = TdsEnums.SNI_WAIT_TIMEOUT;
}
return errorCode;
}
finally
{
_socket.ReceiveTimeout = 0;
}
}
}
/// <summary>
/// Set async callbacks
/// </summary>
/// <param name="receiveCallback">Receive callback</param>
/// <param name="sendCallback">Send callback</param>
/// <summary>
public override void SetAsyncCallbacks(SNIAsyncCallback receiveCallback, SNIAsyncCallback sendCallback)
{
_receiveCallback = receiveCallback;
_sendCallback = sendCallback;
}
/// <summary>
/// Send a packet asynchronously
/// </summary>
/// <param name="packet">SNI packet</param>
/// <param name="callback">Completion callback</param>
/// <returns>SNI error code</returns>
public override uint SendAsync(SNIPacket packet, SNIAsyncCallback callback = null)
{
SNIPacket newPacket = packet;
_writeTaskFactory.StartNew(() =>
{
try
{
lock (this)
{
packet.WriteToStream(_stream);
}
}
catch (Exception e)
{
SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.TCP_PROV, SNICommon.InternalExceptionError, e);
if (callback != null)
{
callback(packet, TdsEnums.SNI_ERROR);
}
else
{
_sendCallback(packet, TdsEnums.SNI_ERROR);
}
return;
}
if (callback != null)
{
callback(packet, TdsEnums.SNI_SUCCESS);
}
else
{
_sendCallback(packet, TdsEnums.SNI_SUCCESS);
}
});
return TdsEnums.SNI_SUCCESS_IO_PENDING;
}
/// <summary>
/// Receive a packet asynchronously
/// </summary>
/// <param name="packet">SNI packet</param>
/// <returns>SNI error code</returns>
public override uint ReceiveAsync(ref SNIPacket packet)
{
lock (this)
{
packet = new SNIPacket(null);
packet.Allocate(_bufferSize);
try
{
packet.ReadFromStreamAsync(_stream, _receiveCallback);
return TdsEnums.SNI_SUCCESS_IO_PENDING;
}
catch (ObjectDisposedException ode)
{
return ReportErrorAndReleasePacket(packet, ode);
}
catch (SocketException se)
{
return ReportErrorAndReleasePacket(packet, se);
}
catch (IOException ioe)
{
return ReportErrorAndReleasePacket(packet, ioe);
}
}
}
/// <summary>
/// Check SNI handle connection
/// </summary>
/// <param name="handle"></param>
/// <returns>SNI error status</returns>
public override uint CheckConnection()
{
try
{
if (!_socket.Connected || _socket.Poll(0, SelectMode.SelectError))
{
return TdsEnums.SNI_ERROR;
}
}
catch (SocketException se)
{
return ReportTcpSNIError(se);
}
catch (ObjectDisposedException ode)
{
return ReportTcpSNIError(ode);
}
return TdsEnums.SNI_SUCCESS;
}
private uint ReportTcpSNIError(Exception sniException)
{
_status = TdsEnums.SNI_ERROR;
return SNICommon.ReportSNIError(SNIProviders.TCP_PROV, SNICommon.InternalExceptionError, sniException);
}
private uint ReportTcpSNIError(uint nativeError, uint sniError, string errorMessage)
{
_status = TdsEnums.SNI_ERROR;
return SNICommon.ReportSNIError(SNIProviders.TCP_PROV, nativeError, sniError, errorMessage);
}
private uint ReportErrorAndReleasePacket(SNIPacket packet, Exception sniException)
{
if (packet != null)
{
packet.Release();
}
return ReportTcpSNIError(sniException);
}
private uint ReportErrorAndReleasePacket(SNIPacket packet, uint nativeError, uint sniError, string errorMessage)
{
if (packet != null)
{
packet.Release();
}
return ReportTcpSNIError(nativeError, sniError, errorMessage);
}
#if DEBUG
/// <summary>
/// Test handle for killing underlying connection
/// </summary>
public override void KillConnection()
{
_socket.Shutdown(SocketShutdown.Both);
}
#endif
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace ContactsService.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);
}
}
}
}
| |
using System;
using OrchardCore.ContentManagement.Records;
using OrchardCore.Data.Migration;
using YesSql.Sql;
namespace OrchardCore.ContentFields.Indexing.SQL
{
public class Migrations : DataMigration
{
public int Create()
{
// NOTE: The Text Length has been decreased from 4000 characters to 768.
// For existing SQL databases update the TextFieldIndex tables Text column length manually.
SchemaBuilder.CreateMapIndexTable<TextFieldIndex>(table => table
.Column<string>("ContentItemId", column => column.WithLength(26))
.Column<string>("ContentItemVersionId", column => column.WithLength(26))
.Column<string>("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize))
.Column<string>("ContentPart", column => column.WithLength(ContentItemIndex.MaxContentPartSize))
.Column<string>("ContentField", column => column.WithLength(ContentItemIndex.MaxContentFieldSize))
.Column<bool>("Published", column => column.Nullable())
.Column<bool>("Latest", column => column.Nullable())
.Column<string>("Text", column => column.Nullable().WithLength(TextFieldIndex.MaxTextSize))
.Column<string>("BigText", column => column.Nullable().Unlimited())
);
SchemaBuilder.AlterTable(nameof(TextFieldIndex), table => table
.CreateIndex("IDX_TextFieldIndex_ContentItemId", "ContentItemId")
);
SchemaBuilder.AlterTable(nameof(TextFieldIndex), table => table
.CreateIndex("IDX_TextFieldIndex_ContentItemVersionId", "ContentItemVersionId")
);
SchemaBuilder.AlterTable(nameof(TextFieldIndex), table => table
.CreateIndex("IDX_TextFieldIndex_ContentType", "ContentType")
);
SchemaBuilder.AlterTable(nameof(TextFieldIndex), table => table
.CreateIndex("IDX_TextFieldIndex_ContentPart", "ContentPart")
);
SchemaBuilder.AlterTable(nameof(TextFieldIndex), table => table
.CreateIndex("IDX_TextFieldIndex_ContentField", "ContentField")
);
SchemaBuilder.AlterTable(nameof(TextFieldIndex), table => table
.CreateIndex("IDX_TextFieldIndex_Published", "Published")
);
SchemaBuilder.AlterTable(nameof(TextFieldIndex), table => table
.CreateIndex("IDX_TextFieldIndex_Latest", "Latest")
);
SchemaBuilder.AlterTable(nameof(TextFieldIndex), table => table
.CreateIndex("IDX_TextFieldIndex_Text", "Text")
);
SchemaBuilder.CreateMapIndexTable<BooleanFieldIndex>(table => table
.Column<string>("ContentItemId", column => column.WithLength(26))
.Column<string>("ContentItemVersionId", column => column.WithLength(26))
.Column<string>("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize))
.Column<string>("ContentPart", column => column.WithLength(ContentItemIndex.MaxContentPartSize))
.Column<string>("ContentField", column => column.WithLength(ContentItemIndex.MaxContentFieldSize))
.Column<bool>("Published", column => column.Nullable())
.Column<bool>("Latest", column => column.Nullable())
.Column<bool>("Boolean", column => column.Nullable())
);
SchemaBuilder.AlterTable(nameof(BooleanFieldIndex), table => table
.CreateIndex("IDX_BooleanFieldIndex_ContentItemId", "ContentItemId")
);
SchemaBuilder.AlterTable(nameof(BooleanFieldIndex), table => table
.CreateIndex("IDX_BooleanFieldIndex_ContentItemVersionId", "ContentItemVersionId")
);
SchemaBuilder.AlterTable(nameof(BooleanFieldIndex), table => table
.CreateIndex("IDX_BooleanFieldIndex_ContentType", "ContentType")
);
SchemaBuilder.AlterTable(nameof(BooleanFieldIndex), table => table
.CreateIndex("IDX_BooleanFieldIndex_ContentPart", "ContentPart")
);
SchemaBuilder.AlterTable(nameof(BooleanFieldIndex), table => table
.CreateIndex("IDX_BooleanFieldIndex_ContentField", "ContentField")
);
SchemaBuilder.AlterTable(nameof(BooleanFieldIndex), table => table
.CreateIndex("IDX_BooleanFieldIndex_Published", "Published")
);
SchemaBuilder.AlterTable(nameof(BooleanFieldIndex), table => table
.CreateIndex("IDX_BooleanFieldIndex_Latest", "Latest")
);
SchemaBuilder.AlterTable(nameof(BooleanFieldIndex), table => table
.CreateIndex("IDX_BooleanFieldIndex_Boolean", "Boolean")
);
SchemaBuilder.CreateMapIndexTable<NumericFieldIndex>(table => table
.Column<string>("ContentItemId", column => column.WithLength(26))
.Column<string>("ContentItemVersionId", column => column.WithLength(26))
.Column<string>("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize))
.Column<string>("ContentPart", column => column.WithLength(ContentItemIndex.MaxContentPartSize))
.Column<string>("ContentField", column => column.WithLength(ContentItemIndex.MaxContentFieldSize))
.Column<bool>("Published", column => column.Nullable())
.Column<bool>("Latest", column => column.Nullable())
.Column<decimal>("Numeric", column => column.Nullable())
);
SchemaBuilder.AlterTable(nameof(NumericFieldIndex), table => table
.CreateIndex("IDX_NumericFieldIndex_ContentItemId", "ContentItemId")
);
SchemaBuilder.AlterTable(nameof(NumericFieldIndex), table => table
.CreateIndex("IDX_NumericFieldIndex_ContentItemVersionId", "ContentItemVersionId")
);
SchemaBuilder.AlterTable(nameof(NumericFieldIndex), table => table
.CreateIndex("IDX_NumericFieldIndex_ContentType", "ContentType")
);
SchemaBuilder.AlterTable(nameof(NumericFieldIndex), table => table
.CreateIndex("IDX_NumericFieldIndex_ContentPart", "ContentPart")
);
SchemaBuilder.AlterTable(nameof(NumericFieldIndex), table => table
.CreateIndex("IDX_NumericFieldIndex_ContentField", "ContentField")
);
SchemaBuilder.AlterTable(nameof(NumericFieldIndex), table => table
.CreateIndex("IDX_NumericFieldIndex_Published", "Published")
);
SchemaBuilder.AlterTable(nameof(NumericFieldIndex), table => table
.CreateIndex("IDX_NumericFieldIndex_Latest", "Latest")
);
SchemaBuilder.AlterTable(nameof(NumericFieldIndex), table => table
.CreateIndex("IDX_NumericFieldIndex_Numeric", "Numeric")
);
SchemaBuilder.CreateMapIndexTable<DateTimeFieldIndex>(table => table
.Column<string>("ContentItemId", column => column.WithLength(26))
.Column<string>("ContentItemVersionId", column => column.WithLength(26))
.Column<string>("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize))
.Column<string>("ContentPart", column => column.WithLength(ContentItemIndex.MaxContentPartSize))
.Column<string>("ContentField", column => column.WithLength(ContentItemIndex.MaxContentFieldSize))
.Column<bool>("Published", column => column.Nullable())
.Column<bool>("Latest", column => column.Nullable())
.Column<DateTime>("DateTime", column => column.Nullable())
);
SchemaBuilder.AlterTable(nameof(DateTimeFieldIndex), table => table
.CreateIndex("IDX_DateTimeFieldIndex_ContentItemId", "ContentItemId")
);
SchemaBuilder.AlterTable(nameof(DateTimeFieldIndex), table => table
.CreateIndex("IDX_DateTimeFieldIndex_ContentItemVersionId", "ContentItemVersionId")
);
SchemaBuilder.AlterTable(nameof(DateTimeFieldIndex), table => table
.CreateIndex("IDX_DateTimeFieldIndex_ContentType", "ContentType")
);
SchemaBuilder.AlterTable(nameof(DateTimeFieldIndex), table => table
.CreateIndex("IDX_DateTimeFieldIndex_ContentPart", "ContentPart")
);
SchemaBuilder.AlterTable(nameof(DateTimeFieldIndex), table => table
.CreateIndex("IDX_DateTimeFieldIndex_ContentField", "ContentField")
);
SchemaBuilder.AlterTable(nameof(DateTimeFieldIndex), table => table
.CreateIndex("IDX_DateTimeFieldIndex_Published", "Published")
);
SchemaBuilder.AlterTable(nameof(DateTimeFieldIndex), table => table
.CreateIndex("IDX_DateTimeFieldIndex_Latest", "Latest")
);
SchemaBuilder.AlterTable(nameof(DateTimeFieldIndex), table => table
.CreateIndex("IDX_DateTimeFieldIndex_DateTime", "DateTime")
);
SchemaBuilder.CreateMapIndexTable<DateFieldIndex>(table => table
.Column<string>("ContentItemId", column => column.WithLength(26))
.Column<string>("ContentItemVersionId", column => column.WithLength(26))
.Column<string>("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize))
.Column<string>("ContentPart", column => column.WithLength(ContentItemIndex.MaxContentPartSize))
.Column<string>("ContentField", column => column.WithLength(ContentItemIndex.MaxContentFieldSize))
.Column<bool>("Published", column => column.Nullable())
.Column<bool>("Latest", column => column.Nullable())
.Column<DateTime>("Date", column => column.Nullable())
);
SchemaBuilder.AlterTable(nameof(DateFieldIndex), table => table
.CreateIndex("IDX_DateFieldIndex_ContentItemId", "ContentItemId")
);
SchemaBuilder.AlterTable(nameof(DateFieldIndex), table => table
.CreateIndex("IDX_DateFieldIndex_ContentItemVersionId", "ContentItemVersionId")
);
SchemaBuilder.AlterTable(nameof(DateFieldIndex), table => table
.CreateIndex("IDX_DateFieldIndex_ContentType", "ContentType")
);
SchemaBuilder.AlterTable(nameof(DateFieldIndex), table => table
.CreateIndex("IDX_DateFieldIndex_ContentPart", "ContentPart")
);
SchemaBuilder.AlterTable(nameof(DateFieldIndex), table => table
.CreateIndex("IDX_DateFieldIndex_ContentField", "ContentField")
);
SchemaBuilder.AlterTable(nameof(DateFieldIndex), table => table
.CreateIndex("IDX_DateFieldIndex_Published", "Published")
);
SchemaBuilder.AlterTable(nameof(DateFieldIndex), table => table
.CreateIndex("IDX_DateFieldIndex_Latest", "Latest")
);
SchemaBuilder.AlterTable(nameof(DateFieldIndex), table => table
.CreateIndex("IDX_DateFieldIndex_Date", "Date")
);
SchemaBuilder.CreateMapIndexTable<ContentPickerFieldIndex>(table => table
.Column<string>("ContentItemId", column => column.WithLength(26))
.Column<string>("ContentItemVersionId", column => column.WithLength(26))
.Column<string>("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize))
.Column<string>("ContentPart", column => column.WithLength(ContentItemIndex.MaxContentPartSize))
.Column<string>("ContentField", column => column.WithLength(ContentItemIndex.MaxContentFieldSize))
.Column<bool>("Published", column => column.Nullable())
.Column<bool>("Latest", column => column.Nullable())
.Column<string>("SelectedContentItemId", column => column.WithLength(26))
);
SchemaBuilder.AlterTable(nameof(ContentPickerFieldIndex), table => table
.CreateIndex("IDX_ContentPickerFieldIndex_ContentItemId", "ContentItemId")
);
SchemaBuilder.AlterTable(nameof(ContentPickerFieldIndex), table => table
.CreateIndex("IDX_ContentPickerFieldIndex_ContentItemVersionId", "ContentItemVersionId")
);
SchemaBuilder.AlterTable(nameof(ContentPickerFieldIndex), table => table
.CreateIndex("IDX_ContentPickerFieldIndex_ContentType", "ContentType")
);
SchemaBuilder.AlterTable(nameof(ContentPickerFieldIndex), table => table
.CreateIndex("IDX_ContentPickerFieldIndex_ContentPart", "ContentPart")
);
SchemaBuilder.AlterTable(nameof(ContentPickerFieldIndex), table => table
.CreateIndex("IDX_ContentPickerFieldIndex_ContentField", "ContentField")
);
SchemaBuilder.AlterTable(nameof(ContentPickerFieldIndex), table => table
.CreateIndex("IDX_ContentPickerFieldIndex_Published", "Published")
);
SchemaBuilder.AlterTable(nameof(ContentPickerFieldIndex), table => table
.CreateIndex("IDX_ContentPickerFieldIndex_Latest", "Latest")
);
SchemaBuilder.AlterTable(nameof(ContentPickerFieldIndex), table => table
.CreateIndex("IDX_ContentPickerFieldIndex_SelectedContentItemId", "SelectedContentItemId")
);
SchemaBuilder.CreateMapIndexTable<TimeFieldIndex>(table => table
.Column<string>("ContentItemId", column => column.WithLength(26))
.Column<string>("ContentItemVersionId", column => column.WithLength(26))
.Column<string>("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize))
.Column<string>("ContentPart", column => column.WithLength(ContentItemIndex.MaxContentPartSize))
.Column<string>("ContentField", column => column.WithLength(ContentItemIndex.MaxContentFieldSize))
.Column<bool>("Published", column => column.Nullable())
.Column<bool>("Latest", column => column.Nullable())
.Column<DateTime>("Time", column => column.Nullable())
);
SchemaBuilder.AlterTable(nameof(TimeFieldIndex), table => table
.CreateIndex("IDX_TimeFieldIndex_ContentItemId", "ContentItemId")
);
SchemaBuilder.AlterTable(nameof(TimeFieldIndex), table => table
.CreateIndex("IDX_TimeFieldIndex_ContentItemVersionId", "ContentItemVersionId")
);
SchemaBuilder.AlterTable(nameof(TimeFieldIndex), table => table
.CreateIndex("IDX_TimeFieldIndex_ContentType", "ContentType")
);
SchemaBuilder.AlterTable(nameof(TimeFieldIndex), table => table
.CreateIndex("IDX_TimeFieldIndex_ContentPart", "ContentPart")
);
SchemaBuilder.AlterTable(nameof(TimeFieldIndex), table => table
.CreateIndex("IDX_TimeFieldIndex_ContentField", "ContentField")
);
SchemaBuilder.AlterTable(nameof(TimeFieldIndex), table => table
.CreateIndex("IDX_TimeFieldIndex_Published", "Published")
);
SchemaBuilder.AlterTable(nameof(TimeFieldIndex), table => table
.CreateIndex("IDX_TimeFieldIndex_Latest", "Latest")
);
SchemaBuilder.AlterTable(nameof(TimeFieldIndex), table => table
.CreateIndex("IDX_TimeFieldIndex_Time", "Time")
);
// NOTE: The Url and Text Length has been decreased from 4000 characters to 768.
// For existing SQL databases update the LinkFieldIndex tables Url and Text column length manually.
// The BigText and BigUrl columns are new additions so will not be populated until the content item is republished.
SchemaBuilder.CreateMapIndexTable<LinkFieldIndex>(table => table
.Column<string>("ContentItemId", column => column.WithLength(26))
.Column<string>("ContentItemVersionId", column => column.WithLength(26))
.Column<string>("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize))
.Column<string>("ContentPart", column => column.WithLength(ContentItemIndex.MaxContentPartSize))
.Column<string>("ContentField", column => column.WithLength(ContentItemIndex.MaxContentFieldSize))
.Column<bool>("Published", column => column.Nullable())
.Column<bool>("Latest", column => column.Nullable())
.Column<string>("Url", column => column.Nullable().WithLength(LinkFieldIndex.MaxUrlSize))
.Column<string>("BigUrl", column => column.Nullable().Unlimited())
.Column<string>("Text", column => column.Nullable().WithLength(LinkFieldIndex.MaxTextSize))
.Column<string>("BigText", column => column.Nullable().Unlimited())
);
SchemaBuilder.AlterTable(nameof(LinkFieldIndex), table => table
.CreateIndex("IDX_LinkFieldIndex_ContentItemId", "ContentItemId")
);
SchemaBuilder.AlterTable(nameof(LinkFieldIndex), table => table
.CreateIndex("IDX_LinkFieldIndex_ContentItemVersionId", "ContentItemVersionId")
);
SchemaBuilder.AlterTable(nameof(LinkFieldIndex), table => table
.CreateIndex("IDX_LinkFieldIndex_ContentType", "ContentType")
);
SchemaBuilder.AlterTable(nameof(LinkFieldIndex), table => table
.CreateIndex("IDX_LinkFieldIndex_ContentPart", "ContentPart")
);
SchemaBuilder.AlterTable(nameof(LinkFieldIndex), table => table
.CreateIndex("IDX_LinkFieldIndex_ContentField", "ContentField")
);
SchemaBuilder.AlterTable(nameof(LinkFieldIndex), table => table
.CreateIndex("IDX_LinkFieldIndex_Published", "Published")
);
SchemaBuilder.AlterTable(nameof(LinkFieldIndex), table => table
.CreateIndex("IDX_LinkFieldIndex_Latest", "Latest")
);
SchemaBuilder.AlterTable(nameof(LinkFieldIndex), table => table
.CreateIndex("IDX_LinkFieldIndex_Url", "Url")
);
SchemaBuilder.AlterTable(nameof(LinkFieldIndex), table => table
.CreateIndex("IDX_LinkFieldIndex_Text", "Text")
);
SchemaBuilder.CreateMapIndexTable<HtmlFieldIndex>(table => table
.Column<string>("ContentItemId", column => column.WithLength(26))
.Column<string>("ContentItemVersionId", column => column.WithLength(26))
.Column<string>("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize))
.Column<string>("ContentPart", column => column.WithLength(ContentItemIndex.MaxContentPartSize))
.Column<string>("ContentField", column => column.WithLength(ContentItemIndex.MaxContentFieldSize))
.Column<bool>("Published", column => column.Nullable())
.Column<bool>("Latest", column => column.Nullable())
.Column<string>("Html", column => column.Nullable().Unlimited())
);
SchemaBuilder.AlterTable(nameof(HtmlFieldIndex), table => table
.CreateIndex("IDX_HtmlFieldIndex_ContentItemId", "ContentItemId")
);
SchemaBuilder.AlterTable(nameof(HtmlFieldIndex), table => table
.CreateIndex("IDX_HtmlFieldIndex_ContentItemVersionId", "ContentItemVersionId")
);
SchemaBuilder.AlterTable(nameof(HtmlFieldIndex), table => table
.CreateIndex("IDX_HtmlFieldIndex_ContentType", "ContentType")
);
SchemaBuilder.AlterTable(nameof(HtmlFieldIndex), table => table
.CreateIndex("IDX_HtmlFieldIndex_ContentPart", "ContentPart")
);
SchemaBuilder.AlterTable(nameof(HtmlFieldIndex), table => table
.CreateIndex("IDX_HtmlFieldIndex_ContentField", "ContentField")
);
SchemaBuilder.AlterTable(nameof(HtmlFieldIndex), table => table
.CreateIndex("IDX_HtmlFieldIndex_Published", "Published")
);
SchemaBuilder.AlterTable(nameof(HtmlFieldIndex), table => table
.CreateIndex("IDX_HtmlFieldIndex_Latest", "Latest")
);
// Return 2 to shorcut migrations on new installations.
return 2;
}
public int UpdateFrom1()
{
SchemaBuilder.AlterTable(nameof(LinkFieldIndex), table => table
.AddColumn<string>("BigUrl", column => column.Nullable().Unlimited()));
SchemaBuilder.AlterTable(nameof(LinkFieldIndex), table => table
.AddColumn<string>("BigText", column => column.Nullable().Unlimited()));
return 2;
}
}
}
| |
/*
* 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 OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Services.Interfaces;
using System;
using System.Collections;
using System.Net;
using System.Reflection;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
namespace OpenSim.Server.Handlers.Simulation
{
public class ObjectHandler
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private ISimulationService m_SimulationService;
public ObjectHandler() { }
public ObjectHandler(ISimulationService sim)
{
m_SimulationService = sim;
}
public Hashtable Handler(Hashtable request)
{
//m_log.Debug("[CONNECTION DEBUGGING]: ObjectHandler Called");
//m_log.Debug("---------------------------");
//m_log.Debug(" >> uri=" + request["uri"]);
//m_log.Debug(" >> content-type=" + request["content-type"]);
//m_log.Debug(" >> http-method=" + request["http-method"]);
//m_log.Debug("---------------------------\n");
Hashtable responsedata = new Hashtable();
responsedata["content_type"] = "text/html";
UUID objectID;
UUID regionID;
string action;
if (!Utils.GetParams((string)request["uri"], out objectID, out regionID, out action))
{
m_log.InfoFormat("[OBJECT HANDLER]: Invalid parameters for object message {0}", request["uri"]);
responsedata["int_response_code"] = 404;
responsedata["str_response_string"] = "false";
return responsedata;
}
try
{
// Next, let's parse the verb
string method = (string)request["http-method"];
if (method.Equals("POST"))
{
DoObjectPost(request, responsedata, regionID);
return responsedata;
}
//else if (method.Equals("DELETE"))
//{
// DoObjectDelete(request, responsedata, agentID, action, regionHandle);
// return responsedata;
//}
else
{
m_log.InfoFormat("[OBJECT HANDLER]: method {0} not supported in object message", method);
responsedata["int_response_code"] = HttpStatusCode.MethodNotAllowed;
responsedata["str_response_string"] = "Method not allowed";
return responsedata;
}
}
catch (Exception e)
{
m_log.WarnFormat("[OBJECT HANDLER]: Caught exception {0}", e.StackTrace);
responsedata["int_response_code"] = HttpStatusCode.InternalServerError;
responsedata["str_response_string"] = "Internal server error";
return responsedata;
}
}
protected void DoObjectPost(Hashtable request, Hashtable responsedata, UUID regionID)
{
OSDMap args = Utils.GetOSDMap((string)request["body"]);
if (args == null)
{
responsedata["int_response_code"] = 400;
responsedata["str_response_string"] = "false";
return;
}
// retrieve the input arguments
int x = 0, y = 0;
UUID uuid = UUID.Zero;
string regionname = string.Empty;
Vector3 newPosition = Vector3.Zero;
if (args.ContainsKey("destination_x") && args["destination_x"] != null)
Int32.TryParse(args["destination_x"].AsString(), out x);
if (args.ContainsKey("destination_y") && args["destination_y"] != null)
Int32.TryParse(args["destination_y"].AsString(), out y);
if (args.ContainsKey("destination_uuid") && args["destination_uuid"] != null)
UUID.TryParse(args["destination_uuid"].AsString(), out uuid);
if (args.ContainsKey("destination_name") && args["destination_name"] != null)
regionname = args["destination_name"].ToString();
if (args.ContainsKey("new_position") && args["new_position"] != null)
Vector3.TryParse(args["new_position"], out newPosition);
GridRegion destination = new GridRegion();
destination.RegionID = uuid;
destination.RegionLocX = x;
destination.RegionLocY = y;
destination.RegionName = regionname;
string sogXmlStr = "", extraStr = "", stateXmlStr = "";
if (args.ContainsKey("sog") && args["sog"] != null)
sogXmlStr = args["sog"].AsString();
if (args.ContainsKey("extra") && args["extra"] != null)
extraStr = args["extra"].AsString();
IScene s = m_SimulationService.GetScene(destination.RegionID);
ISceneObject sog = null;
try
{
//m_log.DebugFormat("[OBJECT HANDLER]: received {0}", sogXmlStr);
sog = s.DeserializeObject(sogXmlStr);
sog.ExtraFromXmlString(extraStr);
}
catch (Exception ex)
{
m_log.InfoFormat("[OBJECT HANDLER]: exception on deserializing scene object {0}", ex.Message);
responsedata["int_response_code"] = HttpStatusCode.BadRequest;
responsedata["str_response_string"] = "Bad request";
return;
}
if (args.ContainsKey("modified"))
sog.HasGroupChanged = args["modified"].AsBoolean();
else
sog.HasGroupChanged = false;
if ((args["state"] != null) && s.AllowScriptCrossings)
{
stateXmlStr = args["state"].AsString();
if (stateXmlStr != "")
{
try
{
sog.SetState(stateXmlStr, s);
}
catch (Exception ex)
{
m_log.InfoFormat("[OBJECT HANDLER]: exception on setting state for scene object {0}", ex.Message);
// ignore and continue
}
}
}
bool result = false;
try
{
// This is the meaning of POST object
result = CreateObject(destination, newPosition, sog);
}
catch (Exception e)
{
m_log.DebugFormat("[OBJECT HANDLER]: Exception in CreateObject: {0}", e.StackTrace);
}
responsedata["int_response_code"] = HttpStatusCode.OK;
responsedata["str_response_string"] = result.ToString();
}
// subclasses can override this
protected virtual bool CreateObject(GridRegion destination, Vector3 newPosition, ISceneObject sog)
{
return m_SimulationService.CreateObject(destination, newPosition, sog, false);
}
}
}
| |
namespace XenAdmin.Dialogs
{
partial class VIFDialog
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(VIFDialog));
this.Cancelbutton = new System.Windows.Forms.Button();
this.buttonOk = new System.Windows.Forms.Button();
this.promptTextBoxMac = new System.Windows.Forms.TextBox();
this.radioButtonAutogenerate = new System.Windows.Forms.RadioButton();
this.radioButtonMac = new System.Windows.Forms.RadioButton();
this.tableLayoutPanelBody = new System.Windows.Forms.TableLayoutPanel();
this.labelBlurb = new System.Windows.Forms.Label();
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.labelNetwork = new System.Windows.Forms.Label();
this.comboBoxNetwork = new System.Windows.Forms.ComboBox();
this.labelMAC = new System.Windows.Forms.Label();
this.tableLayoutPanelMAC = new System.Windows.Forms.TableLayoutPanel();
this.labelQoS = new System.Windows.Forms.Label();
this.tableLayoutPanel3 = new System.Windows.Forms.TableLayoutPanel();
this.labelQoSUnits = new System.Windows.Forms.Label();
this.promptTextBoxQoS = new System.Windows.Forms.TextBox();
this.checkboxQoS = new System.Windows.Forms.CheckBox();
this.tableLayoutPanelInfo = new System.Windows.Forms.TableLayoutPanel();
this.labelInfo = new System.Windows.Forms.Label();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.tableLayoutPanelError = new System.Windows.Forms.TableLayoutPanel();
this.pictureBoxError = new System.Windows.Forms.PictureBox();
this.labelError = new System.Windows.Forms.Label();
this.tableLayoutpanelButtons = new System.Windows.Forms.TableLayoutPanel();
this.tableLayoutPanelBody.SuspendLayout();
this.tableLayoutPanel1.SuspendLayout();
this.tableLayoutPanelMAC.SuspendLayout();
this.tableLayoutPanel3.SuspendLayout();
this.tableLayoutPanelInfo.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.tableLayoutPanelError.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxError)).BeginInit();
this.tableLayoutpanelButtons.SuspendLayout();
this.SuspendLayout();
//
// Cancelbutton
//
this.Cancelbutton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
resources.ApplyResources(this.Cancelbutton, "Cancelbutton");
this.Cancelbutton.Name = "Cancelbutton";
this.Cancelbutton.UseVisualStyleBackColor = true;
//
// buttonOk
//
this.buttonOk.DialogResult = System.Windows.Forms.DialogResult.OK;
resources.ApplyResources(this.buttonOk, "buttonOk");
this.buttonOk.Name = "buttonOk";
this.buttonOk.UseVisualStyleBackColor = true;
//
// promptTextBoxMac
//
resources.ApplyResources(this.promptTextBoxMac, "promptTextBoxMac");
this.promptTextBoxMac.Name = "promptTextBoxMac";
this.promptTextBoxMac.TextChanged += new System.EventHandler(this.promptTextBoxMac_TextChanged);
this.promptTextBoxMac.Enter += new System.EventHandler(this.promptTextBoxMac_Enter);
//
// radioButtonAutogenerate
//
resources.ApplyResources(this.radioButtonAutogenerate, "radioButtonAutogenerate");
this.tableLayoutPanelMAC.SetColumnSpan(this.radioButtonAutogenerate, 2);
this.radioButtonAutogenerate.Name = "radioButtonAutogenerate";
this.radioButtonAutogenerate.CheckedChanged += new System.EventHandler(this.radioButtonAutogenerate_CheckedChanged);
//
// radioButtonMac
//
resources.ApplyResources(this.radioButtonMac, "radioButtonMac");
this.radioButtonMac.Name = "radioButtonMac";
this.radioButtonMac.UseVisualStyleBackColor = true;
this.radioButtonMac.CheckedChanged += new System.EventHandler(this.radioButtonMac_CheckedChanged);
//
// tableLayoutPanelBody
//
resources.ApplyResources(this.tableLayoutPanelBody, "tableLayoutPanelBody");
this.tableLayoutPanelBody.Controls.Add(this.labelBlurb, 0, 0);
this.tableLayoutPanelBody.Controls.Add(this.tableLayoutPanel1, 0, 1);
this.tableLayoutPanelBody.Controls.Add(this.labelMAC, 0, 2);
this.tableLayoutPanelBody.Controls.Add(this.tableLayoutPanelMAC, 0, 3);
this.tableLayoutPanelBody.Controls.Add(this.labelQoS, 0, 4);
this.tableLayoutPanelBody.Controls.Add(this.tableLayoutPanel3, 0, 5);
this.tableLayoutPanelBody.Controls.Add(this.tableLayoutPanelInfo, 0, 6);
this.tableLayoutPanelBody.Controls.Add(this.tableLayoutPanelError, 0, 7);
this.tableLayoutPanelBody.Controls.Add(this.tableLayoutpanelButtons, 0, 8);
this.tableLayoutPanelBody.Name = "tableLayoutPanelBody";
//
// labelBlurb
//
resources.ApplyResources(this.labelBlurb, "labelBlurb");
this.labelBlurb.Name = "labelBlurb";
//
// tableLayoutPanel1
//
resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1");
this.tableLayoutPanel1.Controls.Add(this.labelNetwork, 0, 0);
this.tableLayoutPanel1.Controls.Add(this.comboBoxNetwork, 1, 0);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
//
// labelNetwork
//
resources.ApplyResources(this.labelNetwork, "labelNetwork");
this.labelNetwork.Name = "labelNetwork";
//
// comboBoxNetwork
//
resources.ApplyResources(this.comboBoxNetwork, "comboBoxNetwork");
this.comboBoxNetwork.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxNetwork.FormattingEnabled = true;
this.comboBoxNetwork.Name = "comboBoxNetwork";
this.comboBoxNetwork.SelectedIndexChanged += new System.EventHandler(this.comboBoxNetwork_SelectedIndexChanged);
//
// labelMAC
//
resources.ApplyResources(this.labelMAC, "labelMAC");
this.labelMAC.Name = "labelMAC";
//
// tableLayoutPanelMAC
//
resources.ApplyResources(this.tableLayoutPanelMAC, "tableLayoutPanelMAC");
this.tableLayoutPanelMAC.Controls.Add(this.radioButtonAutogenerate, 0, 0);
this.tableLayoutPanelMAC.Controls.Add(this.radioButtonMac, 0, 1);
this.tableLayoutPanelMAC.Controls.Add(this.promptTextBoxMac, 1, 1);
this.tableLayoutPanelMAC.Name = "tableLayoutPanelMAC";
//
// labelQoS
//
resources.ApplyResources(this.labelQoS, "labelQoS");
this.labelQoS.Name = "labelQoS";
//
// tableLayoutPanel3
//
resources.ApplyResources(this.tableLayoutPanel3, "tableLayoutPanel3");
this.tableLayoutPanel3.Controls.Add(this.labelQoSUnits, 2, 0);
this.tableLayoutPanel3.Controls.Add(this.promptTextBoxQoS, 1, 0);
this.tableLayoutPanel3.Controls.Add(this.checkboxQoS, 0, 0);
this.tableLayoutPanel3.Name = "tableLayoutPanel3";
//
// labelQoSUnits
//
resources.ApplyResources(this.labelQoSUnits, "labelQoSUnits");
this.labelQoSUnits.Name = "labelQoSUnits";
//
// promptTextBoxQoS
//
resources.ApplyResources(this.promptTextBoxQoS, "promptTextBoxQoS");
this.promptTextBoxQoS.Name = "promptTextBoxQoS";
this.promptTextBoxQoS.TextChanged += new System.EventHandler(this.promptTextBoxQoS_TextChanged);
this.promptTextBoxQoS.Enter += new System.EventHandler(this.promptTextBoxQoS_Enter);
//
// checkboxQoS
//
resources.ApplyResources(this.checkboxQoS, "checkboxQoS");
this.checkboxQoS.Name = "checkboxQoS";
this.checkboxQoS.UseVisualStyleBackColor = true;
this.checkboxQoS.CheckedChanged += new System.EventHandler(this.checkboxQoS_CheckedChanged);
//
// tableLayoutPanelInfo
//
resources.ApplyResources(this.tableLayoutPanelInfo, "tableLayoutPanelInfo");
this.tableLayoutPanelInfo.Controls.Add(this.labelInfo, 1, 0);
this.tableLayoutPanelInfo.Controls.Add(this.pictureBox1, 0, 0);
this.tableLayoutPanelInfo.Name = "tableLayoutPanelInfo";
//
// labelInfo
//
resources.ApplyResources(this.labelInfo, "labelInfo");
this.labelInfo.Name = "labelInfo";
//
// pictureBox1
//
resources.ApplyResources(this.pictureBox1, "pictureBox1");
this.pictureBox1.Image = global::XenAdmin.Properties.Resources._000_Info3_h32bit_16;
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.TabStop = false;
//
// tableLayoutPanelError
//
resources.ApplyResources(this.tableLayoutPanelError, "tableLayoutPanelError");
this.tableLayoutPanelError.Controls.Add(this.pictureBoxError, 0, 0);
this.tableLayoutPanelError.Controls.Add(this.labelError, 1, 0);
this.tableLayoutPanelError.Name = "tableLayoutPanelError";
//
// pictureBoxError
//
resources.ApplyResources(this.pictureBoxError, "pictureBoxError");
this.pictureBoxError.Image = global::XenAdmin.Properties.Resources._000_error_h32bit_16;
this.pictureBoxError.Name = "pictureBoxError";
this.pictureBoxError.TabStop = false;
//
// labelError
//
resources.ApplyResources(this.labelError, "labelError");
this.labelError.Name = "labelError";
//
// tableLayoutpanelButtons
//
resources.ApplyResources(this.tableLayoutpanelButtons, "tableLayoutpanelButtons");
this.tableLayoutpanelButtons.Controls.Add(this.buttonOk, 0, 0);
this.tableLayoutpanelButtons.Controls.Add(this.Cancelbutton, 1, 0);
this.tableLayoutpanelButtons.Name = "tableLayoutpanelButtons";
//
// VIFDialog
//
this.AcceptButton = this.buttonOk;
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.CancelButton = this.Cancelbutton;
this.Controls.Add(this.tableLayoutPanelBody);
this.Name = "VIFDialog";
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.VIFDialog_FormClosing);
this.tableLayoutPanelBody.ResumeLayout(false);
this.tableLayoutPanelBody.PerformLayout();
this.tableLayoutPanel1.ResumeLayout(false);
this.tableLayoutPanel1.PerformLayout();
this.tableLayoutPanelMAC.ResumeLayout(false);
this.tableLayoutPanelMAC.PerformLayout();
this.tableLayoutPanel3.ResumeLayout(false);
this.tableLayoutPanel3.PerformLayout();
this.tableLayoutPanelInfo.ResumeLayout(false);
this.tableLayoutPanelInfo.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.tableLayoutPanelError.ResumeLayout(false);
this.tableLayoutPanelError.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxError)).EndInit();
this.tableLayoutpanelButtons.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button Cancelbutton;
private System.Windows.Forms.Button buttonOk;
private System.Windows.Forms.TextBox promptTextBoxMac;
private System.Windows.Forms.RadioButton radioButtonAutogenerate;
private System.Windows.Forms.RadioButton radioButtonMac;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanelBody;
private System.Windows.Forms.Label labelBlurb;
private System.Windows.Forms.Label labelMAC;
private System.Windows.Forms.Label labelQoS;
private System.Windows.Forms.Label labelQoSUnits;
private System.Windows.Forms.CheckBox checkboxQoS;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanelMAC;
private System.Windows.Forms.TextBox promptTextBoxQoS;
private System.Windows.Forms.TableLayoutPanel tableLayoutpanelButtons;
private System.Windows.Forms.Label labelNetwork;
private System.Windows.Forms.ComboBox comboBoxNetwork;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanelInfo;
private System.Windows.Forms.Label labelInfo;
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel3;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanelError;
private System.Windows.Forms.PictureBox pictureBoxError;
private System.Windows.Forms.Label labelError;
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using Orleans.CodeGeneration;
namespace Orleans.Runtime
{
/// <summary>
/// A collection of utility functions for dealing with Type information.
/// </summary>
internal static class TypeUtils
{
/// <summary>
/// The assembly name of the core Orleans assembly.
/// </summary>
private static readonly AssemblyName OrleansCoreAssembly = typeof(IGrain).GetTypeInfo().Assembly.GetName();
private static readonly ConcurrentDictionary<Tuple<Type, TypeFormattingOptions>, string> ParseableNameCache = new ConcurrentDictionary<Tuple<Type, TypeFormattingOptions>, string>();
private static readonly ConcurrentDictionary<Tuple<Type, bool>, List<Type>> ReferencedTypes = new ConcurrentDictionary<Tuple<Type, bool>, List<Type>>();
public static string GetSimpleTypeName(Type t, Predicate<Type> fullName = null)
{
return GetSimpleTypeName(t.GetTypeInfo(), fullName);
}
public static string GetSimpleTypeName(TypeInfo typeInfo, Predicate<Type> fullName = null)
{
if (typeInfo.IsNestedPublic || typeInfo.IsNestedPrivate)
{
if (typeInfo.DeclaringType.GetTypeInfo().IsGenericType)
{
return GetTemplatedName(
GetUntemplatedTypeName(typeInfo.DeclaringType.Name),
typeInfo.DeclaringType,
typeInfo.GetGenericArguments(),
_ => true) + "." + GetUntemplatedTypeName(typeInfo.Name);
}
return GetTemplatedName(typeInfo.DeclaringType) + "." + GetUntemplatedTypeName(typeInfo.Name);
}
var type = typeInfo.AsType();
if (typeInfo.IsGenericType) return GetSimpleTypeName(fullName != null && fullName(type) ? GetFullName(type) : typeInfo.Name);
return fullName != null && fullName(type) ? GetFullName(type) : typeInfo.Name;
}
public static string GetUntemplatedTypeName(string typeName)
{
int i = typeName.IndexOf('`');
if (i > 0)
{
typeName = typeName.Substring(0, i);
}
i = typeName.IndexOf('<');
if (i > 0)
{
typeName = typeName.Substring(0, i);
}
return typeName;
}
public static string GetSimpleTypeName(string typeName)
{
int i = typeName.IndexOf('`');
if (i > 0)
{
typeName = typeName.Substring(0, i);
}
i = typeName.IndexOf('[');
if (i > 0)
{
typeName = typeName.Substring(0, i);
}
i = typeName.IndexOf('<');
if (i > 0)
{
typeName = typeName.Substring(0, i);
}
return typeName;
}
public static bool IsConcreteTemplateType(Type t)
{
if (t.GetTypeInfo().IsGenericType) return true;
return t.IsArray && IsConcreteTemplateType(t.GetElementType());
}
public static string GetTemplatedName(Type t, Predicate<Type> fullName = null)
{
if (fullName == null)
fullName = _ => true; // default to full type names
var typeInfo = t.GetTypeInfo();
if (typeInfo.IsGenericType) return GetTemplatedName(GetSimpleTypeName(typeInfo, fullName), t, typeInfo.GetGenericArguments(), fullName);
if (t.IsArray)
{
return GetTemplatedName(t.GetElementType(), fullName)
+ "["
+ new string(',', t.GetArrayRank() - 1)
+ "]";
}
return GetSimpleTypeName(typeInfo, fullName);
}
public static bool IsConstructedGenericType(this TypeInfo typeInfo)
{
// is there an API that returns this info without converting back to type already?
return typeInfo.AsType().IsConstructedGenericType;
}
internal static IEnumerable<TypeInfo> GetTypeInfos(this Type[] types)
{
return types.Select(t => t.GetTypeInfo());
}
public static string GetTemplatedName(string baseName, Type t, Type[] genericArguments, Predicate<Type> fullName)
{
var typeInfo = t.GetTypeInfo();
if (!typeInfo.IsGenericType || (t.DeclaringType != null && t.DeclaringType.GetTypeInfo().IsGenericType)) return baseName;
string s = baseName;
s += "<";
s += GetGenericTypeArgs(genericArguments, fullName);
s += ">";
return s;
}
public static string GetGenericTypeArgs(IEnumerable<Type> args, Predicate<Type> fullName)
{
string s = string.Empty;
bool first = true;
foreach (var genericParameter in args)
{
if (!first)
{
s += ",";
}
if (!genericParameter.GetTypeInfo().IsGenericType)
{
s += GetSimpleTypeName(genericParameter, fullName);
}
else
{
s += GetTemplatedName(genericParameter, fullName);
}
first = false;
}
return s;
}
public static string GetParameterizedTemplateName(TypeInfo typeInfo, bool applyRecursively = false, Predicate<Type> fullName = null)
{
if (fullName == null)
fullName = tt => true;
return GetParameterizedTemplateName(typeInfo, fullName, applyRecursively);
}
public static string GetParameterizedTemplateName(TypeInfo typeInfo, Predicate<Type> fullName, bool applyRecursively = false)
{
if (typeInfo.IsGenericType)
{
return GetParameterizedTemplateName(GetSimpleTypeName(typeInfo, fullName), typeInfo, applyRecursively, fullName);
}
var t = typeInfo.AsType();
if (fullName != null && fullName(t) == true)
{
return t.FullName;
}
return t.Name;
}
public static string GetParameterizedTemplateName(string baseName, TypeInfo typeInfo, bool applyRecursively = false, Predicate<Type> fullName = null)
{
if (fullName == null)
fullName = tt => false;
if (!typeInfo.IsGenericType) return baseName;
string s = baseName;
s += "<";
bool first = true;
foreach (var genericParameter in typeInfo.GetGenericArguments())
{
if (!first)
{
s += ",";
}
var genericParameterTypeInfo = genericParameter.GetTypeInfo();
if (applyRecursively && genericParameterTypeInfo.IsGenericType)
{
s += GetParameterizedTemplateName(genericParameterTypeInfo, applyRecursively);
}
else
{
s += genericParameter.FullName == null || !fullName(genericParameter)
? genericParameter.Name
: genericParameter.FullName;
}
first = false;
}
s += ">";
return s;
}
public static string GetRawClassName(string baseName, Type t)
{
var typeInfo = t.GetTypeInfo();
return typeInfo.IsGenericType ? baseName + '`' + typeInfo.GetGenericArguments().Length : baseName;
}
public static string GetRawClassName(string typeName)
{
int i = typeName.IndexOf('[');
return i <= 0 ? typeName : typeName.Substring(0, i);
}
public static Type[] GenericTypeArgsFromClassName(string className)
{
return GenericTypeArgsFromArgsString(GenericTypeArgsString(className));
}
public static Type[] GenericTypeArgsFromArgsString(string genericArgs)
{
if (string.IsNullOrEmpty(genericArgs)) return new Type[] { };
var genericTypeDef = genericArgs.Replace("[]", "##"); // protect array arguments
return InnerGenericTypeArgs(genericTypeDef);
}
private static Type[] InnerGenericTypeArgs(string className)
{
var typeArgs = new List<Type>();
var innerTypes = GetInnerTypes(className);
foreach (var innerType in innerTypes)
{
if (innerType.StartsWith("[[")) // Resolve and load generic types recursively
{
InnerGenericTypeArgs(GenericTypeArgsString(innerType));
string genericTypeArg = className.Trim('[', ']');
typeArgs.Add(Type.GetType(genericTypeArg.Replace("##", "[]")));
}
else
{
string nonGenericTypeArg = innerType.Trim('[', ']');
typeArgs.Add(Type.GetType(nonGenericTypeArg.Replace("##", "[]")));
}
}
return typeArgs.ToArray();
}
private static string[] GetInnerTypes(string input)
{
// Iterate over strings of length 2 positionwise.
var charsWithPositions = input.Zip(Enumerable.Range(0, input.Length), (c, i) => new { Ch = c, Pos = i });
var candidatesWithPositions = charsWithPositions.Zip(charsWithPositions.Skip(1), (c1, c2) => new { Str = c1.Ch.ToString() + c2.Ch, Pos = c1.Pos });
var results = new List<string>();
int startPos = -1;
int endPos = -1;
int endTokensNeeded = 0;
string curStartToken = "";
string curEndToken = "";
var tokenPairs = new[] { new { Start = "[[", End = "]]" }, new { Start = "[", End = "]" } }; // Longer tokens need to come before shorter ones
foreach (var candidate in candidatesWithPositions)
{
if (startPos == -1)
{
foreach (var token in tokenPairs)
{
if (candidate.Str.StartsWith(token.Start))
{
curStartToken = token.Start;
curEndToken = token.End;
startPos = candidate.Pos;
break;
}
}
}
if (curStartToken != "" && candidate.Str.StartsWith(curStartToken))
endTokensNeeded++;
if (curEndToken != "" && candidate.Str.EndsWith(curEndToken))
{
endPos = candidate.Pos;
endTokensNeeded--;
}
if (endTokensNeeded == 0 && startPos != -1)
{
results.Add(input.Substring(startPos, endPos - startPos + 2));
startPos = -1;
curStartToken = "";
}
}
return results.ToArray();
}
public static string GenericTypeArgsString(string className)
{
int startIndex = className.IndexOf('[');
int endIndex = className.LastIndexOf(']');
return className.Substring(startIndex + 1, endIndex - startIndex - 1);
}
public static bool IsGenericClass(string name)
{
return name.Contains("`") || name.Contains("[");
}
public static string GetFullName(TypeInfo typeInfo)
{
if (typeInfo == null) throw new ArgumentNullException(nameof(typeInfo));
return GetFullName(typeInfo.AsType());
}
public static string GetFullName(Type t)
{
if (t == null) throw new ArgumentNullException(nameof(t));
if (t.IsNested && !t.IsGenericParameter)
{
return t.Namespace + "." + t.DeclaringType.Name + "." + t.Name;
}
if (t.IsArray)
{
return GetFullName(t.GetElementType())
+ "["
+ new string(',', t.GetArrayRank() - 1)
+ "]";
}
return t.FullName ?? (t.IsGenericParameter ? t.Name : t.Namespace + "." + t.Name);
}
/// <summary>
/// Returns all fields of the specified type.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>All fields of the specified type.</returns>
public static IEnumerable<FieldInfo> GetAllFields(this Type type)
{
const BindingFlags AllFields =
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly;
var current = type;
while ((current != typeof(object)) && (current != null))
{
var fields = current.GetFields(AllFields);
foreach (var field in fields)
{
yield return field;
}
current = current.GetTypeInfo().BaseType;
}
}
/// <summary>
/// decide whether the class is derived from Grain
/// </summary>
public static bool IsGrainClass(Type type)
{
var grainType = typeof(Grain);
var grainChevronType = typeof(Grain<>);
#if !NETSTANDARD
if (type.Assembly.ReflectionOnly)
{
grainType = ToReflectionOnlyType(grainType);
grainChevronType = ToReflectionOnlyType(grainChevronType);
}
#endif
if (grainType == type || grainChevronType == type) return false;
if (!grainType.IsAssignableFrom(type)) return false;
// exclude generated classes.
return !IsGeneratedType(type);
}
public static bool IsConcreteGrainClass(Type type, out IEnumerable<string> complaints, bool complain)
{
complaints = null;
if (!IsGrainClass(type)) return false;
if (!type.GetTypeInfo().IsAbstract) return true;
complaints = complain ? new[] { string.Format("Grain type {0} is abstract and cannot be instantiated.", type.FullName) } : null;
return false;
}
public static bool IsConcreteGrainClass(Type type, out IEnumerable<string> complaints)
{
return IsConcreteGrainClass(type, out complaints, complain: true);
}
public static bool IsConcreteGrainClass(Type type)
{
IEnumerable<string> complaints;
return IsConcreteGrainClass(type, out complaints, complain: false);
}
public static bool IsGeneratedType(Type type)
{
return TypeHasAttribute(type, typeof(GeneratedAttribute));
}
/// <summary>
/// Returns true if the provided <paramref name="type"/> is in any of the provided
/// <paramref name="namespaces"/>, false otherwise.
/// </summary>
/// <param name="type">The type to check.</param>
/// <param name="namespaces"></param>
/// <returns>
/// true if the provided <paramref name="type"/> is in any of the provided <paramref name="namespaces"/>, false
/// otherwise.
/// </returns>
public static bool IsInNamespace(Type type, List<string> namespaces)
{
if (type.Namespace == null)
{
return false;
}
foreach (var ns in namespaces)
{
if (ns.Length > type.Namespace.Length)
{
continue;
}
// If the candidate namespace is a prefix of the type's namespace, return true.
if (type.Namespace.StartsWith(ns, StringComparison.Ordinal)
&& (type.Namespace.Length == ns.Length || type.Namespace[ns.Length] == '.'))
{
return true;
}
}
return false;
}
/// <summary>
/// Returns true if <paramref name="type"/> has implementations of all serialization methods, false otherwise.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>
/// true if <paramref name="type"/> has implementations of all serialization methods, false otherwise.
/// </returns>
public static bool HasAllSerializationMethods(Type type)
{
// Check if the type has any of the serialization methods.
var hasCopier = false;
var hasSerializer = false;
var hasDeserializer = false;
foreach (var method in type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic))
{
hasSerializer |= method.GetCustomAttribute<SerializerMethodAttribute>(false) != null;
hasDeserializer |= method.GetCustomAttribute<DeserializerMethodAttribute>(false) != null;
hasCopier |= method.GetCustomAttribute<CopierMethodAttribute>(false) != null;
}
var hasAllSerializationMethods = hasCopier && hasSerializer && hasDeserializer;
return hasAllSerializationMethods;
}
public static bool IsGrainMethodInvokerType(Type type)
{
var generalType = typeof(IGrainMethodInvoker);
#if !NETSTANDARD
if (type.Assembly.ReflectionOnly)
{
generalType = ToReflectionOnlyType(generalType);
}
#endif
return generalType.IsAssignableFrom(type) && TypeHasAttribute(type, typeof(MethodInvokerAttribute));
}
#if NETSTANDARD_TODO
public static Type ResolveType(string fullName)
{
return Type.GetType(fullName, true);
}
public static bool TryResolveType(string fullName, out Type type)
{
type = Type.GetType(fullName, false);
return type != null;
}
#else
public static Type ResolveType(string fullName)
{
return CachedTypeResolver.Instance.ResolveType(fullName);
}
public static bool TryResolveType(string fullName, out Type type)
{
return CachedTypeResolver.Instance.TryResolveType(fullName, out type);
}
public static Type ResolveReflectionOnlyType(string assemblyQualifiedName)
{
return CachedReflectionOnlyTypeResolver.Instance.ResolveType(assemblyQualifiedName);
}
public static Type ToReflectionOnlyType(Type type)
{
return type.Assembly.ReflectionOnly ? type : ResolveReflectionOnlyType(type.AssemblyQualifiedName);
}
#endif
public static IEnumerable<Type> GetTypes(Assembly assembly, Predicate<Type> whereFunc, Logger logger)
{
return assembly.IsDynamic ? Enumerable.Empty<Type>() : GetDefinedTypes(assembly, logger).Select(t => t.AsType()).Where(type => !type.GetTypeInfo().IsNestedPrivate && whereFunc(type));
}
public static IEnumerable<TypeInfo> GetDefinedTypes(Assembly assembly, Logger logger)
{
try
{
return assembly.DefinedTypes;
}
catch (Exception exception)
{
if (logger != null && logger.IsWarning)
{
var message = $"AssemblyLoader encountered an exception loading types from assembly '{assembly.FullName}': {exception}";
logger.Warn(ErrorCode.Loader_TypeLoadError_5, message, exception);
}
var typeLoadException = exception as ReflectionTypeLoadException;
if (typeLoadException != null)
{
return typeLoadException.Types?.Where(type => type != null).Select(type => type.GetTypeInfo()) ??
Enumerable.Empty<TypeInfo>();
}
return Enumerable.Empty<TypeInfo>();
}
}
public static IEnumerable<Type> GetTypes(Predicate<Type> whereFunc, Logger logger)
{
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
var result = new List<Type>();
foreach (var assembly in assemblies)
{
// there's no point in evaluating nested private types-- one of them fails to coerce to a reflection-only type anyhow.
var types = GetTypes(assembly, whereFunc, logger);
result.AddRange(types);
}
return result;
}
public static IEnumerable<Type> GetTypes(List<string> assemblies, Predicate<Type> whereFunc, Logger logger)
{
var currentAssemblies = AppDomain.CurrentDomain.GetAssemblies();
var result = new List<Type>();
foreach (var assembly in currentAssemblies.Where(loaded => !loaded.IsDynamic && assemblies.Contains(loaded.Location)))
{
// there's no point in evaluating nested private types-- one of them fails to coerce to a reflection-only type anyhow.
var types = GetTypes(assembly, whereFunc, logger);
result.AddRange(types);
}
return result;
}
/// <summary>
/// Returns a value indicating whether or not the provided <paramref name="methodInfo"/> is a grain method.
/// </summary>
/// <param name="methodInfo">The method.</param>
/// <returns>A value indicating whether or not the provided <paramref name="methodInfo"/> is a grain method.</returns>
public static bool IsGrainMethod(MethodInfo methodInfo)
{
if (methodInfo == null) throw new ArgumentNullException("methodInfo", "Cannot inspect null method info");
if (methodInfo.IsStatic || methodInfo.IsSpecialName || methodInfo.DeclaringType == null)
{
return false;
}
return methodInfo.DeclaringType.GetTypeInfo().IsInterface
&& typeof(IAddressable).IsAssignableFrom(methodInfo.DeclaringType);
}
public static bool TypeHasAttribute(Type type, Type attribType)
{
#if !NETSTANDARD
if (type.Assembly.ReflectionOnly || attribType.Assembly.ReflectionOnly)
{
type = ToReflectionOnlyType(type);
attribType = ToReflectionOnlyType(attribType);
// we can't use Type.GetCustomAttributes here because we could potentially be working with a reflection-only type.
return CustomAttributeData.GetCustomAttributes(type).Any(
attrib => attribType.IsAssignableFrom(attrib.AttributeType));
}
#endif
return TypeHasAttribute(type.GetTypeInfo(), attribType);
}
public static bool TypeHasAttribute(TypeInfo typeInfo, Type attribType)
{
return typeInfo.GetCustomAttributes(attribType, true).Any();
}
/// <summary>
/// Returns a sanitized version of <paramref name="type"/>s name which is suitable for use as a class name.
/// </summary>
/// <param name="type">
/// The grain type.
/// </param>
/// <returns>
/// A sanitized version of <paramref name="type"/>s name which is suitable for use as a class name.
/// </returns>
public static string GetSuitableClassName(Type type)
{
return GetClassNameFromInterfaceName(type.GetUnadornedTypeName());
}
/// <summary>
/// Returns a class-like version of <paramref name="interfaceName"/>.
/// </summary>
/// <param name="interfaceName">
/// The interface name.
/// </param>
/// <returns>
/// A class-like version of <paramref name="interfaceName"/>.
/// </returns>
public static string GetClassNameFromInterfaceName(string interfaceName)
{
string cleanName;
if (interfaceName.StartsWith("i", StringComparison.OrdinalIgnoreCase))
{
cleanName = interfaceName.Substring(1);
}
else
{
cleanName = interfaceName;
}
return cleanName;
}
/// <summary>
/// Returns the non-generic type name without any special characters.
/// </summary>
/// <param name="type">
/// The type.
/// </param>
/// <returns>
/// The non-generic type name without any special characters.
/// </returns>
public static string GetUnadornedTypeName(this Type type)
{
var index = type.Name.IndexOf('`');
// An ampersand can appear as a suffix to a by-ref type.
return (index > 0 ? type.Name.Substring(0, index) : type.Name).TrimEnd('&');
}
/// <summary>
/// Returns the non-generic method name without any special characters.
/// </summary>
/// <param name="method">
/// The method.
/// </param>
/// <returns>
/// The non-generic method name without any special characters.
/// </returns>
public static string GetUnadornedMethodName(this MethodInfo method)
{
var index = method.Name.IndexOf('`');
return index > 0 ? method.Name.Substring(0, index) : method.Name;
}
/// <summary>Returns a string representation of <paramref name="type"/>.</summary>
/// <param name="type">The type.</param>
/// <param name="options">The type formatting options.</param>
/// <returns>A string representation of the <paramref name="type"/>.</returns>
public static string GetParseableName(this Type type, TypeFormattingOptions options = null)
{
options = options ?? new TypeFormattingOptions();
return ParseableNameCache.GetOrAdd(
Tuple.Create(type, options),
_ =>
{
var builder = new StringBuilder();
var typeInfo = type.GetTypeInfo();
GetParseableName(
type,
builder,
new Queue<Type>(
typeInfo.IsGenericTypeDefinition
? typeInfo.GetGenericArguments()
: typeInfo.GenericTypeArguments),
options);
return builder.ToString();
});
}
/// <summary>Returns a string representation of <paramref name="type"/>.</summary>
/// <param name="type">The type.</param>
/// <param name="builder">The <see cref="StringBuilder"/> to append results to.</param>
/// <param name="typeArguments">The type arguments of <paramref name="type"/>.</param>
/// <param name="options">The type formatting options.</param>
private static void GetParseableName(
Type type,
StringBuilder builder,
Queue<Type> typeArguments,
TypeFormattingOptions options)
{
var typeInfo = type.GetTypeInfo();
if (typeInfo.IsArray)
{
builder.AppendFormat(
"{0}[{1}]",
typeInfo.GetElementType().GetParseableName(options),
string.Concat(Enumerable.Range(0, type.GetArrayRank() - 1).Select(_ => ',')));
return;
}
if (typeInfo.IsGenericParameter)
{
if (options.IncludeGenericTypeParameters)
{
builder.Append(type.GetUnadornedTypeName());
}
return;
}
if (typeInfo.DeclaringType != null)
{
// This is not the root type.
GetParseableName(typeInfo.DeclaringType, builder, typeArguments, options);
builder.Append(options.NestedTypeSeparator);
}
else if (!string.IsNullOrWhiteSpace(type.Namespace) && options.IncludeNamespace)
{
// This is the root type, so include the namespace.
var namespaceName = type.Namespace;
if (options.NestedTypeSeparator != '.')
{
namespaceName = namespaceName.Replace('.', options.NestedTypeSeparator);
}
if (options.IncludeGlobal)
{
builder.AppendFormat("global::");
}
builder.AppendFormat("{0}{1}", namespaceName, options.NestedTypeSeparator);
}
if (type.IsConstructedGenericType)
{
// Get the unadorned name, the generic parameters, and add them together.
var unadornedTypeName = type.GetUnadornedTypeName() + options.NameSuffix;
builder.Append(EscapeIdentifier(unadornedTypeName));
var generics =
Enumerable.Range(0, Math.Min(typeInfo.GetGenericArguments().Count(), typeArguments.Count))
.Select(_ => typeArguments.Dequeue())
.ToList();
if (generics.Count > 0 && options.IncludeTypeParameters)
{
var genericParameters = string.Join(
",",
generics.Select(generic => GetParseableName(generic, options)));
builder.AppendFormat("<{0}>", genericParameters);
}
}
else if (typeInfo.IsGenericTypeDefinition)
{
// Get the unadorned name, the generic parameters, and add them together.
var unadornedTypeName = type.GetUnadornedTypeName() + options.NameSuffix;
builder.Append(EscapeIdentifier(unadornedTypeName));
var generics =
Enumerable.Range(0, Math.Min(type.GetGenericArguments().Count(), typeArguments.Count))
.Select(_ => typeArguments.Dequeue())
.ToList();
if (generics.Count > 0 && options.IncludeTypeParameters)
{
var genericParameters = string.Join(
",",
generics.Select(_ => options.IncludeGenericTypeParameters ? _.ToString() : string.Empty));
builder.AppendFormat("<{0}>", genericParameters);
}
}
else
{
builder.Append(EscapeIdentifier(type.GetUnadornedTypeName() + options.NameSuffix));
}
}
/// <summary>
/// Returns the namespaces of the specified types.
/// </summary>
/// <param name="types">
/// The types to include.
/// </param>
/// <returns>
/// The namespaces of the specified types.
/// </returns>
public static IEnumerable<string> GetNamespaces(params Type[] types)
{
return types.Select(type => "global::" + type.Namespace).Distinct();
}
/// <summary>
/// Returns the <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>.
/// </summary>
/// <typeparam name="T">
/// The containing type of the method.
/// </typeparam>
/// <typeparam name="TResult">
/// The return type of the method.
/// </typeparam>
/// <param name="expression">
/// The expression.
/// </param>
/// <returns>
/// The <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>.
/// </returns>
public static MethodInfo Method<T, TResult>(Expression<Func<T, TResult>> expression)
{
var methodCall = expression.Body as MethodCallExpression;
if (methodCall != null)
{
return methodCall.Method;
}
throw new ArgumentException("Expression type unsupported.");
}
/// <summary>
/// Returns the <see cref="PropertyInfo"/> for the simple member access in the provided <paramref name="expression"/>.
/// </summary>
/// <typeparam name="T">
/// The containing type of the property.
/// </typeparam>
/// <typeparam name="TResult">
/// The return type of the property.
/// </typeparam>
/// <param name="expression">
/// The expression.
/// </param>
/// <returns>
/// The <see cref="PropertyInfo"/> for the simple member access call in the provided <paramref name="expression"/>.
/// </returns>
public static PropertyInfo Property<T, TResult>(Expression<Func<T, TResult>> expression)
{
var property = expression.Body as MemberExpression;
if (property != null)
{
return property.Member as PropertyInfo;
}
throw new ArgumentException("Expression type unsupported.");
}
/// <summary>
/// Returns the <see cref="MemberInfo"/> for the simple member access in the provided <paramref name="expression"/>.
/// </summary>
/// <typeparam name="T">
/// The containing type of the method.
/// </typeparam>
/// <typeparam name="TResult">
/// The return type of the method.
/// </typeparam>
/// <param name="expression">
/// The expression.
/// </param>
/// <returns>
/// The <see cref="MemberInfo"/> for the simple member access call in the provided <paramref name="expression"/>.
/// </returns>
public static MemberInfo Member<T, TResult>(Expression<Func<T, TResult>> expression)
{
var methodCall = expression.Body as MethodCallExpression;
if (methodCall != null)
{
return methodCall.Method;
}
var property = expression.Body as MemberExpression;
if (property != null)
{
return property.Member;
}
throw new ArgumentException("Expression type unsupported.");
}
/// <summary>Returns the <see cref="MemberInfo"/> for the simple member access in the provided <paramref name="expression"/>.</summary>
/// <typeparam name="TResult">The return type of the method.</typeparam>
/// <param name="expression">The expression.</param>
/// <returns>The <see cref="MemberInfo"/> for the simple member access call in the provided <paramref name="expression"/>.</returns>
public static MemberInfo Member<TResult>(Expression<Func<TResult>> expression)
{
var methodCall = expression.Body as MethodCallExpression;
if (methodCall != null)
{
return methodCall.Method;
}
var property = expression.Body as MemberExpression;
if (property != null)
{
return property.Member;
}
throw new ArgumentException("Expression type unsupported.");
}
/// <summary>Returns the <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>.</summary>
/// <typeparam name="T">The containing type of the method.</typeparam>
/// <param name="expression">The expression.</param>
/// <returns>The <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>.</returns>
public static MethodInfo Method<T>(Expression<Func<T>> expression)
{
var methodCall = expression.Body as MethodCallExpression;
if (methodCall != null)
{
return methodCall.Method;
}
throw new ArgumentException("Expression type unsupported.");
}
/// <summary>Returns the <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>.
/// </summary>
/// <typeparam name="T">The containing type of the method.</typeparam>
/// <param name="expression">The expression.</param>
/// <returns>The <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>.</returns>
public static MethodInfo Method<T>(Expression<Action<T>> expression)
{
var methodCall = expression.Body as MethodCallExpression;
if (methodCall != null)
{
return methodCall.Method;
}
throw new ArgumentException("Expression type unsupported.");
}
/// <summary>
/// Returns the <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>.
/// </summary>
/// <param name="expression">
/// The expression.
/// </param>
/// <returns>
/// The <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>.
/// </returns>
public static MethodInfo Method(Expression<Action> expression)
{
var methodCall = expression.Body as MethodCallExpression;
if (methodCall != null)
{
return methodCall.Method;
}
throw new ArgumentException("Expression type unsupported.");
}
/// <summary>Returns the namespace of the provided type, or <see cref="string.Empty"/> if the type has no namespace.</summary>
/// <param name="type">The type.</param>
/// <returns>The namespace of the provided type, or <see cref="string.Empty"/> if the type has no namespace.</returns>
public static string GetNamespaceOrEmpty(this Type type)
{
if (type == null || string.IsNullOrEmpty(type.Namespace))
{
return string.Empty;
}
return type.Namespace;
}
/// <summary>Returns the types referenced by the provided <paramref name="type"/>.</summary>
/// <param name="type">The type.</param>
/// <param name="includeMethods">Whether or not to include the types referenced in the methods of this type.</param>
/// <returns>The types referenced by the provided <paramref name="type"/>.</returns>
public static IList<Type> GetTypes(this Type type, bool includeMethods = false)
{
List<Type> results;
var key = Tuple.Create(type, includeMethods);
if (!ReferencedTypes.TryGetValue(key, out results))
{
results = GetTypes(type, includeMethods, null).ToList();
ReferencedTypes.TryAdd(key, results);
}
return results;
}
/// <summary>
/// Get a public or non-public constructor that matches the constructor arguments signature
/// </summary>
/// <param name="type">The type to use.</param>
/// <param name="constructorArguments">The constructor argument types to match for the signature.</param>
/// <returns>A constructor that matches the signature or <see langword="null"/>.</returns>
public static ConstructorInfo GetConstructorThatMatches(Type type, Type[] constructorArguments)
{
#if NETSTANDARD
var candidates = type.GetTypeInfo().GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
foreach (ConstructorInfo candidate in candidates)
{
if (ConstructorMatches(candidate, constructorArguments))
{
return candidate;
}
}
return null;
#else
var constructorInfo = type.GetConstructor(
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
null,
constructorArguments,
null);
return constructorInfo;
#endif
}
private static bool ConstructorMatches(ConstructorInfo candidate, Type[] constructorArguments)
{
ParameterInfo[] parameters = candidate.GetParameters();
if (parameters.Length == constructorArguments.Length)
{
for (int i = 0; i < constructorArguments.Length; i++)
{
if (parameters[i].ParameterType != constructorArguments[i])
{
return false;
}
}
return true;
}
return false;
}
/// <summary>
/// Returns a value indicating whether or not the provided assembly is the Orleans assembly or references it.
/// </summary>
/// <param name="assembly">The assembly.</param>
/// <returns>A value indicating whether or not the provided assembly is the Orleans assembly or references it.</returns>
internal static bool IsOrleansOrReferencesOrleans(Assembly assembly)
{
// We want to be loosely coupled to the assembly version if an assembly depends on an older Orleans,
// but we want a strong assembly match for the Orleans binary itself
// (so we don't load 2 different versions of Orleans by mistake)
return DoReferencesContain(assembly.GetReferencedAssemblies(), OrleansCoreAssembly)
|| string.Equals(assembly.GetName().FullName, OrleansCoreAssembly.FullName, StringComparison.Ordinal);
}
/// <summary>
/// Returns a value indicating whether or not the specified references contain the provided assembly name.
/// </summary>
/// <param name="references">The references.</param>
/// <param name="assemblyName">The assembly name.</param>
/// <returns>A value indicating whether or not the specified references contain the provided assembly name.</returns>
private static bool DoReferencesContain(IReadOnlyCollection<AssemblyName> references, AssemblyName assemblyName)
{
if (references.Count == 0)
{
return false;
}
return references.Any(asm => string.Equals(asm.Name, assemblyName.Name, StringComparison.Ordinal));
}
/// <summary>Returns the types referenced by the provided <paramref name="type"/>.</summary>
/// <param name="type">The type.</param>
/// <param name="includeMethods">Whether or not to include the types referenced in the methods of this type.</param>
/// <param name="exclude">Types to exclude</param>
/// <returns>The types referenced by the provided <paramref name="type"/>.</returns>
private static IEnumerable<Type> GetTypes(
this Type type,
bool includeMethods,
HashSet<Type> exclude)
{
exclude = exclude ?? new HashSet<Type>();
if (!exclude.Add(type))
{
yield break;
}
yield return type;
if (type.IsArray)
{
foreach (var elementType in type.GetElementType().GetTypes(false, exclude: exclude))
{
yield return elementType;
}
}
if (type.IsConstructedGenericType)
{
foreach (var genericTypeArgument in
type.GetGenericArguments().SelectMany(_ => GetTypes(_, false, exclude: exclude)))
{
yield return genericTypeArgument;
}
}
if (!includeMethods)
{
yield break;
}
foreach (var method in type.GetMethods())
{
foreach (var referencedType in GetTypes(method.ReturnType, false, exclude: exclude))
{
yield return referencedType;
}
foreach (var parameter in method.GetParameters())
{
foreach (var referencedType in GetTypes(parameter.ParameterType, false, exclude: exclude))
{
yield return referencedType;
}
}
}
}
private static string EscapeIdentifier(string identifier)
{
switch (identifier)
{
case "abstract":
case "add":
case "base":
case "bool":
case "break":
case "byte":
case "case":
case "catch":
case "char":
case "checked":
case "class":
case "const":
case "continue":
case "decimal":
case "default":
case "delegate":
case "do":
case "double":
case "else":
case "enum":
case "event":
case "explicit":
case "extern":
case "false":
case "finally":
case "fixed":
case "float":
case "for":
case "foreach":
case "get":
case "goto":
case "if":
case "implicit":
case "in":
case "int":
case "interface":
case "internal":
case "lock":
case "long":
case "namespace":
case "new":
case "null":
case "object":
case "operator":
case "out":
case "override":
case "params":
case "partial":
case "private":
case "protected":
case "public":
case "readonly":
case "ref":
case "remove":
case "return":
case "sbyte":
case "sealed":
case "set":
case "short":
case "sizeof":
case "static":
case "string":
case "struct":
case "switch":
case "this":
case "throw":
case "true":
case "try":
case "typeof":
case "uint":
case "ulong":
case "unsafe":
case "ushort":
case "using":
case "virtual":
case "where":
case "while":
return "@" + identifier;
default:
return identifier;
}
}
}
}
| |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.WindowsAzure.Commands.ServiceManagement.IaaS.Extensions;
using Microsoft.WindowsAzure.Commands.ServiceManagement.Model;
using Microsoft.WindowsAzure.Commands.ServiceManagement.Test.FunctionalTests.ConfigDataInfo;
using Microsoft.WindowsAzure.Commands.Sync.Download;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;
using Security.Cryptography;
using Security.Cryptography.X509Certificates;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Xml;
namespace Microsoft.WindowsAzure.Commands.ServiceManagement.Test.FunctionalTests
{
internal class Utilities
{
#region Constants
public static string AzurePowershellPath = AppDomain.CurrentDomain.BaseDirectory;
public const string AzurePowershellProfileModule = "Microsoft.WindowsAzure.Commands.Profile.dll";
public const string AzurePowershellCommandsModule = "Microsoft.WindowsAzure.Commands.dll";
public const string AzurePowershellStorageModule = "Microsoft.WindowsAzure.Commands.Storage.dll";
public const string AzurePowershellServiceManagementModule = "Microsoft.WindowsAzure.Commands.ServiceManagement.dll";
public const string AzurePowershellModuleServiceManagementPirModule = "Microsoft.WindowsAzure.Commands.ServiceManagement.PlatformImageRepository.dll";
public const string AzurePowershellModuleServiceManagementPreviewModule = "Microsoft.WindowsAzure.Commands.ServiceManagement.Preview.dll";
// AzureAffinityGroup
public const string NewAzureAffinityGroupCmdletName = "New-AzureAffinityGroup";
public const string GetAzureAffinityGroupCmdletName = "Get-AzureAffinityGroup";
public const string SetAzureAffinityGroupCmdletName = "Set-AzureAffinityGroup";
public const string RemoveAzureAffinityGroupCmdletName = "Remove-AzureAffinityGroup";
// AzureAvailablitySet
public const string SetAzureAvailabilitySetCmdletName = "Set-AzureAvailabilitySet";
public const string RemoveAzureAvailabilitySetCmdletName = "Remove-AzureAvailabilitySet";
// AzureCertificate & AzureCertificateSetting
public const string AddAzureCertificateCmdletName = "Add-AzureCertificate";
public const string GetAzureCertificateCmdletName = "Get-AzureCertificate";
public const string RemoveAzureCertificateCmdletName = "Remove-AzureCertificate";
public const string NewAzureCertificateSettingCmdletName = "New-AzureCertificateSetting";
// AzureDataDisk
public const string AddAzureDataDiskCmdletName = "Add-AzureDataDisk";
public const string GetAzureDataDiskCmdletName = "Get-AzureDataDisk";
public const string SetAzureDataDiskCmdletName = "Set-AzureDataDisk";
public const string RemoveAzureDataDiskCmdletName = "Remove-AzureDataDisk";
// AzureDeployment
public const string NewAzureDeploymentCmdletName = "New-AzureDeployment";
public const string GetAzureDeploymentCmdletName = "Get-AzureDeployment";
public const string SetAzureDeploymentCmdletName = "Set-AzureDeployment";
public const string RemoveAzureDeploymentCmdletName = "Remove-AzureDeployment";
public const string MoveAzureDeploymentCmdletName = "Move-AzureDeployment";
public const string GetAzureDeploymentEventCmdletName = "Get-AzureDeploymentEvent";
// AzureDisk
public const string AddAzureDiskCmdletName = "Add-AzureDisk";
public const string GetAzureDiskCmdletName = "Get-AzureDisk";
public const string UpdateAzureDiskCmdletName = "Update-AzureDisk";
public const string RemoveAzureDiskCmdletName = "Remove-AzureDisk";
// AzureDns
public const string NewAzureDnsCmdletName = "New-AzureDns";
public const string GetAzureDnsCmdletName = "Get-AzureDns";
public const string SetAzureDnsCmdletName = "Set-AzureDns";
public const string AddAzureDnsCmdletName = "Add-AzureDns";
public const string RemoveAzureDnsCmdletName = "Remove-AzureDns";
// AzureEndpoint
public const string AddAzureEndpointCmdletName = "Add-AzureEndpoint";
public const string GetAzureEndpointCmdletName = "Get-AzureEndpoint";
public const string SetAzureEndpointCmdletName = "Set-AzureEndpoint";
public const string RemoveAzureEndpointCmdletName = "Remove-AzureEndpoint";
// AzureLocation
public const string GetAzureLocationCmdletName = "Get-AzureLocation";
// AzureOSDisk & AzureOSVersion
public const string GetAzureOSDiskCmdletName = "Get-AzureOSDisk";
public const string SetAzureOSDiskCmdletName = "Set-AzureOSDisk";
public const string GetAzureOSVersionCmdletName = "Get-AzureOSVersion";
// AzureProvisioningConfig
public const string AddAzureProvisioningConfigCmdletName = "Add-AzureProvisioningConfig";
// AzurePublishSettingsFile
public const string ImportAzurePublishSettingsFileCmdletName = "Import-AzurePublishSettingsFile";
public const string GetAzurePublishSettingsFileCmdletName = "Get-AzurePublishSettingsFile";
public const string AddAzureEnvironmentCmdletName = "Add-AzureEnvironment";
// AzureQuickVM
public const string NewAzureQuickVMCmdletName = "New-AzureQuickVM";
// Get-AzureWinRMUri
public const string GetAzureWinRMUriCmdletName = "Get-AzureWinRMUri";
// AzurePlatformExtension
public const string PublishAzurePlatformExtensionCmdletName = "Publish-AzurePlatformExtension";
public const string SetAzurePlatformExtensionCmdletName = "Set-AzurePlatformExtension";
public const string UnpublishAzurePlatformExtensionCmdletName = "Unpublish-AzurePlatformExtension";
public const string NewAzurePlatformExtensionCertificateConfigCmdletName = "New-AzurePlatformExtensionCertificateConfig";
public const string NewAzurePlatformExtensionEndpointConfigSetCmdletName = "New-AzurePlatformExtensionEndpointConfigSet";
public const string SetAzurePlatformExtensionEndpointCmdletName = "Set-AzurePlatformExtensionEndpoint";
public const string RemoveAzurePlatformExtensionEndpointCmdletName = "Remove-AzurePlatformExtensionEndpoint";
public const string NewAzurePlatformExtensionLocalResourceConfigSetCmdletName = "New-AzurePlatformExtensionLocalResourceConfigSet";
public const string SetAzurePlatformExtensionLocalResourceCmdletName = "Set-AzurePlatformExtensionLocalResource";
public const string RemoveAzurePlatformExtensionLocalResourceCmdletName = "Remove-AzurePlatformExtensionLocalResource";
// AzurePlatformVMImage
public const string SetAzurePlatformVMImageCmdletName = "Set-AzurePlatformVMImage";
public const string GetAzurePlatformVMImageCmdletName = "Get-AzurePlatformVMImage";
public const string RemoveAzurePlatformVMImageCmdletName = "Remove-AzurePlatformVMImage";
public const string NewAzurePlatformComputeImageConfigCmdletName = "New-AzurePlatformComputeImageConfig";
public const string NewAzurePlatformMarketplaceImageConfigCmdletName = "New-AzurePlatformMarketplaceImageConfig";
// AzureRemoteDesktopFile
public const string GetAzureRemoteDesktopFileCmdletName = "Get-AzureRemoteDesktopFile";
// AzureReservedIP
public const string NewAzureReservedIPCmdletName = "New-AzureReservedIP";
public const string GetAzureReservedIPCmdletName = "Get-AzureReservedIP";
public const string RemoveAzureReservedIPCmdletName = "Remove-AzureReservedIP";
public const string SetAzureReservedIPAssociationCmdletName = "Set-AzureReservedIPAssociation";
public const string RemoveAzureReservedIPAssociationCmdletName = "Remove-AzureReservedIPAssociation";
public const string AddAzureVirtualIPCmdletName = "Add-AzureVirtualIP";
public const string RemoveAzureVirtualIPCmdletName = "Remove-AzureVirtualIP";
// AzureRole & AzureRoleInstnace
public const string GetAzureRoleCmdletName = "Get-AzureRole";
public const string SetAzureRoleCmdletName = "Set-AzureRole";
public const string GetAzureRoleInstanceCmdletName = "Get-AzureRoleInstance";
// AzureRoleSize
public const string GetAzureRoleSizeCmdletName = "Get-AzureRoleSize";
// AzureService
public const string NewAzureServiceCmdletName = "New-AzureService";
public const string GetAzureServiceCmdletName = "Get-AzureService";
public const string SetAzureServiceCmdletName = "Set-AzureService";
public const string RemoveAzureServiceCmdletName = "Remove-AzureService";
// AzureServiceAvailableExtension
public const string GetAzureServiceAvailableExtensionCmdletName = "Get-AzureServiceAvailableExtension";
// AzureServiceExtension
public const string NewAzureServiceExtensionConfigCmdletName = "New-AzureServiceExtensionConfig";
public const string SetAzureServiceExtensionCmdletName = "Set-AzureServiceExtension";
public const string GetAzureServiceExtensionCmdletName = "Get-AzureServiceExtension";
public const string RemoveAzureServiceExtensionCmdletName = "Remove-AzureServiceExtension";
// AzureServiceRemoteDesktopExtension
public const string NewAzureServiceRemoteDesktopExtensionConfigCmdletName = "New-AzureServiceRemoteDesktopExtensionConfig";
public const string SetAzureServiceRemoteDesktopExtensionCmdletName = "Set-AzureServiceRemoteDesktopExtension";
public const string GetAzureServiceRemoteDesktopExtensionCmdletName = "Get-AzureServiceRemoteDesktopExtension";
public const string RemoveAzureServiceRemoteDesktopExtensionCmdletName = "Remove-AzureServiceRemoteDesktopExtension";
// AzureServiceDiagnosticExtension
public const string NewAzureServiceDiagnosticsExtensionConfigCmdletName = "New-AzureServiceDiagnosticsExtensionConfig";
public const string SetAzureServiceDiagnosticsExtensionCmdletName = "Set-AzureServiceDiagnosticsExtension";
public const string GetAzureServiceDiagnosticsExtensionCmdletName = "Get-AzureServiceDiagnosticsExtension";
public const string RemoveAzureServiceDiagnosticsExtensionCmdletName = "Remove-AzureServiceDiagnosticsExtension";
// AzureSSHKey
public const string NewAzureSSHKeyCmdletName = "New-AzureSSHKey";
// AzureStorageAccount
public const string NewAzureStorageAccountCmdletName = "New-AzureStorageAccount";
public const string GetAzureStorageAccountCmdletName = "Get-AzureStorageAccount";
public const string SetAzureStorageAccountCmdletName = "Set-AzureStorageAccount";
public static string RemoveAzureStorageAccountCmdletName = "Remove-AzureStorageAccount";
//AzureDomainJoinExtension
public const string NewAzureServiceDomainJoinExtensionConfig = "New-AzureServiceADDomainExtensionConfig";
public const string SetAzureServiceDomainJoinExtension = "Set-AzureServiceADDomainExtension";
public const string RemoveAzureServiceDomainJoinExtension = "Remove-AzureServiceADDomainExtension";
public const string GetAzureServiceDomainJoinExtension = "Get-AzureServiceADDomainExtension";
// AzureStorageKey
public static string NewAzureStorageKeyCmdletName = "New-AzureStorageKey";
public static string GetAzureStorageKeyCmdletName = "Get-AzureStorageKey";
// AzureSubnet
public static string GetAzureSubnetCmdletName = "Get-AzureSubnet";
public static string SetAzureSubnetCmdletName = "Set-AzureSubnet";
// AzureSubscription
public const string GetAzureSubscriptionCmdletName = "Get-AzureSubscription";
public const string SetAzureSubscriptionCmdletName = "Set-AzureSubscription";
public const string SelectAzureSubscriptionCmdletName = "Select-AzureSubscription";
public const string RemoveAzureSubscriptionCmdletName = "Remove-AzureSubscription";
// AzureEnvironment
public const string GetAzureEnvironmentCmdletName = "Get-AzureEnvironment";
public const string SetAzureEnvironmentCmdletName = "Set-AzureEnvironment";
// AzureVhd
public static string AddAzureVhdCmdletName = "Add-AzureVhd";
public static string SaveAzureVhdCmdletName = "Save-AzureVhd";
// AzureVM
public const string NewAzureVMCmdletName = "New-AzureVM";
public const string GetAzureVMCmdletName = "Get-AzureVM";
public const string UpdateAzureVMCmdletName = "Update-AzureVM";
public const string RemoveAzureVMCmdletName = "Remove-AzureVM";
public const string ExportAzureVMCmdletName = "Export-AzureVM";
public const string ImportAzureVMCmdletName = "Import-AzureVM";
public const string StartAzureVMCmdletName = "Start-AzureVM";
public const string StopAzureVMCmdletName = "Stop-AzureVM";
public const string RestartAzureVMCmdletName = "Restart-AzureVM";
// AzureVMConfig
public const string NewAzureVMConfigCmdletName = "New-AzureVMConfig";
// AzureVMImage
public const string AddAzureVMImageCmdletName = "Add-AzureVMImage";
public const string GetAzureVMImageCmdletName = "Get-AzureVMImage";
public const string RemoveAzureVMImageCmdletName = "Remove-AzureVMImage";
public const string SaveAzureVMImageCmdletName = "Save-AzureVMImage";
public const string UpdateAzureVMImageCmdletName = "Update-AzureVMImage";
// AzureVMSize
public const string SetAzureVMSizeCmdletName = "Set-AzureVMSize";
// AzureVNetConfig & AzureVNetConnection
public const string GetAzureVNetConfigCmdletName = "Get-AzureVNetConfig";
public const string SetAzureVNetConfigCmdletName = "Set-AzureVNetConfig";
public const string RemoveAzureVNetConfigCmdletName = "Remove-AzureVNetConfig";
public const string GetAzureVNetConnectionCmdletName = "Get-AzureVNetConnection";
// AzureVnetGateway & AzureVnetGatewayKey
public const string NewAzureVNetGatewayCmdletName = "New-AzureVNetGateway";
public const string GetAzureVNetGatewayCmdletName = "Get-AzureVNetGateway";
public const string SetAzureVNetGatewayCmdletName = "Set-AzureVNetGateway";
public const string RemoveAzureVNetGatewayCmdletName = "Remove-AzureVNetGateway";
public const string GetAzureVNetGatewayKeyCmdletName = "Get-AzureVNetGatewayKey";
// AzureVNetSite
public const string GetAzureVNetSiteCmdletName = "Get-AzureVNetSite";
// AzureWalkUpgradeDomain
public const string SetAzureWalkUpgradeDomainCmdletName = "Set-AzureWalkUpgradeDomain";
public const string GetModuleCmdletName = "Get-Module";
public const string TestAzureNameCmdletName = "Test-AzureName";
public const string CopyAzureStorageBlobCmdletName = "Copy-AzureStorageBlob";
public static string SetAzureAclConfigCmdletName = "Set-AzureAclConfig";
public static string NewAzureAclConfigCmdletName = "New-AzureAclConfig";
public static string GetAzureAclConfigCmdletName = "Get-AzureAclConfig";
public static string SetAzureLoadBalancedEndpointCmdletName = "Set-AzureLoadBalancedEndpoint";
public const string ResetAzureRoleInstanceCmdletName = "ReSet-AzureRoleInstance";
//Static CA cmdlets
public const string TestAzureStaticVNetIPCmdletName = "Test-AzureStaticVNetIP";
public const string SetAzureStaticVNetIPCmdletName = "Set-AzureStaticVNetIP";
public const string GetAzureStaticVNetIPCmdletName = "Get-AzureStaticVNetIP";
public const string RemoveAzureStaticVNetIPCmdletName = "Remove-AzureStaticVNetIP";
public const string GetAzureVMBGInfoExtensionCmdletName = "Get-AzureVMBGInfoExtension";
public const string SetAzureVMBGInfoExtensionCmdletName = "Set-AzureVMBGInfoExtension";
public const string RemoveAzureVMBGInfoExtensionCmdletName = "Remove-AzureVMBGInfoExtension";
// Generic Azure VM Extension cmdlets
public const string GetAzureVMExtensionCmdletName = "Get-AzureVMExtension";
public const string SetAzureVMExtensionCmdletName = "Set-AzureVMExtension";
public const string RemoveAzureVMExtensionCmdletName = "Remove-AzureVMExtension";
public const string GetAzureVMAvailableExtensionCmdletName = "Get-AzureVMAvailableExtension";
public const string GetAzureVMExtensionConfigTemplateCmdletName = "Get-AzureVMExtensionConfigTemplate";
// VM Access Extesnion
public const string GetAzureVMAccessExtensionCmdletName = "Get-AzureVMAccessExtension";
public const string SetAzureVMAccessExtensionCmdletName = "Set-AzureVMAccessExtension";
public const string RemoveAzureVMAccessExtensionCmdletName = "Remove-AzureVMAccessExtension";
// Custom script extension
public const string SetAzureVMCustomScriptExtensionCmdletName = "Set-AzureVMCustomScriptExtension";
public const string GetAzureVMCustomScriptExtensionCmdletName = "Get-AzureVMCustomScriptExtension";
public const string RemoveAzureVMCustomScriptExtensionCmdletName = "Remove-AzureVMCustomScriptExtension";
public const string PaaSDiagnosticsExtensionName = "PaaSDiagnostics";
// VM Image Disk
public const string GetAzureVMImageDiskConfigSetCmdletName = "Get-AzureVMImageDiskConfigSet";
public const string SetAzureVMImageDataDiskConfigCmdletName = "Set-AzureVMImageDataDiskConfig";
public const string SetAzureVMImageOSDiskConfigCmdletName = "Set-AzureVMImageOSDiskConfig";
public const string NewAzureVMImageDiskConfigSetCmdletName = "New-AzureVMImageDiskConfigSet";
//ILB
public const string NewAzureInternalLoadBalancerConfigCmdletName = "New-AzureInternalLoadBalancerConfig";
public const string AddAzureInternalLoadBalancerCmdletName = "Add-AzureInternalLoadBalancer";
public const string GetAzureInternalLoadBalancerCmdletName = "Get-AzureInternalLoadBalancer";
public const string SetAzureInternalLoadBalancerCmdletName = "Set-AzureInternalLoadBalancer";
public const string RemoveAzureInternalLoadBalancerCmdletName = "Remove-AzureInternalLoadBalancer";
public const string SetAzurePublicIPCmdletName = "Set-AzurePublicIP";
public const string GetAzurePublicIPCmdletName = "Get-AzurePublicIP";
// NetworkInterface config
public const string AddAzureNetworkInterfaceConfig = "Add-AzureNetworkInterfaceConfig";
public const string SetAzureNetworkInterfaceConfig = "Set-AzureNetworkInterfaceConfig";
public const string RemoveAzureNetworkInterfaceConfig = "Remove-AzureNetworkInterfaceConfig";
public const string GetAzureNetworkInterfaceConfig = "Get-AzureNetworkInterfaceConfig";
// SqlServer extension
public const string SetAzureVMSqlServerExtensionCmdletName = "Set-AzureVMSqlServerExtension";
public const string GetAzureVMSqlServerExtensionCmdletName = "Get-AzureVMSqlServerExtension";
public const string RemoveAzureVMSqlServerExtensionCmdletName = "Remove-AzureVMSqlServerExtension";
#endregion
private static ServiceManagementCmdletTestHelper vmPowershellCmdlets = new ServiceManagementCmdletTestHelper();
public static string GetUniqueShortName(string prefix = "", int length = 6, string suffix = "", bool includeDate = false)
{
string dateSuffix = "";
if (includeDate)
{
dateSuffix = string.Format("-{0}{1}", DateTime.Now.Year, DateTime.Now.DayOfYear);
}
return string.Format("{0}{1}{2}{3}", prefix, Guid.NewGuid().ToString("N").Substring(0, length), suffix, dateSuffix);
}
public static int MatchKeywords(string input, string[] keywords, bool exactMatch = true)
{ //returns -1 for no match, 0 for exact match, and a positive number for how many keywords are matched.
int result = 0;
if (string.IsNullOrEmpty(input) || keywords.Length == 0)
return -1;
foreach (string keyword in keywords)
{
//For whole word match, modify pattern to be "\b{0}\b"
if (!string.IsNullOrEmpty(keyword) && Regex.IsMatch(input, string.Format(@"{0}", Regex.Escape(keyword)), RegexOptions.IgnoreCase))
{
result++;
}
}
if (result == keywords.Length)
{
return 0;
}
else if (result == 0)
{
return -1;
}
else
{
if (exactMatch)
{
return -1;
}
else
{
return result;
}
}
}
public static bool GetAzureVMAndWaitForReady(string serviceName, string vmName,int waitTime, int maxWaitTime )
{
Console.WriteLine("Waiting for the vm {0} to reach \"ReadyRole\" ");
DateTime startTime = DateTime.Now;
DateTime MaxEndTime = startTime.AddMilliseconds(maxWaitTime);
while (true)
{
Console.WriteLine("Getting vm '{0}' details:",vmName);
var vmRoleContext = vmPowershellCmdlets.GetAzureVM(vmName, serviceName);
Console.WriteLine("Current status of the VM is {0} ", vmRoleContext.InstanceStatus);
if (vmRoleContext.InstanceStatus == "ReadyRole")
{
Console.WriteLine("Instance status reached expected ReadyRole state. Exiting wait.");
return true;
}
else
{
if (DateTime.Compare(DateTime.Now, MaxEndTime) > 0)
{
Console.WriteLine("Maximum wait time reached and instance status didnt reach \"ReadyRole\" state. Exiting wait. ");
return false;
}
else
{
Console.WriteLine("Waiting for {0} seconds for the {1} status to be ReadyRole", waitTime / 1000, vmName);
Thread.Sleep(waitTime);
}
}
}
}
public static bool PrintAndCompareDeployment
(DeploymentInfoContext deployment, string serviceName, string deploymentName, string deploymentLabel, string slot, string status, int instanceCount)
{
Console.WriteLine("ServiceName:{0}, DeploymentID: {1}, Uri: {2}", deployment.ServiceName, deployment.DeploymentId, deployment.Url.AbsoluteUri);
Console.WriteLine("Name - {0}, Label - {1}, Slot - {2}, Status - {3}",
deployment.DeploymentName, deployment.Label, deployment.Slot, deployment.Status);
Console.WriteLine("RoleInstance: {0}", deployment.RoleInstanceList.Count);
foreach (var instance in deployment.RoleInstanceList)
{
Console.WriteLine("InstanceName - {0}, InstanceStatus - {1}", instance.InstanceName, instance.InstanceStatus);
}
Assert.AreEqual(deployment.ServiceName, serviceName);
Assert.AreEqual(deployment.DeploymentName, deploymentName);
Assert.AreEqual(deployment.Label, deploymentLabel);
Assert.AreEqual(deployment.Slot, slot);
if (status != null)
{
Assert.AreEqual(deployment.Status, status);
}
Assert.AreEqual(deployment.RoleInstanceList.Count, instanceCount);
Assert.IsNotNull(deployment.LastModifiedTime);
Assert.IsNotNull(deployment.CreatedTime);
return true;
}
// CheckRemove checks if 'fn(name)' exists. 'fn(name)' is usually 'Get-AzureXXXXX name'
public static bool CheckRemove<Arg, Ret>(Func<Arg, Ret> fn, Arg name)
{
try
{
fn(name);
Console.WriteLine("{0} still exists!", name);
return false;
}
catch (Exception e)
{
if (e.ToString().Contains("ResourceNotFound"))
{
Console.WriteLine("{0} does not exist.", name);
return true;
}
else
{
Console.WriteLine("Error: {0}", e.ToString());
return false;
}
}
}
public static PersistentVM CreateVMObjectWithDataDiskSubnetAndAvailibilitySet(string vmName, OS os, string username, string password, string subnet)
{
string disk1 = "Disk1";
int diskSize = 30;
string availabilitySetName = Utilities.GetUniqueShortName("AvailSet");
string img = string.Empty;
bool isWindowsOs = false;
if (os == OS.Windows)
{
img = vmPowershellCmdlets.GetAzureVMImageName(new[] { "Windows" }, false);
isWindowsOs = true;
}
else
{
img = vmPowershellCmdlets.GetAzureVMImageName(new[] { "Linux" }, false);
isWindowsOs = false;
}
PersistentVM vm = Utilities.CreateIaaSVMObject(vmName, InstanceSize.Small, img, isWindowsOs, username, password);
AddAzureDataDiskConfig azureDataDiskConfigInfo1 = new AddAzureDataDiskConfig(DiskCreateOption.CreateNew, diskSize, disk1, 0, HostCaching.ReadWrite.ToString());
azureDataDiskConfigInfo1.Vm = vm;
vm = vmPowershellCmdlets.SetAzureSubnet(vm, new string[] { subnet });
vm = vmPowershellCmdlets.SetAzureAvailabilitySet(availabilitySetName, vm);
return vm;
}
// CheckRemove checks if 'fn(name)' exists. 'fn(name)' is usually 'Get-AzureXXXXX name'
public static bool CheckRemove<Arg1, Arg2, Ret>(Func<Arg1, Arg2, Ret> fn, Arg1 name1, Arg2 name2)
{
try
{
fn(name1, name2);
Console.WriteLine("{0}, {1} still exist!", name1, name2);
return false;
}
catch (Exception e)
{
if (e.ToString().Contains("ResourceNotFound"))
{
Console.WriteLine("{0}, {1} is successfully removed", name1, name2);
return true;
}
else
{
Console.WriteLine("Error: {0}", e.ToString());
return false;
}
}
}
// CheckRemove checks if 'fn(name)' exists. 'fn(name)' is usually 'Get-AzureXXXXX name'
public static bool CheckRemove<Arg1, Arg2, Arg3, Ret>(Func<Arg1, Arg2, Arg3, Ret> fn, Arg1 name1, Arg2 name2, Arg3 name3)
{
try
{
fn(name1, name2, name3);
Console.WriteLine("{0}, {1}, {2} still exist!", name1, name2, name3);
return false;
}
catch (Exception e)
{
if (e.ToString().Contains("ResourceNotFound"))
{
Console.WriteLine("{0}, {1}, {2} is successfully removed", name1, name2, name3);
return true;
}
else
{
Console.WriteLine("Error: {0}", e.ToString());
return false;
}
}
}
public static BlobHandle GetBlobHandle(string blob, string key)
{
BlobUri blobPath;
Assert.IsTrue(BlobUri.TryParseUri(new Uri(blob), out blobPath));
return new BlobHandle(blobPath, key);
}
/// <summary>
/// Retry the given action until success or timed out.
/// </summary>
/// <param name="act">the action</param>
/// <param name="errorMessage">retry for this error message</param>
/// <param name="maxTry">the max number of retries</param>
/// <param name="intervalSeconds">the interval between retries</param>
public static void RetryActionUntilSuccess(Action act, string errorMessage, int maxTry, int intervalSeconds)
{
int i = 0;
while (i < maxTry)
{
try
{
act();
return;
}
catch (Exception e)
{
if (e.ToString().Contains(errorMessage) || (e.InnerException != null && e.InnerException.ToString().Contains(errorMessage)))
{
i++;
if (i == maxTry)
{
Console.WriteLine("Max number of retry is reached: {0}", errorMessage);
throw;
}
Console.WriteLine("{0} error occurs! retrying ...", errorMessage);
if (e.InnerException != null)
{
Console.WriteLine(e.InnerException);
}
Thread.Sleep(TimeSpan.FromSeconds(intervalSeconds));
continue;
}
else
{
Console.WriteLine(e);
if (e.InnerException != null)
{
Console.WriteLine(e.InnerException);
}
throw;
}
}
}
}
/// <summary>
/// Retry the given action until success or timed out.
/// </summary>
/// <param name="act">the action</param>
/// <param name="errorMessages">retry for this error messages</param>
/// <param name="maxTry">the max number of retries</param>
/// <param name="intervalSeconds">the interval between retries</param>
public static void RetryActionUntilSuccess(Action act, string[] errorMessages, int maxTry, int intervalSeconds)
{
int i = 0;
while (i < maxTry)
{
try
{
act();
return;
}
catch (Exception e)
{
bool found = false;
foreach (var errorMessage in errorMessages)
{
if (e.ToString().Contains(errorMessage) || (e.InnerException != null && e.InnerException.ToString().Contains(errorMessage)))
{
found = true;
i++;
if (i == maxTry)
{
Console.WriteLine("Max number of retry is reached: {0}", errorMessage);
throw;
}
Console.WriteLine("{0} error occurs! retrying ...", errorMessage);
if (e.InnerException != null)
{
Console.WriteLine(e.InnerException);
}
Thread.Sleep(TimeSpan.FromSeconds(intervalSeconds));
break;
}
}
if (!found)
{
Console.WriteLine(e);
if (e.InnerException != null)
{
Console.WriteLine(e.InnerException);
}
throw;
}
}
}
}
/// <summary>
/// This method verifies if a given error occurs during the action. Otherwise, it throws.
/// </summary>
/// <param name="act">Action item</param>
/// <param name="errorMessage">Required error message</param>
public static void VerifyFailure(Action act, string errorMessage)
{
try
{
act();
Assert.Fail("Should have failed, but it succeeded!!");
}
catch (Exception e)
{
if (e is AssertFailedException)
{
throw;
}
if (e.ToString().Contains(errorMessage))
{
Console.WriteLine("This failure is expected: {0}", e.InnerException);
}
else
{
Console.WriteLine(e);
throw;
}
}
}
/// <summary>
///
/// </summary>
/// <param name="act"></param>
/// <param name="errorMessage"></param>
public static void TryAndIgnore(Action act, string errorMessage)
{
try
{
act();
}
catch (Exception e)
{
if (e.ToString().Contains(errorMessage))
{
Console.WriteLine("Ignoring exception: {0}", e.InnerException);
}
else
{
Console.WriteLine(e);
throw;
}
}
}
public static X509Certificate2 InstallCert(string certFile, StoreLocation location = StoreLocation.CurrentUser, StoreName name = StoreName.My)
{
var cert = new X509Certificate2(certFile);
var certStore = new X509Store(name, location);
certStore.Open(OpenFlags.ReadWrite);
certStore.Add(cert);
certStore.Close();
Console.WriteLine("Cert, {0}, is installed.", cert.Thumbprint);
return cert;
}
public static void UninstallCert(X509Certificate2 cert, StoreLocation location, StoreName name)
{
try
{
X509Store certStore = new X509Store(name, location);
certStore.Open(OpenFlags.ReadWrite);
certStore.Remove(cert);
certStore.Close();
Console.WriteLine("Cert, {0}, is uninstalled.", cert.Thumbprint);
}
catch (Exception e)
{
Console.WriteLine("Error during uninstalling the cert: {0}", e.ToString());
throw;
}
}
public static X509Certificate2 CreateCertificate(string password, string issuer = "CN=Microsoft Azure Powershell Test", string friendlyName = "PSTest")
{
var keyCreationParameters = new CngKeyCreationParameters
{
ExportPolicy = CngExportPolicies.AllowExport,
KeyCreationOptions = CngKeyCreationOptions.None,
KeyUsage = CngKeyUsages.AllUsages,
Provider = CngProvider.MicrosoftSoftwareKeyStorageProvider
};
keyCreationParameters.Parameters.Add(new CngProperty("Length", BitConverter.GetBytes(2048), CngPropertyOptions.None));
CngKey key = CngKey.Create(CngAlgorithm2.Rsa, null, keyCreationParameters);
var creationParams = new X509CertificateCreationParameters(new X500DistinguishedName(issuer))
{
TakeOwnershipOfKey = true
};
X509Certificate2 cert = key.CreateSelfSignedCertificate(creationParams);
key = null;
cert.FriendlyName = friendlyName;
byte[] bytes = cert.Export(X509ContentType.Pfx, password);
X509Certificate2 returnCert = new X509Certificate2();
returnCert.Import(bytes, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
return returnCert;
}
public static SecureString convertToSecureString(string str)
{
SecureString secureStr = new SecureString();
foreach (char c in str)
{
secureStr.AppendChar(c);
}
return secureStr;
}
public static string FindSubstring(string givenStr, char givenChar, int i)
{
if (i > 0)
{
return FindSubstring(givenStr.Substring(givenStr.IndexOf(givenChar) + 1), givenChar, i - 1);
}
else
{
return givenStr;
}
}
public static bool CompareDateTime(DateTime expectedDate, string givenDate)
{
DateTime resultExpDate = DateTime.Parse(givenDate);
bool result = (resultExpDate.Day == expectedDate.Day);
result &= (resultExpDate.Month == expectedDate.Month);
result &= (resultExpDate.Year == expectedDate.Year);
return result;
}
public static string GetInnerXml(string xmlString, string tag)
{
string removedHeader = "<" + Utilities.FindSubstring(xmlString, '<', 2);
byte[] encodedString = Encoding.UTF8.GetBytes(xmlString);
MemoryStream stream = new MemoryStream(encodedString);
stream.Flush();
stream.Position = 0;
XmlDocument xml = new XmlDocument();
xml.Load(stream);
return xml.GetElementsByTagName(tag)[0].InnerXml;
}
public static void CompareWadCfg(string wadcfg, XmlDocument daconfig)
{
if (string.IsNullOrWhiteSpace(wadcfg))
{
Assert.IsNull(wadcfg);
}
else
{
string innerXml = daconfig.InnerXml;
StringAssert.Contains(Utilities.FindSubstring(innerXml, '<', 2), Utilities.FindSubstring(wadcfg, '<', 2));
}
}
static public string GenerateSasUri(string blobStorageEndpointFormat, string storageAccount, string storageAccountKey,
string blobContainer, string vhdName, int hours = 10, bool read = true, bool write = true, bool delete = true, bool list = true)
{
string destinationSasUri = string.Format(@blobStorageEndpointFormat, storageAccount) + string.Format("/{0}/{1}", blobContainer, vhdName);
var destinationBlob = new CloudPageBlob(new Uri(destinationSasUri), new StorageCredentials(storageAccount, storageAccountKey));
SharedAccessBlobPermissions permission = 0;
permission |= (read) ? SharedAccessBlobPermissions.Read : 0;
permission |= (write) ? SharedAccessBlobPermissions.Write : 0;
permission |= (delete) ? SharedAccessBlobPermissions.Delete : 0;
permission |= (list) ? SharedAccessBlobPermissions.List : 0;
var policy = new SharedAccessBlobPolicy()
{
Permissions = permission,
SharedAccessExpiryTime = DateTime.UtcNow + TimeSpan.FromHours(hours)
};
string destinationBlobToken = destinationBlob.GetSharedAccessSignature(policy);
return (destinationSasUri + destinationBlobToken);
}
static public void RecordTimeTaken(ref DateTime prev)
{
var period = DateTime.Now - prev;
Console.WriteLine("{0} minutes {1} seconds and {2} ms passed...", period.Minutes.ToString(), period.Seconds.ToString(), period.Milliseconds.ToString());
prev = DateTime.Now;
}
public static void PrintContext<T>(T obj)
{
PrintTypeContents(typeof(T), obj);
}
public static void PrintContextAndItsBase<T>(T obj)
{
Type type = typeof(T);
PrintTypeContents(type, obj);
PrintTypeContents(type.BaseType, obj);
}
private static void PrintTypeContents<T>(Type type, T obj)
{
foreach (PropertyInfo property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly))
{
string typeName = property.PropertyType.FullName;
if (typeName.Equals("System.String") || typeName.Equals("System.Int32") || typeName.Equals("System.Uri") ||
typeName.Contains("Nullable"))
{
Console.WriteLine("{0}: {1}", property.Name, property.GetValue(obj, null));
}
else if (typeName.Contains("Boolean"))
{
Console.WriteLine("{0}: {1}", property.Name, property.GetValue(obj, null).ToString());
}
else
{
Console.WriteLine("This type is not printed: {0}", typeName);
}
}
}
public static void PrintCompleteContext<T>(T obj)
{
Type type = typeof(T);
foreach (PropertyInfo property in type.GetProperties())
{
string typeName = property.PropertyType.FullName;
if (typeName.Equals("System.String") || typeName.Equals("System.Int32") || typeName.Equals("System.Uri") ||
typeName.Contains("Nullable"))
{
Console.WriteLine("{0}: {1}", property.Name, property.GetValue(obj, null));
}
else if (typeName.Contains("Boolean"))
{
Console.WriteLine("{0}: {1}", property.Name, property.GetValue(obj, null).ToString());
}
else
{
Console.WriteLine("This type is not printed: {0}", typeName);
}
}
}
public static bool validateHttpUri(string uri)
{
Uri uriResult;
return Uri.TryCreate(uri, UriKind.Absolute, out uriResult) && uriResult.Scheme == Uri.UriSchemeHttp;
}
public static PersistentVM CreateIaaSVMObject(string vmName,InstanceSize size,string imageName,bool isWindows = true,string username = null,string password = null,bool disableGuestAgent = false)
{
//Create an IaaS VM
var azureVMConfigInfo = new AzureVMConfigInfo(vmName, size.ToString(), imageName);
AzureProvisioningConfigInfo azureProvisioningConfig = null;
if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(username))
{
azureProvisioningConfig = new AzureProvisioningConfigInfo(isWindows ? OS.Windows:OS.Linux, username, password,disableGuestAgent);
}
var persistentVMConfigInfo = new PersistentVMConfigInfo(azureVMConfigInfo, azureProvisioningConfig, null, null);
return vmPowershellCmdlets.GetPersistentVM(persistentVMConfigInfo);
}
public static void PrintHeader(string title)
{
if (title.Length > 100)
{
Console.WriteLine(string.Format("{0}{1}{0}", "> > >", title));
}
else
{
int headerLineLength = 100;
Console.WriteLine();
Console.WriteLine(string.Format("{0}{1}{0}", new String('>', (headerLineLength - title.Length) / 2), title));
}
}
public static void PrintFooter(string title)
{
if (title.Length > 100)
{
Console.WriteLine(string.Format("{0}{1}{0}", "< < <", title));
}
else
{
int headerLineLength = 100;
string completed = ": Completed";
Console.WriteLine(string.Format("{0}{1}{0}", new String('<', (headerLineLength - (title.Length + completed.Length)) / 2), title + completed));
}
}
public static void PrintSeperationLineStart(string title,char seperator)
{
int headerLineLength = 100;
string completed = ": Completed";
Console.WriteLine(string.Format("{0}{1}{0}", new String(seperator, (headerLineLength - (title.Length + completed.Length)) / 2), title + completed));
}
public static void PrintSeperationLineEnd(string title,string successMessage, char seperator)
{
int headerLineLength = 100;
Console.WriteLine(string.Format("{0}{1}{0}", new String(seperator, (headerLineLength - (title.Length + successMessage.Length)) / 2), title + successMessage));
}
public static string ConvertToJsonArray(string[] values)
{
List<string> files = new List<string>();
foreach (string s in values)
{
files.Add(string.Format("'{0}'", s));
}
return string.Join(",", files);
}
public static string GetSASUri(string blobUrlRoot,string storageAccoutnName,string primaryKey, string container, string filename, TimeSpan persmissionDuration,SharedAccessBlobPermissions permissionType)
{
// Set the destination
string httpsBlobUrlRoot = string.Format("https:{0}", blobUrlRoot.Substring(blobUrlRoot.IndexOf('/')));
string vhdDestUri = httpsBlobUrlRoot + string.Format("{0}/{1}", container, filename);
var destinationBlob = new CloudPageBlob(new Uri(vhdDestUri), new StorageCredentials(storageAccoutnName, primaryKey));
var policy2 = new SharedAccessBlobPolicy()
{
Permissions = permissionType,
SharedAccessExpiryTime = DateTime.UtcNow.Add(persmissionDuration)
};
var destinationBlobToken2 = destinationBlob.GetSharedAccessSignature(policy2);
vhdDestUri += destinationBlobToken2;
return vhdDestUri;
}
public static PersistentVM GetAzureVM(string vmName, string serviceName)
{
var vmroleContext = vmPowershellCmdlets.GetAzureVM(vmName, serviceName);
return vmroleContext.VM;
}
public static void LogAssert(Action method,string actionTitle)
{
Console.Write(actionTitle);
method();
Console.WriteLine(": verified");
}
public static void ExecuteAndLog(Action method,string actionTitle)
{
PrintHeader(actionTitle);
method();
PrintFooter(actionTitle);
}
public static VirtualMachineExtensionImageContext GetAzureVMExtenionInfo(string extensionName)
{
List<VirtualMachineExtensionImageContext> extensionInfo = new List<VirtualMachineExtensionImageContext>();
extensionInfo.AddRange(vmPowershellCmdlets.GetAzureVMAvailableExtension());
return extensionInfo.Find(c => c.ExtensionName.Equals(extensionName));
}
}
}
| |
using System;
using System.Xml.Linq;
namespace WixSharp
{
/// <summary>
/// Represents a Wix Extension
/// </summary>
public class WixExtension
{
/// <summary>
/// File name of the represented Wix Extension assembly
/// </summary>
/// <remarks>The represented value must include the file name and extension. See example</remarks>
/// <example>WixIIsExtension.dll</example>
public string Assembly
{
get { return assembly.ExpandEnvVars(); }
}
readonly string assembly;
/// <summary>
/// Xml namespace declaration prefix for the represented Wix Extension
/// </summary>
public readonly string XmlNamespacePrefix;
/// <summary>
/// Xml namespace value for the represented Wix Extension
/// </summary>
public readonly string XmlNamespace;
/// <summary>
/// Creates a WixExtension instance representing the corresponding XML namespace declaration
/// </summary>
/// <param name="assembly"></param>
/// <param name="prefix"></param>
/// <param name="namespace"></param>
public WixExtension(string assembly, string prefix, string @namespace)
{
if (assembly.IsNullOrEmpty()) throw new ArgumentNullException("assembly", "assembly is a null reference or empty");
//note some extensions do not have associated XML namespace (e.g. WixUIExtension.dll).
this.assembly = assembly;
XmlNamespacePrefix = prefix;
XmlNamespace = @namespace;
}
/// <summary>
/// Returns XmlNamespacePrefix as an instance of XNamespace
/// </summary>
/// <returns></returns>
public XNamespace ToXNamespace()
{
return XmlNamespace;
}
/// <summary>
/// Creates XName based on the XNamespace and specified name.
/// </summary>
/// <returns></returns>
public XName ToXName(string name)
{
return ToXNamespace() + name;
}
/// <summary>
/// Creates XElement based on XName (XNamespace and specified name) and specified content.
/// </summary>
/// <returns></returns>
public XElement XElement(string name, object content)
{
return new XElement(ToXNamespace() + name, content);
}
/// <summary>
/// Returns a <see cref="System.String" /> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String" /> that represents this instance.
/// </returns>
public override string ToString()
{
return XmlNamespace;
}
/// <summary>
/// Creates XElement based on XName (XNamespace and specified name) and specified attributes.
/// <param name="name">Name of the element.</param>
/// <param name="attributesDefinition">The attributes definition. Rules of the composing the
/// definition are the same as for <see cref="WixObject.AttributesDefinition"/>.</param>
/// </summary>
public XElement XElement(string name, string attributesDefinition)
{
return new XElement(ToXNamespace() + name).SetAttributes(attributesDefinition);
}
/// <summary>
/// Gets the xml namespace attribute for this WixExtension
/// </summary>
/// <returns></returns>
public string ToNamespaceDeclaration()
{
return GetNamespaceDeclaration(XmlNamespacePrefix, XmlNamespace);
}
/// <summary>
/// Gets the xml namespace attribute for the provided <paramref name="prefix"/> and <paramref name="namespace"/>
/// </summary>
/// <param name="prefix"></param>
/// <param name="namespace"></param>
/// <returns></returns>
public static string GetNamespaceDeclaration(string prefix, string @namespace)
{
return string.Format("xmlns:{0}=\"{1}\"", prefix, @namespace);
}
/// <summary>
/// Well-known Wix Extension: difx
/// </summary>
public static WixExtension Difx = new WixExtension("%WixLocation%\\WixDifxAppExtension.dll", "difx", DifxNamespace);
/// <summary>
/// The `Difx` extension namespace
/// </summary>
public const string DifxNamespace = "http://schemas.microsoft.com/wix/DifxAppExtension";
/// <summary>
/// Well-known Wix Extension: Fire (Firewall)
/// </summary>
public static WixExtension Fire = new WixExtension("%WixLocation%\\WixFirewallExtension.dll", "fire", FireNamespace);
/// <summary>
/// The `Firewall` extension namespace
/// </summary>
public const string FireNamespace = "http://schemas.microsoft.com/wix/FirewallExtension";
/// <summary>
/// Well-known Wix Extension: Util
/// </summary>
public static WixExtension Util = new WixExtension("%WixLocation%\\WixUtilExtension.dll", "util", UtilNamespace);
/// <summary>
/// The `Util` extension namespace
/// </summary>
public const string UtilNamespace = "http://schemas.microsoft.com/wix/UtilExtension";
/// <summary>
/// Well-known Wix Extension: Bal
/// </summary>
public static WixExtension Bal = new WixExtension("%WixLocation%\\WixBalExtension.dll", "bal", BalNamespace);
/// <summary>
/// The `Bal` extension namespace
/// </summary>
public const string BalNamespace = "http://schemas.microsoft.com/wix/BalExtension";
/// <summary>
/// Well-known Wix Extension IIs
/// </summary>
public static WixExtension IIs = new WixExtension("%WixLocation%\\WixIIsExtension.dll", "iis", IisNamespace);
/// <summary>
/// The `Iis` extension namespace
/// </summary>
public const string IisNamespace = "http://schemas.microsoft.com/wix/IIsExtension";
/// <summary>
/// Well-known Wix Extension Sql
/// </summary>
public static WixExtension Sql = new WixExtension("%WixLocation%\\WixSqlExtension.dll", "sql", SqlNamespace);
/// <summary>
/// The `Sql` extension namespace
/// </summary>
public const string SqlNamespace = "http://schemas.microsoft.com/wix/SqlExtension";
/// <summary>
/// Well-known Wix Extension NetFx
/// </summary>
public static WixExtension NetFx = new WixExtension("%WixLocation%\\WiXNetFxExtension.dll", "netfx", NetFxNamespace);
/// <summary>
/// The `NetFx` extension namespace
/// </summary>
public const string NetFxNamespace = "http://schemas.microsoft.com/wix/NetFxExtension";
/// <summary>
/// Well-known Wix Extension Http
/// </summary>
public static WixExtension Http = new WixExtension("%WixLocation%\\WiXHttpExtension.dll", "http", HttpNamespace);
/// <summary>
/// The `Http` extension namespace
/// </summary>
public const string HttpNamespace = "http://schemas.microsoft.com/wix/HttpExtension";
/// <summary>
/// Well-known Wix Extension UI
/// </summary>
public static WixExtension UI = new WixExtension("%WixLocation%\\WixUIExtension.dll", null, null);
}
/// <summary>
/// The interface for the Wix# types that can generate WiX XML.
/// </summary>
public interface IXmlAware
{
/// <summary>
/// Emits WiX XML.
/// </summary>
/// <returns></returns>
XElement ToXml();
}
}
| |
// UrlRewriter - A .NET URL Rewriter module
// Version 2.0
//
// Copyright 2007 Intelligencia
// Copyright 2007 Seth Yates
//
using System;
using System.IO;
using System.Xml;
using System.Web;
using System.Web.Caching;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Specialized;
using System.Configuration;
using System.Reflection;
using Intelligencia.UrlRewriter.Parsers;
using Intelligencia.UrlRewriter.Transforms;
using Intelligencia.UrlRewriter.Utilities;
using Intelligencia.UrlRewriter.Logging;
namespace Intelligencia.UrlRewriter.Configuration
{
/// <summary>
/// Configuration for the URL rewriter.
/// </summary>
public class RewriterConfiguration
{
/// <summary>
/// Default constructor.
/// </summary>
internal RewriterConfiguration()
{
_xPoweredBy = MessageProvider.FormatString(Message.ProductName, Assembly.GetExecutingAssembly().GetName().Version.ToString(3));
_actionParserFactory = new ActionParserFactory();
_actionParserFactory.AddParser(new IfConditionActionParser());
_actionParserFactory.AddParser(new UnlessConditionActionParser());
_actionParserFactory.AddParser(new AddHeaderActionParser());
_actionParserFactory.AddParser(new SetCookieActionParser());
_actionParserFactory.AddParser(new SetPropertyActionParser());
_actionParserFactory.AddParser(new RewriteActionParser());
_actionParserFactory.AddParser(new RedirectActionParser());
_actionParserFactory.AddParser(new SetStatusActionParser());
_actionParserFactory.AddParser(new ForbiddenActionParser());
_actionParserFactory.AddParser(new GoneActionParser());
_actionParserFactory.AddParser(new NotAllowedActionParser());
_actionParserFactory.AddParser(new NotFoundActionParser());
_actionParserFactory.AddParser(new NotImplementedActionParser());
_conditionParserPipeline = new ConditionParserPipeline();
_conditionParserPipeline.AddParser(new AddressConditionParser());
_conditionParserPipeline.AddParser(new HeaderMatchConditionParser());
_conditionParserPipeline.AddParser(new MethodConditionParser());
_conditionParserPipeline.AddParser(new PropertyMatchConditionParser());
_conditionParserPipeline.AddParser(new ExistsConditionParser());
_conditionParserPipeline.AddParser(new UrlMatchConditionParser());
_transformFactory = new TransformFactory();
_transformFactory.AddTransform(new DecodeTransform());
_transformFactory.AddTransform(new EncodeTransform());
_transformFactory.AddTransform(new LowerTransform());
_transformFactory.AddTransform(new UpperTransform());
_transformFactory.AddTransform(new Base64Transform());
_transformFactory.AddTransform(new Base64DecodeTransform());
_defaultDocuments = new StringCollection();
}
/// <summary>
/// The rules.
/// </summary>
public IList Rules
{
get
{
return _rules;
}
}
/// <summary>
/// The action parser factory.
/// </summary>
public ActionParserFactory ActionParserFactory
{
get
{
return _actionParserFactory;
}
}
/// <summary>
/// The transform factory.
/// </summary>
public TransformFactory TransformFactory
{
get
{
return _transformFactory;
}
}
/// <summary>
/// The condition parser pipeline.
/// </summary>
public ConditionParserPipeline ConditionParserPipeline
{
get
{
return _conditionParserPipeline;
}
}
/// <summary>
/// Dictionary of error handlers.
/// </summary>
public IDictionary ErrorHandlers
{
get
{
return _errorHandlers;
}
}
/// <summary>
/// Logger to use for logging information.
/// </summary>
public IRewriteLogger Logger
{
get
{
return _logger;
}
set
{
_logger = value;
}
}
/// <summary>
/// Collection of default document names to use if the result of a rewriting
/// is a directory name.
/// </summary>
public StringCollection DefaultDocuments
{
get
{
return _defaultDocuments;
}
}
internal string XPoweredBy
{
get
{
return _xPoweredBy;
}
}
/// <summary>
/// Creates a new configuration with only the default entries.
/// </summary>
/// <returns></returns>
public static RewriterConfiguration Create()
{
return new RewriterConfiguration();
}
/// <summary>
/// The current configuration.
/// </summary>
public static RewriterConfiguration Current
{
get
{
RewriterConfiguration configuration = HttpRuntime.Cache.Get(_cacheName) as RewriterConfiguration;
if (configuration == null)
{
lock (SyncObject)
{
configuration = HttpRuntime.Cache.Get(_cacheName) as RewriterConfiguration;
if (configuration == null)
{
configuration = Load();
}
}
}
return configuration;
}
}
private static object SyncObject = new Object();
/// <summary>
/// Loads the configuration from the .config file, with caching.
/// </summary>
/// <returns>The configuration.</returns>
public static RewriterConfiguration Load()
{
XmlNode section = ConfigurationManager.GetSection(Constants.RewriterNode) as XmlNode;
RewriterConfiguration config = null;
XmlNode filenameNode = section.Attributes.GetNamedItem(Constants.AttrFile);
if (filenameNode != null)
{
string filename = HttpContext.Current.Server.MapPath(filenameNode.Value);
config = LoadFromFile(filename);
if (config != null)
{
CacheDependency fileDependency = new CacheDependency(filename);
HttpRuntime.Cache.Add(_cacheName, config, fileDependency, DateTime.UtcNow.AddHours(1.0), TimeSpan.Zero, CacheItemPriority.Default, null);
}
}
if (config == null)
{
config = LoadFromNode(section);
HttpRuntime.Cache.Add(_cacheName, config, null, DateTime.UtcNow.AddHours(1.0), TimeSpan.Zero, CacheItemPriority.Default, null);
}
return config;
}
/// <summary>
/// Loads the configuration from an external XML file.
/// </summary>
/// <param name="filename">The filename of the file to load configuration from.</param>
/// <returns>The configuration.</returns>
public static RewriterConfiguration LoadFromFile(string filename)
{
if (File.Exists(filename))
{
XmlDocument document = new XmlDocument();
document.Load(filename);
return LoadFromNode(document.DocumentElement);
}
return null;
}
/// <summary>
/// Loads the configuration from an XML node.
/// </summary>
/// <param name="node">The XML node to load configuration from.</param>
/// <returns>The configuration.</returns>
public static RewriterConfiguration LoadFromNode(XmlNode node)
{
return (RewriterConfiguration)RewriterConfigurationReader.Read(node);
}
private IRewriteLogger _logger = new NullLogger();
private Hashtable _errorHandlers = new Hashtable();
private ArrayList _rules = new ArrayList();
private ActionParserFactory _actionParserFactory;
private ConditionParserPipeline _conditionParserPipeline;
private TransformFactory _transformFactory;
private StringCollection _defaultDocuments;
private string _xPoweredBy;
private static string _cacheName = typeof(RewriterConfiguration).AssemblyQualifiedName;
}
}
| |
namespace Signum.Engine.Maps;
public static class TableExtensions
{
internal static string UnScapeSql(this string name, bool isPostgres)
{
if (isPostgres)
{
if (name.StartsWith('\"'))
return name.Trim('\"');
return name.ToLower();
}
return name.Trim('[', ']');
}
}
public class ServerName : IEquatable<ServerName>
{
public string Name { get; private set; }
public bool IsPostgres { get; private set; }
/// <summary>
/// Linked Servers: http://msdn.microsoft.com/en-us/library/ms188279.aspx
/// </summary>
/// <param name="name"></param>
public ServerName(string name, bool isPostgres)
{
if (string.IsNullOrEmpty(name))
throw new ArgumentNullException(nameof(name));
this.Name = name;
this.IsPostgres = isPostgres;
}
public override string ToString()
{
return Name.SqlEscape(IsPostgres);
}
public override bool Equals(object? obj) => obj is ServerName sn && Equals(sn);
public bool Equals(ServerName? other)
{
if (other == null)
return false;
return other.Name == Name;
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
public static ServerName? Parse(string? name, bool isPostgres)
{
if (!name.HasText())
return null;
return new ServerName(name.UnScapeSql(isPostgres), isPostgres);
}
}
public class DatabaseName : IEquatable<DatabaseName>
{
public string Name { get; private set; }
public bool IsPostgres { get; private set; }
public ServerName? Server { get; private set; }
public DatabaseName(ServerName? server, string name, bool isPostgres)
{
if (string.IsNullOrEmpty(name))
throw new ArgumentNullException(nameof(name));
this.Name = name;
this.Server = server;
this.IsPostgres = isPostgres;
}
public override string ToString()
{
var options = ObjectName.CurrentOptions;
var name = !options.DatabaseNameReplacement.HasText() ? Name.SqlEscape(IsPostgres): Name.Replace(Connector.Current.DatabaseName(), options.DatabaseNameReplacement).SqlEscape(IsPostgres);
if (Server == null)
return name;
return Server.ToString() + "." + name;
}
public override bool Equals(object? obj) => obj is DatabaseName dn && Equals(dn);
public bool Equals(DatabaseName? other)
{
if (other == null)
return false;
return other.Name == Name && object.Equals(Server, other.Server);
}
public override int GetHashCode()
{
return Name.GetHashCode() ^ (Server == null ? 0 : Server.GetHashCode());
}
public static DatabaseName? Parse(string? name, bool isPostgres)
{
if (!name.HasText())
return null;
var tuple = ObjectName.SplitLast(name, isPostgres);
return new DatabaseName(ServerName.Parse(tuple.prefix, isPostgres), tuple.name, isPostgres);
}
}
public class SchemaName : IEquatable<SchemaName>
{
public string Name { get; private set; }
public bool IsPostgres { get; private set; }
readonly DatabaseName? database;
public DatabaseName? Database
{
get
{
if (database == null || ObjectName.CurrentOptions.AvoidDatabaseName)
return null;
return database;
}
}
static readonly SchemaName defaultSqlServer = new SchemaName(null, "dbo", isPostgres: false);
static readonly SchemaName defaultPostgreeSql = new SchemaName(null, "public", isPostgres: true);
public static SchemaName Default(bool isPostgres) => isPostgres ? defaultPostgreeSql : defaultSqlServer;
public bool IsDefault()
{
return Database == null && (IsPostgres ? defaultPostgreeSql : defaultSqlServer).Name == Name;
}
public SchemaName(DatabaseName? database, string name, bool isPostgres)
{
if (string.IsNullOrEmpty(name))
throw new ArgumentNullException(nameof(name));
this.Name = name;
this.database = database;
this.IsPostgres = isPostgres;
}
public override string ToString()
{
var result = Name.SqlEscape(IsPostgres);
if (Database == null)
return result;
return Database.ToString() + "." + result;
}
public override bool Equals(object? obj) => obj is SchemaName sn && Equals(sn);
public bool Equals(SchemaName? other)
{
if (other == null)
return false;
return other.Name == Name &&
object.Equals(Database, other.Database);
}
public override int GetHashCode()
{
return Name.GetHashCode() ^ (Database == null ? 0 : Database.GetHashCode());
}
public static SchemaName Parse(string? name, bool isPostgres)
{
if (!name.HasText())
return SchemaName.Default(isPostgres);
var tuple = ObjectName.SplitLast(name, isPostgres);
return new SchemaName(DatabaseName.Parse(tuple.prefix, isPostgres), tuple.name, isPostgres);
}
internal SchemaName OnDatabase(DatabaseName? database)
{
return new SchemaName(database, this.Name, this.IsPostgres);
}
}
public class ObjectName : IEquatable<ObjectName>
{
public static int MaxPostgreeSize = 63;
public string Name { get; private set; }
public bool IsPostgres { get; private set; }
public SchemaName Schema { get; private set; } // null only for postgres temporary
public ObjectName(SchemaName schema, string name, bool isPostgres)
{
this.Name = name.HasText() ? name : throw new ArgumentNullException(nameof(name));
if (isPostgres && this.Name.Length > MaxPostgreeSize)
throw new InvalidOperationException($"The name '{name}' is too long, consider using TableNameAttribute/ColumnNameAttribute");
this.Schema = schema ?? (isPostgres && name.StartsWith("#") ? (SchemaName)null! : throw new ArgumentNullException(nameof(schema)));
this.IsPostgres = isPostgres;
}
public override string ToString()
{
if (Schema == null)
return Name.SqlEscape(IsPostgres);
return Schema.ToString() + "." + Name.SqlEscape(IsPostgres);
}
public override bool Equals(object? obj) => obj is ObjectName on && Equals(on);
public bool Equals(ObjectName? other)
{
if (other == null)
return false;
return other.Name == Name &&
object.Equals(Schema, other.Schema);
}
public override int GetHashCode()
{
return Name.GetHashCode() ^ Schema?.GetHashCode() ?? 0;
}
public static ObjectName Parse(string? name, bool isPostgres)
{
if (!name.HasText())
throw new ArgumentNullException(nameof(name));
var tuple = SplitLast(name, isPostgres);
return new ObjectName(SchemaName.Parse(tuple.prefix, isPostgres), tuple.name, isPostgres);
}
//FROM "[a.b.c].[d.e.f].[a.b.c].[c.d.f]"
//TO ("[a.b.c].[d.e.f].[a.b.c]", "c.d.f")
internal static (string? prefix, string name) SplitLast(string str, bool isPostgres)
{
if (isPostgres)
{
if (!str.EndsWith('\"'))
{
return (
prefix: str.TryBeforeLast('.'),
name: str.TryAfterLast('.') ?? str
);
}
var index = str.LastIndexOf('\"', str.Length - 2);
return (
prefix: index == 0 ? null : str.Substring(0, index - 1),
name: str.Substring(index).UnScapeSql(isPostgres)
);
}
else
{
if (!str.EndsWith("]"))
{
return (
prefix: str.TryBeforeLast('.'),
name: str.TryAfterLast('.') ?? str
);
}
var index = str.LastIndexOf('[');
return (
prefix: index == 0 ? null : str.Substring(0, index - 1),
name: str.Substring(index).UnScapeSql(isPostgres)
);
}
}
public ObjectName OnDatabase(DatabaseName? databaseName)
{
if (databaseName != null && databaseName.IsPostgres != this.IsPostgres)
throw new Exception("Inconsitent IsPostgres");
return new ObjectName(new SchemaName(databaseName, Schema!.Name, IsPostgres), Name, IsPostgres);
}
public ObjectName OnSchema(SchemaName schemaName)
{
if (schemaName.IsPostgres != this.IsPostgres)
throw new Exception("Inconsitent IsPostgres");
return new ObjectName(schemaName, Name, IsPostgres);
}
static readonly ThreadVariable<ObjectNameOptions> optionsVariable = Statics.ThreadVariable<ObjectNameOptions>("objectNameOptions");
public static IDisposable OverrideOptions(ObjectNameOptions options)
{
var old = optionsVariable.Value;
optionsVariable.Value = options;
return new Disposable(() => optionsVariable.Value = old);
}
public static ObjectNameOptions CurrentOptions
{
get { return optionsVariable.Value; }
}
public bool IsTemporal => this.Name.StartsWith("#");
}
public struct ObjectNameOptions
{
public string DatabaseNameReplacement;
public bool AvoidDatabaseName;
}
| |
//-----------------------------------------------------------------------
// <copyright file="FlowInterleaveSpec.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using Akka.Streams.Dsl;
using Akka.Streams.TestKit;
using Akka.Streams.TestKit.Tests;
using Akka.Util.Internal;
using FluentAssertions;
using Reactive.Streams;
using Xunit;
// ReSharper disable InvokeAsExtensionMethod
namespace Akka.Streams.Tests.Dsl
{
public class FlowInterleaveSpec : BaseTwoStreamsSetup<int>
{
protected override TestSubscriber.Probe<int> Setup(IPublisher<int> p1, IPublisher<int> p2)
{
var subscriber = this.CreateSubscriberProbe<int>();
Source.FromPublisher(p1)
.Interleave(Source.FromPublisher(p2), 2)
.RunWith(Sink.FromSubscriber(subscriber), Materializer);
return subscriber;
}
[Fact]
public void An_Interleave_for_Flow_must_work_in_the_happy_case()
{
this.AssertAllStagesStopped(() =>
{
var probe = this.CreateManualSubscriberProbe<int>();
Source.From(Enumerable.Range(0, 4))
.Interleave(Source.From(Enumerable.Range(4, 3)), 2)
.Interleave(Source.From(Enumerable.Range(7, 5)), 3)
.RunWith(Sink.FromSubscriber(probe), Materializer);
var subscription = probe.ExpectSubscription();
var collected = new List<int>();
for (var i = 1; i <= 12; i++)
{
subscription.Request(1);
collected.Add(probe.ExpectNext());
}
collected.ShouldAllBeEquivalentTo(new[] {0, 1, 4, 7, 8, 9, 5, 2, 3, 10, 11, 6});
probe.ExpectComplete();
}, Materializer);
}
[Fact]
public void An_Interleave_for_Flow_must_work_when_segmentSize_is_not_equal_elements_in_stream()
{
this.AssertAllStagesStopped(() =>
{
var probe = this.CreateManualSubscriberProbe<int>();
Source.From(Enumerable.Range(0, 3))
.Interleave(Source.From(Enumerable.Range(3, 3)), 2)
.RunWith(Sink.FromSubscriber(probe), Materializer);
probe.ExpectSubscription().Request(10);
probe.ExpectNext(0, 1, 3, 4, 2, 5);
probe.ExpectComplete();
}, Materializer);
}
[Fact]
public void An_Interleave_for_Flow_must_work_with_segmentSize_1()
{
this.AssertAllStagesStopped(() =>
{
var probe = this.CreateManualSubscriberProbe<int>();
Source.From(Enumerable.Range(0, 3))
.Interleave(Source.From(Enumerable.Range(3, 3)), 1)
.RunWith(Sink.FromSubscriber(probe), Materializer);
probe.ExpectSubscription().Request(10);
probe.ExpectNext(0, 3, 1, 4, 2, 5);
probe.ExpectComplete();
}, Materializer);
}
[Fact]
public void An_Interleave_for_Flow_must_not_work_with_segmentSize_0()
{
this.AssertAllStagesStopped(() =>
{
var source = Source.From(Enumerable.Range(0, 3));
source.Invoking(s => s.Interleave(Source.From(Enumerable.Range(3, 3)), 0))
.ShouldThrow<ArgumentException>();
}, Materializer);
}
[Fact]
public void An_Interleave_for_Flow_must_work_when_segmentSize_is_greater_than_stream_elements()
{
this.AssertAllStagesStopped(() =>
{
var probe = this.CreateManualSubscriberProbe<int>();
Source.From(Enumerable.Range(0, 3))
.Interleave(Source.From(Enumerable.Range(3, 13)), 10)
.RunWith(Sink.FromSubscriber(probe), Materializer);
probe.ExpectSubscription().Request(25);
Enumerable.Range(0, 16).ForEach(i => probe.ExpectNext(i));
probe.ExpectComplete();
var probe2 = this.CreateManualSubscriberProbe<int>();
Source.From(Enumerable.Range(1, 20))
.Interleave(Source.From(Enumerable.Range(21, 5)), 10)
.RunWith(Sink.FromSubscriber(probe2), Materializer);
probe2.ExpectSubscription().Request(100);
Enumerable.Range(1, 10).ForEach(i => probe2.ExpectNext(i));
Enumerable.Range(21, 5).ForEach(i => probe2.ExpectNext(i));
Enumerable.Range(11, 10).ForEach(i => probe2.ExpectNext(i));
probe2.ExpectComplete();
}, Materializer);
}
[Fact]
public void An_Interleave_for_Flow_must_work_with_one_immediately_completed_and_one_nonempty_publisher()
{
this.AssertAllStagesStopped(() =>
{
var subscriber1 = Setup(CompletedPublisher<int>(), NonEmptyPublisher(Enumerable.Range(1, 4)));
var subscription1 = subscriber1.ExpectSubscription();
subscription1.Request(4);
Enumerable.Range(1, 4).ForEach(i => subscriber1.ExpectNext(i));
subscriber1.ExpectComplete();
var subscriber2 = Setup(NonEmptyPublisher(Enumerable.Range(1, 4)), CompletedPublisher<int>());
var subscription2 = subscriber2.ExpectSubscription();
subscription2.Request(4);
Enumerable.Range(1, 4).ForEach(i => subscriber2.ExpectNext(i));
subscriber2.ExpectComplete();
}, Materializer);
}
[Fact]
public void An_Interleave_for_Flow_must_work_with_one_delayed_completed_and_one_nonempty_publisher()
{
this.AssertAllStagesStopped(() =>
{
var subscriber1 = Setup(SoonToCompletePublisher<int>(), NonEmptyPublisher(Enumerable.Range(1, 4)));
var subscription1 = subscriber1.ExpectSubscription();
subscription1.Request(4);
Enumerable.Range(1, 4).ForEach(i => subscriber1.ExpectNext(i));
subscriber1.ExpectComplete();
var subscriber2 = Setup(NonEmptyPublisher(Enumerable.Range(1, 4)), SoonToCompletePublisher<int>());
var subscription2 = subscriber2.ExpectSubscription();
subscription2.Request(4);
Enumerable.Range(1, 4).ForEach(i => subscriber2.ExpectNext(i));
subscriber2.ExpectComplete();
}, Materializer);
}
[Fact]
public void An_Interleave_for_Flow_must_work_with_one_immediately_failed_and_one_nonempty_publisher()
{
var subscriber1 = Setup(FailedPublisher<int>(), NonEmptyPublisher(Enumerable.Range(1, 4)));
var subscription1 = subscriber1.ExpectSubscription();
subscription1.Request(4);
subscriber1.ExpectError().Should().Be(TestException());
var subscriber2 = Setup(NonEmptyPublisher(Enumerable.Range(1, 4)), FailedPublisher<int>());
var subscription2 = subscriber2.ExpectSubscription();
subscription2.Request(4);
var result = subscriber2.ExpectNextOrError();
if (result is int)
result.Should().Be(1);
else
{
result.Should().Be(TestException());
return;
}
result = subscriber2.ExpectNextOrError();
if (result is int)
result.Should().Be(1);
else
{
result.Should().Be(TestException());
return;
}
subscriber2.ExpectError().Should().Be(TestException());
}
[Fact(Skip = "This is nondeterministic, multiple scenarios can happen")]
public void An_Interleave_for_Flow_must_work_with_one_delayed_failed_and_one_nonempty_publisher()
{
}
[Fact]
public void An_Interleave_for_Flow_must_pass_along_early_cancellation()
{
this.AssertAllStagesStopped(() =>
{
var up1 = this.CreateManualPublisherProbe<int>();
var up2 = this.CreateManualPublisherProbe<int>();
var down = this.CreateManualSubscriberProbe<int>();
var t = Source.AsSubscriber<int>()
.InterleaveMaterialized(Source.AsSubscriber<int>(), 2, Tuple.Create)
.ToMaterialized(Sink.FromSubscriber(down), Keep.Left)
.Run(Materializer);
var graphSubscriber1 = t.Item1;
var graphSubscriber2 = t.Item2;
var downstream = down.ExpectSubscription();
downstream.Cancel();
up1.Subscribe(graphSubscriber1);
up2.Subscribe(graphSubscriber2);
up1.ExpectSubscription().ExpectCancellation();
up2.ExpectSubscription().ExpectCancellation();
}, Materializer);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
namespace Orleans.Runtime.ConsistentRing
{
/// <summary>
/// We use the 'backward/clockwise' definition to assign responsibilities on the ring.
/// E.g. in a ring of nodes {5, 10, 15} the responsible for key 7 is 10 (the node is responsible for its predecessing range).
/// The backwards/clockwise approach is consistent with many overlays, e.g., Chord, Cassandra, etc.
/// Note: MembershipOracle uses 'forward/counter-clockwise' definition to assign responsibilities.
/// E.g. in a ring of nodes {5, 10, 15}, the responsible of key 7 is node 5 (the node is responsible for its sucessing range)..
/// </summary>
internal class VirtualBucketsRingProvider :
#if !NETSTANDARD
MarshalByRefObject,
#endif
IConsistentRingProvider, ISiloStatusListener
{
private readonly List<IRingRangeListener> statusListeners;
private readonly SortedDictionary<uint, SiloAddress> bucketsMap;
private List<Tuple<uint, SiloAddress>> sortedBucketsList; // flattened sorted bucket list for fast lock-free calculation of CalculateTargetSilo
private readonly Logger logger;
private readonly SiloAddress myAddress;
private readonly int numBucketsPerSilo;
private readonly object lockable;
private bool running;
private IRingRange myRange;
internal VirtualBucketsRingProvider(SiloAddress siloAddr, int nBucketsPerSilo)
{
if (nBucketsPerSilo <= 0 )
throw new IndexOutOfRangeException("numBucketsPerSilo is out of the range. numBucketsPerSilo = " + nBucketsPerSilo);
logger = LogManager.GetLogger(typeof(VirtualBucketsRingProvider).Name);
statusListeners = new List<IRingRangeListener>();
bucketsMap = new SortedDictionary<uint, SiloAddress>();
sortedBucketsList = new List<Tuple<uint, SiloAddress>>();
myAddress = siloAddr;
numBucketsPerSilo = nBucketsPerSilo;
lockable = new object();
running = true;
myRange = RangeFactory.CreateFullRange();
logger.Info("Starting {0} on silo {1}.", typeof(VirtualBucketsRingProvider).Name, siloAddr.ToStringWithHashCode());
StringValueStatistic.FindOrCreate(StatisticNames.CONSISTENTRING_RING, ToString);
IntValueStatistic.FindOrCreate(StatisticNames.CONSISTENTRING_RINGSIZE, () => GetRingSize());
StringValueStatistic.FindOrCreate(StatisticNames.CONSISTENTRING_MYRANGE_RINGDISTANCE, () => String.Format("x{0,8:X8}", ((IRingRangeInternal)myRange).RangeSize()));
FloatValueStatistic.FindOrCreate(StatisticNames.CONSISTENTRING_MYRANGE_RINGPERCENTAGE, () => (float)((IRingRangeInternal)myRange).RangePercentage());
FloatValueStatistic.FindOrCreate(StatisticNames.CONSISTENTRING_AVERAGERINGPERCENTAGE, () =>
{
int size = GetRingSize();
return size == 0 ? 0 : ((float)100.0/(float) size);
});
// add myself to the list of members
AddServer(myAddress);
}
private void Stop()
{
running = false;
}
public IRingRange GetMyRange()
{
return myRange;
}
private int GetRingSize()
{
lock (lockable)
{
return bucketsMap.Values.Distinct().Count();
}
}
public bool SubscribeToRangeChangeEvents(IRingRangeListener observer)
{
lock (statusListeners)
{
if (statusListeners.Contains(observer)) return false;
statusListeners.Add(observer);
return true;
}
}
public bool UnSubscribeFromRangeChangeEvents(IRingRangeListener observer)
{
lock (statusListeners)
{
return statusListeners.Contains(observer) && statusListeners.Remove(observer);
}
}
private void NotifyLocalRangeSubscribers(IRingRange old, IRingRange now, bool increased)
{
logger.Info(ErrorCode.CRP_Notify, "-NotifyLocalRangeSubscribers about old {0} new {1} increased? {2}", old.ToString(), now.ToString(), increased);
List<IRingRangeListener> copy;
lock (statusListeners)
{
copy = statusListeners.ToList();
}
foreach (IRingRangeListener listener in copy)
{
try
{
listener.RangeChangeNotification(old, now, increased);
}
catch (Exception exc)
{
logger.Error(ErrorCode.CRP_Local_Subscriber_Exception,
String.Format("Local IRangeChangeListener {0} has thrown an exception when was notified about RangeChangeNotification about old {1} new {2} increased? {3}",
listener.GetType().FullName, old, now, increased), exc);
}
}
}
private void AddServer(SiloAddress silo)
{
lock (lockable)
{
List<uint> hashes = silo.GetUniformHashCodes(numBucketsPerSilo);
foreach (var hash in hashes)
{
if (bucketsMap.ContainsKey(hash))
{
var other = bucketsMap[hash];
// If two silos conflict, take the lesser of the two (usually the older one; that is, the lower epoch)
if (silo.CompareTo(other) > 0) continue;
}
bucketsMap[hash] = silo;
}
var myOldRange = myRange;
var bucketsList = bucketsMap.Select(pair => new Tuple<uint, SiloAddress>(pair.Key, pair.Value)).ToList();
var myNewRange = CalculateRange(bucketsList, myAddress);
// capture my range and sortedBucketsList for later lock-free access.
myRange = myNewRange;
sortedBucketsList = bucketsList;
logger.Info(ErrorCode.CRP_Added_Silo, "Added Server {0}. Current view: {1}", silo.ToStringWithHashCode(), this.ToString());
NotifyLocalRangeSubscribers(myOldRange, myNewRange, true);
}
}
internal void RemoveServer(SiloAddress silo)
{
lock (lockable)
{
if (!bucketsMap.ContainsValue(silo)) return; // we have already removed this silo
List<uint> hashes = silo.GetUniformHashCodes(numBucketsPerSilo);
foreach (var hash in hashes)
{
bucketsMap.Remove(hash);
}
var myOldRange = this.myRange;
var bucketsList = bucketsMap.Select(pair => new Tuple<uint, SiloAddress>(pair.Key, pair.Value)).ToList();
var myNewRange = CalculateRange(bucketsList, myAddress);
// capture my range and sortedBucketsList for later lock-free access.
myRange = myNewRange;
sortedBucketsList = bucketsList;
logger.Info(ErrorCode.CRP_Removed_Silo, "Removed Server {0}. Current view: {1}", silo.ToStringWithHashCode(), this.ToString());
NotifyLocalRangeSubscribers(myOldRange, myNewRange, true);
}
}
private static IRingRange CalculateRange(List<Tuple<uint, SiloAddress>> list, SiloAddress silo)
{
var ranges = new List<IRingRange>();
for (int i = 0; i < list.Count; i++)
{
var curr = list[i];
var next = list[(i + 1) % list.Count];
// 'backward/clockwise' definition to assign responsibilities on the ring.
if (next.Item2.Equals(silo))
{
IRingRange range = RangeFactory.CreateRange(curr.Item1, next.Item1);
ranges.Add(range);
}
}
return RangeFactory.CreateRange(ranges);
}
// just for debugging
public override string ToString()
{
Dictionary<SiloAddress, IRingRangeInternal> ranges = GetRanges();
List<KeyValuePair<SiloAddress, IRingRangeInternal>> sortedList = ranges.AsEnumerable().ToList();
sortedList.Sort((t1, t2) => t1.Value.RangePercentage().CompareTo(t2.Value.RangePercentage()));
return Utils.EnumerableToString(sortedList, kv => String.Format("{0} -> {1}", kv.Key, kv.Value.ToString()));
}
// Internal: for testing only!
internal Dictionary<SiloAddress, IRingRangeInternal> GetRanges()
{
List<SiloAddress> silos;
List<Tuple<uint, SiloAddress>> snapshotBucketsList;
lock (lockable)
{
silos = bucketsMap.Values.Distinct().ToList();
snapshotBucketsList = sortedBucketsList;
}
var ranges = new Dictionary<SiloAddress, IRingRangeInternal>();
foreach (var silo in silos)
{
var range = (IRingRangeInternal)CalculateRange(snapshotBucketsList, silo);
ranges.Add(silo, range);
}
return ranges;
}
public void SiloStatusChangeNotification(SiloAddress updatedSilo, SiloStatus status)
{
// This silo's status has changed
if (updatedSilo.Equals(myAddress))
{
if (status.IsTerminating())
{
Stop();
}
}
else // Status change for some other silo
{
if (status.IsTerminating())
{
RemoveServer(updatedSilo);
}
else if (status == SiloStatus.Active) // do not do anything with SiloStatus.Created or SiloStatus.Joining -- wait until it actually becomes active
{
AddServer(updatedSilo);
}
}
}
public SiloAddress GetPrimaryTargetSilo(uint key)
{
return CalculateTargetSilo(key);
}
/// <summary>
/// Finds the silo that owns the given hash value.
/// This routine will always return a non-null silo address unless the excludeThisSiloIfStopping parameter is true,
/// this is the only silo known, and this silo is stopping.
/// </summary>
/// <param name="hash"></param>
/// <param name="excludeThisSiloIfStopping"></param>
/// <returns></returns>
private SiloAddress CalculateTargetSilo(uint hash, bool excludeThisSiloIfStopping = true)
{
// put a private reference to point to sortedBucketsList,
// so if someone is changing the sortedBucketsList reference, we won't get it changed in the middle of our operation.
// The tricks of writing lock-free code!
var snapshotBucketsList = sortedBucketsList;
// excludeMySelf from being a TargetSilo if we're not running and the excludeThisSIloIfStopping flag is true. see the comment in the Stop method.
bool excludeMySelf = excludeThisSiloIfStopping && !running;
if (snapshotBucketsList.Count == 0)
{
// If the membership ring is empty, then we're the owner by default unless we're stopping.
return excludeMySelf ? null : myAddress;
}
// use clockwise ... current code in membershipOracle.CalculateTargetSilo() does counter-clockwise ...
// if you want to stick to counter-clockwise, change the responsibility definition in 'In()' method & responsibility defs in OrleansReminderMemory
// need to implement a binary search, but for now simply traverse the list of silos sorted by their hashes
Tuple<uint, SiloAddress> s = snapshotBucketsList.Find(tuple => (tuple.Item1 >= hash) && // <= hash for counter-clockwise responsibilities
(!tuple.Item2.Equals(myAddress) || !excludeMySelf));
if (s == null)
{
// if not found in traversal, then first silo should be returned (we are on a ring)
// if you go back to their counter-clockwise policy, then change the 'In()' method in OrleansReminderMemory
s = snapshotBucketsList[0]; // vs [membershipRingList.Count - 1]; for counter-clockwise policy
// Make sure it's not us...
if (s.Item2.Equals(myAddress) && excludeMySelf)
{
// vs [membershipRingList.Count - 2]; for counter-clockwise policy
s = snapshotBucketsList.Count > 1 ? snapshotBucketsList[1] : null;
}
}
if (logger.IsVerbose2) logger.Verbose2("Calculated ring partition owner silo {0} for key {1}: {2} --> {3}", s.Item2, hash, hash, s.Item1);
return s.Item2;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections;
using System.Globalization;
using Xunit;
using SortedList_SortedListUtils;
namespace SortedListCtorIntComp
{
public class Driver<KeyType, ValueType>
{
private Test m_test;
public Driver(Test test)
{
m_test = test;
}
private CultureInfo _english = new CultureInfo("en");
private CultureInfo _german = new CultureInfo("de");
private CultureInfo _danish = new CultureInfo("da");
private CultureInfo _turkish = new CultureInfo("tr");
//CompareString lcid_en-US, EMPTY_FLAGS, "AE", 0, 2, "\u00C4", 0, 1, 1, NULL_STRING
//CompareString 0x10407, EMPTY_FLAGS, "AE", 0, 2, "\u00C4", 0, 1, 0, NULL_STRING
//CompareString lcid_da-DK, "NORM_IGNORECASE", "aA", 0, 2, "Aa", 0, 2, -1, NULL_STRING
//CompareString lcid_en-US, "NORM_IGNORECASE", "aA", 0, 2, "Aa", 0, 2, 0, NULL_STRING
//CompareString lcid_tr-TR, "NORM_IGNORECASE", "\u0131", 0, 1, "\u0049", 0, 1, 0, NULL_STRING
private const String strAE = "AE";
private const String strUC4 = "\u00C4";
private const String straA = "aA";
private const String strAa = "Aa";
private const String strI = "I";
private const String strTurkishUpperI = "\u0131";
private const String strBB = "BB";
private const String strbb = "bb";
private const String value = "Default_Value";
private static IComparer<String>[] s_predefinedComparers = new IComparer<String>[] {
StringComparer.CurrentCulture,
StringComparer.CurrentCultureIgnoreCase,
StringComparer.OrdinalIgnoreCase,
StringComparer.Ordinal};
public void TestEnum(int capacity)
{
SortedList<String, String> _dic;
IComparer<String> comparer;
foreach (var comparison in s_predefinedComparers)
{
_dic = new SortedList<String, String>(capacity, comparison);
m_test.Eval(_dic.Count == 0, String.Format("Err_23497sg! Count different: {0}", _dic.Count));
m_test.Eval(_dic.Keys.Count == 0, String.Format("Err_25ag! Count different: {0}", _dic.Keys.Count));
m_test.Eval(_dic.Values.Count == 0, String.Format("Err_23agd! Count different: {0}", _dic.Values.Count));
}
//Current culture
CultureInfo.DefaultThreadCurrentCulture = _english;
comparer = StringComparer.CurrentCulture;
_dic = new SortedList<String, String>(capacity, comparer);
_dic.Add(strAE, value);
m_test.Eval(!_dic.ContainsKey(strUC4), String.Format("Err_235rdag! Wrong result returned: {0}", _dic.ContainsKey(strUC4)));
//bug #11263 in NDPWhidbey
CultureInfo.DefaultThreadCurrentCulture = _german;
_dic = new SortedList<String, String>(capacity, StringComparer.CurrentCulture);
_dic.Add(strAE, value);
m_test.Eval(!_dic.ContainsKey(strUC4), String.Format("Err_23r7ag! Wrong result returned: {0}", _dic.ContainsKey(strUC4)));
//CurrentCultureIgnoreCase
CultureInfo.DefaultThreadCurrentCulture = _english;
_dic = new SortedList<String, String>(capacity, StringComparer.CurrentCultureIgnoreCase);
_dic.Add(straA, value);
m_test.Eval(_dic.ContainsKey(strAa), String.Format("Err_237g! Wrong result returned: {0}", _dic.ContainsKey(strAa)));
CultureInfo.DefaultThreadCurrentCulture = _danish;
_dic = new SortedList<String, String>(capacity, StringComparer.CurrentCultureIgnoreCase);
_dic.Add(straA, value);
m_test.Eval(!_dic.ContainsKey(strAa), String.Format("Err_0723f! Wrong result returned: {0}", _dic.ContainsKey(strAa)));
//InvariantCultureIgnoreCase
CultureInfo.DefaultThreadCurrentCulture = _english;
_dic = new SortedList<String, String>(capacity, StringComparer.OrdinalIgnoreCase);
_dic.Add(strI, value);
m_test.Eval(!_dic.ContainsKey(strTurkishUpperI), String.Format("Err_234qf! Wrong result returned: {0}", _dic.ContainsKey(strTurkishUpperI)));
CultureInfo.DefaultThreadCurrentCulture = _turkish;
_dic = new SortedList<String, String>(capacity, StringComparer.OrdinalIgnoreCase);
_dic.Add(strI, value);
m_test.Eval(!_dic.ContainsKey(strTurkishUpperI), String.Format("Err_234ra7g! Wrong result returned: {0}", _dic.ContainsKey(strTurkishUpperI)));
//Ordinal - not that many meaningful test
CultureInfo.DefaultThreadCurrentCulture = _english;
_dic = new SortedList<String, String>(capacity, StringComparer.Ordinal);
_dic.Add(strBB, value);
m_test.Eval(!_dic.ContainsKey(strbb), String.Format("Err_1244sd! Wrong result returned: {0}", _dic.ContainsKey(strbb)));
CultureInfo.DefaultThreadCurrentCulture = _danish;
_dic = new SortedList<String, String>(capacity, StringComparer.Ordinal);
_dic.Add(strBB, value);
m_test.Eval(!_dic.ContainsKey(strbb), String.Format("Err_235aeg! Wrong result returned: {0}", _dic.ContainsKey(strbb)));
}
public void TestParm()
{
//passing null will revert to the default comparison mechanism
SortedList<String, String> _dic;
IComparer<String> comparer;
int[] negativeValues = { -1, -2, -5, Int32.MinValue };
comparer = StringComparer.CurrentCulture;
for (int i = 0; i < negativeValues.Length; i++)
{
try
{
_dic = new SortedList<String, String>(negativeValues[i], comparer);
m_test.Eval(false, String.Format("Err_387tsg! No exception thrown"));
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception ex)
{
m_test.Eval(false, String.Format("Err_387tsg! Wrong exception thrown: {0}", ex));
}
}
}
public void NonStringImplementation(int capacity, KeyType key, ValueType value)
{
SortedList<KeyType, ValueType> _dic;
IComparer<KeyType> comparer = new MyOwnIKeyImplementation<KeyType>();
_dic = new SortedList<KeyType, ValueType>(capacity, comparer);
m_test.Eval(_dic.Count == 0, String.Format("Err_23497sg! Count different: {0}", _dic.Count));
m_test.Eval(_dic.Keys.Count == 0, String.Format("Err_25ag! Count different: {0}", _dic.Keys.Count));
m_test.Eval(_dic.Values.Count == 0, String.Format("Err_23agd! Count different: {0}", _dic.Values.Count));
_dic.Add(key, value);
//m_test.Eval(_dic[key].Equals(value), String.Format("Err_234e7af! Result different: {0}", _dic[key]));
}
}
public class Constructor_int_StringComparer
{
[Fact]
[ActiveIssue(5460, PlatformID.AnyUnix)]
public static void RunTests()
{
//This mostly follows the format established by the original author of these tests
Test test = new Test();
Driver<String, String> driver1 = new Driver<String, String>(test);
//Scenario 1: Pass all the enum values and ensure that the behavior is correct
int[] validCapacityValues = { 0, 1, 2, 5, 10, 16, 32, 50, 500, 5000, 10000 };
for (int i = 0; i < validCapacityValues.Length; i++)
driver1.TestEnum(validCapacityValues[i]);
//Scenario 2: Parm validation: other enum values and invalid capacity values
driver1.TestParm();
//Scenario 3: Non-string implementations and check
Driver<SimpleRef<int>, SimpleRef<String>> driver2 = new Driver<SimpleRef<int>, SimpleRef<String>>(test);
Driver<SimpleRef<String>, SimpleRef<int>> driver3 = new Driver<SimpleRef<String>, SimpleRef<int>>(test);
Driver<SimpleRef<int>, SimpleRef<int>> driver4 = new Driver<SimpleRef<int>, SimpleRef<int>>(test);
Driver<SimpleRef<String>, SimpleRef<String>> driver5 = new Driver<SimpleRef<String>, SimpleRef<String>>(test);
for (int i = 0; i < validCapacityValues.Length; i++)
{
driver1.NonStringImplementation(validCapacityValues[i], "Any", "Value");
driver2.NonStringImplementation(validCapacityValues[i], new SimpleRef<int>(1), new SimpleRef<string>("1"));
driver3.NonStringImplementation(validCapacityValues[i], new SimpleRef<string>("1"), new SimpleRef<int>(1));
driver4.NonStringImplementation(validCapacityValues[i], new SimpleRef<int>(1), new SimpleRef<int>(1));
driver5.NonStringImplementation(validCapacityValues[i], new SimpleRef<string>("1"), new SimpleRef<string>("1"));
}
Assert.True(test.result);
}
}
internal class MyOwnIKeyImplementation<KeyType> : IComparer<KeyType>
{
public int GetHashCode(KeyType key)
{
if (null == key)
return 0;
//We cannot get the hascode that is culture aware here since TextInfo doesn't expose this functionality publicly
return key.GetHashCode();
}
public int Compare(KeyType key1, KeyType key2)
{
return key1 == null ? (key2 == null ? 0 : -1) : (key2 == null ? 1 : key1.GetHashCode());
//if (null == key1)
//{
// if (null == key2)
// return 0;
// return -1;
//}
//return key1.CompareTo(key2);
}
public bool Equals(KeyType key1, KeyType key2)
{
if (null == key1)
return null == key2;
return key1.Equals(key2);
}
}
}
| |
/*
* Copyright 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Text;
using ZXing.Common;
using ZXing.Core;
namespace ZXing.OneD
{
/// <summary>
/// <p>Decodes Codabar barcodes.</p>
///
/// <author>Bas Vijfwinkel</author>
/// </summary>
public sealed class CodaBarReader : OneDReader
{
// These values are critical for determining how permissive the decoding
// will be. All stripe sizes must be within the window these define, as
// compared to the average stripe size.
private static readonly int MAX_ACCEPTABLE = (int)(PATTERN_MATCH_RESULT_SCALE_FACTOR * 2.0f);
private static readonly int PADDING = (int)(PATTERN_MATCH_RESULT_SCALE_FACTOR * 1.5f);
private const String ALPHABET_STRING = "0123456789-$:/.+ABCD";
internal static readonly char[] ALPHABET = ALPHABET_STRING.ToCharArray();
/**
* These represent the encodings of characters, as patterns of wide and narrow bars. The 7 least-significant bits of
* each int correspond to the pattern of wide and narrow, with 1s representing "wide" and 0s representing narrow.
*/
internal static int[] CHARACTER_ENCODINGS = {
0x003, 0x006, 0x009, 0x060, 0x012, 0x042, 0x021, 0x024, 0x030, 0x048, // 0-9
0x00c, 0x018, 0x045, 0x051, 0x054, 0x015, 0x01A, 0x029, 0x00B, 0x00E, // -$:/.+ABCD
};
// minimal number of characters that should be present (inclusing start and stop characters)
// under normal circumstances this should be set to 3, but can be set higher
// as a last-ditch attempt to reduce false positives.
private const int MIN_CHARACTER_LENGTH = 3;
// official start and end patterns
private static readonly char[] STARTEND_ENCODING = { 'A', 'B', 'C', 'D' };
// some codabar generator allow the codabar string to be closed by every
// character. This will cause lots of false positives!
// some industries use a checksum standard but this is not part of the original codabar standard
// for more information see : http://www.mecsw.com/specs/codabar.html
// Keep some instance variables to avoid reallocations
private readonly StringBuilder decodeRowResult;
private int[] counters;
private int counterLength;
public CodaBarReader()
{
decodeRowResult = new StringBuilder(20);
counters = new int[80];
counterLength = 0;
}
public override Result decodeRow(int rowNumber, BitArray row, IDictionary<DecodeHintType, object> hints)
{
for (var index = 0; index < counters.Length; index++)
counters[index] = 0;
if (!setCounters(row))
return null;
int startOffset = findStartPattern();
if (startOffset < 0)
return null;
int nextStart = startOffset;
decodeRowResult.Length = 0;
do
{
int charOffset = toNarrowWidePattern(nextStart);
if (charOffset == -1)
{
return null;
}
// Hack: We store the position in the alphabet table into a
// StringBuilder, so that we can access the decoded patterns in
// validatePattern. We'll translate to the actual characters later.
decodeRowResult.Append((char) charOffset);
nextStart += 8;
// Stop as soon as we see the end character.
if (decodeRowResult.Length > 1 &&
arrayContains(STARTEND_ENCODING, ALPHABET[charOffset]))
{
break;
}
} while (nextStart < counterLength); // no fixed end pattern so keep on reading while data is available
// Look for whitespace after pattern:
int trailingWhitespace = counters[nextStart - 1];
int lastPatternSize = 0;
for (int i = -8; i < -1; i++)
{
lastPatternSize += counters[nextStart + i];
}
// We need to see whitespace equal to 50% of the last pattern size,
// otherwise this is probably a false positive. The exception is if we are
// at the end of the row. (I.e. the barcode barely fits.)
if (nextStart < counterLength && trailingWhitespace < lastPatternSize/2)
{
return null;
}
if (!validatePattern(startOffset))
return null;
// Translate character table offsets to actual characters.
for (int i = 0; i < decodeRowResult.Length; i++)
{
decodeRowResult[i] = ALPHABET[decodeRowResult[i]];
}
// Ensure a valid start and end character
char startchar = decodeRowResult[0];
if (!arrayContains(STARTEND_ENCODING, startchar))
{
return null;
}
char endchar = decodeRowResult[decodeRowResult.Length - 1];
if (!arrayContains(STARTEND_ENCODING, endchar))
{
return null;
}
// remove stop/start characters character and check if a long enough string is contained
if (decodeRowResult.Length <= MIN_CHARACTER_LENGTH)
{
// Almost surely a false positive ( start + stop + at least 1 character)
return null;
}
if (!SupportClass.GetValue(hints, DecodeHintType.RETURN_CODABAR_START_END, false))
{
decodeRowResult.Remove(decodeRowResult.Length - 1, 1);
decodeRowResult.Remove(0, 1);
}
int runningCount = 0;
for (int i = 0; i < startOffset; i++)
{
runningCount += counters[i];
}
float left = runningCount;
for (int i = startOffset; i < nextStart - 1; i++)
{
runningCount += counters[i];
}
float right = runningCount;
var resultPointCallback = SupportClass.GetValue(hints, DecodeHintType.NEED_RESULT_POINT_CALLBACK, (ResultPointCallback) null);
if (resultPointCallback != null)
{
resultPointCallback(new ResultPoint(left, rowNumber));
resultPointCallback(new ResultPoint(right, rowNumber));
}
return new Result(
decodeRowResult.ToString(),
null,
new[]
{
new ResultPoint(left, rowNumber),
new ResultPoint(right, rowNumber)
},
BarcodeFormat.CODABAR);
}
private bool validatePattern(int start)
{
// First, sum up the total size of our four categories of stripe sizes;
int[] sizes = { 0, 0, 0, 0 };
int[] counts = { 0, 0, 0, 0 };
int end = decodeRowResult.Length - 1;
// We break out of this loop in the middle, in order to handle
// inter-character spaces properly.
int pos = start;
for (int i = 0; true; i++)
{
int pattern = CHARACTER_ENCODINGS[decodeRowResult[i]];
for (int j = 6; j >= 0; j--)
{
// Even j = bars, while odd j = spaces. Categories 2 and 3 are for
// long stripes, while 0 and 1 are for short stripes.
int category = (j & 1) + (pattern & 1) * 2;
sizes[category] += counters[pos + j];
counts[category]++;
pattern >>= 1;
}
if (i >= end)
{
break;
}
// We ignore the inter-character space - it could be of any size.
pos += 8;
}
// Calculate our allowable size thresholds using fixed-point math.
int[] maxes = new int[4];
int[] mins = new int[4];
// Define the threshold of acceptability to be the midpoint between the
// average small stripe and the average large stripe. No stripe lengths
// should be on the "wrong" side of that line.
for (int i = 0; i < 2; i++)
{
mins[i] = 0; // Accept arbitrarily small "short" stripes.
mins[i + 2] = ((sizes[i] << INTEGER_MATH_SHIFT) / counts[i] +
(sizes[i + 2] << INTEGER_MATH_SHIFT) / counts[i + 2]) >> 1;
maxes[i] = mins[i + 2];
maxes[i + 2] = (sizes[i + 2] * MAX_ACCEPTABLE + PADDING) / counts[i + 2];
}
// Now verify that all of the stripes are within the thresholds.
pos = start;
for (int i = 0; true; i++)
{
int pattern = CHARACTER_ENCODINGS[decodeRowResult[i]];
for (int j = 6; j >= 0; j--)
{
// Even j = bars, while odd j = spaces. Categories 2 and 3 are for
// long stripes, while 0 and 1 are for short stripes.
int category = (j & 1) + (pattern & 1) * 2;
int size = counters[pos + j] << INTEGER_MATH_SHIFT;
if (size < mins[category] || size > maxes[category])
{
return false;
}
pattern >>= 1;
}
if (i >= end)
{
break;
}
pos += 8;
}
return true;
}
/// <summary>
/// Records the size of all runs of white and black pixels, starting with white.
/// This is just like recordPattern, except it records all the counters, and
/// uses our builtin "counters" member for storage.
/// </summary>
/// <param name="row">row to count from</param>
private bool setCounters(BitArray row)
{
counterLength = 0;
// Start from the first white bit.
int i = row.getNextUnset(0);
int end = row.Size;
if (i >= end)
{
return false;
}
bool isWhite = true;
int count = 0;
while (i < end)
{
if (row[i] ^ isWhite)
{
// that is, exactly one is true
count++;
}
else
{
counterAppend(count);
count = 1;
isWhite = !isWhite;
}
i++;
}
counterAppend(count);
return true;
}
private void counterAppend(int e)
{
counters[counterLength] = e;
counterLength++;
if (counterLength >= counters.Length)
{
int[] temp = new int[counterLength * 2];
Array.Copy(counters, 0, temp, 0, counterLength);
counters = temp;
}
}
private int findStartPattern()
{
for (int i = 1; i < counterLength; i += 2)
{
int charOffset = toNarrowWidePattern(i);
if (charOffset != -1 && arrayContains(STARTEND_ENCODING, ALPHABET[charOffset]))
{
// Look for whitespace before start pattern, >= 50% of width of start pattern
// We make an exception if the whitespace is the first element.
int patternSize = 0;
for (int j = i; j < i + 7; j++)
{
patternSize += counters[j];
}
if (i == 1 || counters[i - 1] >= patternSize / 2)
{
return i;
}
}
}
return -1;
}
internal static bool arrayContains(char[] array, char key)
{
if (array != null)
{
foreach (char c in array)
{
if (c == key)
{
return true;
}
}
}
return false;
}
// Assumes that counters[position] is a bar.
private int toNarrowWidePattern(int position)
{
int end = position + 7;
if (end >= counterLength)
{
return -1;
}
int[] theCounters = counters;
int maxBar = 0;
int minBar = Int32.MaxValue;
for (int j = position; j < end; j += 2)
{
int currentCounter = theCounters[j];
if (currentCounter < minBar)
{
minBar = currentCounter;
}
if (currentCounter > maxBar)
{
maxBar = currentCounter;
}
}
int thresholdBar = (minBar + maxBar) / 2;
int maxSpace = 0;
int minSpace = Int32.MaxValue;
for (int j = position + 1; j < end; j += 2)
{
int currentCounter = theCounters[j];
if (currentCounter < minSpace)
{
minSpace = currentCounter;
}
if (currentCounter > maxSpace)
{
maxSpace = currentCounter;
}
}
int thresholdSpace = (minSpace + maxSpace) / 2;
int bitmask = 1 << 7;
int pattern = 0;
for (int i = 0; i < 7; i++)
{
int threshold = (i & 1) == 0 ? thresholdBar : thresholdSpace;
bitmask >>= 1;
if (theCounters[position + i] > threshold)
{
pattern |= bitmask;
}
}
for (int i = 0; i < CHARACTER_ENCODINGS.Length; i++)
{
if (CHARACTER_ENCODINGS[i] == pattern)
{
return i;
}
}
return -1;
}
}
}
| |
// 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 Fixtures.PetstoreV2
{
using Microsoft.Rest;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// This is a sample server Petstore server. You can find out more about
/// Swagger at <a
/// href="http://swagger.io">http://swagger.io</a> or on
/// irc.freenode.net, #swagger. For this sample, you can use the api key
/// "special-key" to test the authorization filters
/// </summary>
public partial interface ISwaggerPetstoreV2 : System.IDisposable
{
/// <summary>
/// The base URI of the service.
/// </summary>
System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; }
/// <summary>
/// Subscription credentials which uniquely identify client
/// subscription.
/// </summary>
ServiceClientCredentials Credentials { get; }
/// <summary>
/// Add a new pet to the store
/// </summary>
/// <param name='body'>
/// Pet object that needs to be added to the store
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Pet>> AddPetWithHttpMessagesAsync(Pet body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Update an existing pet
/// </summary>
/// <param name='body'>
/// Pet object that needs to be added to the store
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> UpdatePetWithHttpMessagesAsync(Pet body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Finds Pets by status
/// </summary>
/// <remarks>
/// Multiple status values can be provided with comma seperated strings
/// </remarks>
/// <param name='status'>
/// Status values that need to be considered for filter
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<IList<Pet>>> FindPetsByStatusWithHttpMessagesAsync(IList<string> status, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Finds Pets by tags
/// </summary>
/// <remarks>
/// Muliple tags can be provided with comma seperated strings. Use
/// tag1, tag2, tag3 for testing.
/// </remarks>
/// <param name='tags'>
/// Tags to filter by
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<IList<Pet>>> FindPetsByTagsWithHttpMessagesAsync(IList<string> tags, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Find pet by Id
/// </summary>
/// <remarks>
/// Returns a single pet
/// </remarks>
/// <param name='petId'>
/// Id of pet to return
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Pet>> GetPetByIdWithHttpMessagesAsync(long petId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Updates a pet in the store with form data
/// </summary>
/// <param name='petId'>
/// Id of pet that needs to be updated
/// </param>
/// <param name='fileContent'>
/// File to upload.
/// </param>
/// <param name='fileName'>
/// Updated name of the pet
/// </param>
/// <param name='status'>
/// Updated status of the pet
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> UpdatePetWithFormWithHttpMessagesAsync(long petId, Stream fileContent, string fileName = default(string), string status = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes a pet
/// </summary>
/// <param name='petId'>
/// Pet id to delete
/// </param>
/// <param name='apiKey'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> DeletePetWithHttpMessagesAsync(long petId, string apiKey = "", Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Returns pet inventories by status
/// </summary>
/// <remarks>
/// Returns a map of status codes to quantities
/// </remarks>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<IDictionary<string, int?>>> GetInventoryWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Place an order for a pet
/// </summary>
/// <param name='body'>
/// order placed for purchasing the pet
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Order>> PlaceOrderWithHttpMessagesAsync(Order body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Find purchase order by Id
/// </summary>
/// <remarks>
/// For valid response try integer IDs with value <= 5 or > 10.
/// Other values will generated exceptions
/// </remarks>
/// <param name='orderId'>
/// Id of pet that needs to be fetched
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Order>> GetOrderByIdWithHttpMessagesAsync(string orderId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete purchase order by Id
/// </summary>
/// <remarks>
/// For valid response try integer IDs with value < 1000. Anything
/// above 1000 or nonintegers will generate API errors
/// </remarks>
/// <param name='orderId'>
/// Id of the order that needs to be deleted
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> DeleteOrderWithHttpMessagesAsync(string orderId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Create user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='body'>
/// Created user object
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> CreateUserWithHttpMessagesAsync(User body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates list of users with given input array
/// </summary>
/// <param name='body'>
/// List of user object
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> CreateUsersWithArrayInputWithHttpMessagesAsync(IList<User> body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates list of users with given input array
/// </summary>
/// <param name='body'>
/// List of user object
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> CreateUsersWithListInputWithHttpMessagesAsync(IList<User> body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Logs user into the system
/// </summary>
/// <param name='username'>
/// The user name for login
/// </param>
/// <param name='password'>
/// The password for login in clear text
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<string,LoginUserHeaders>> LoginUserWithHttpMessagesAsync(string username, string password, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Logs out current logged in user session
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> LogoutUserWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get user by user name
/// </summary>
/// <param name='username'>
/// The name that needs to be fetched. Use user1 for testing.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<User>> GetUserByNameWithHttpMessagesAsync(string username, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Updated user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='username'>
/// name that need to be deleted
/// </param>
/// <param name='body'>
/// Updated user object
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> UpdateUserWithHttpMessagesAsync(string username, User body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='username'>
/// The name that needs to be deleted
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> DeleteUserWithHttpMessagesAsync(string username, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
// 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 Fixtures.AcceptanceTestsAzureCompositeModelClient
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// ArrayOperations operations.
/// </summary>
internal partial class ArrayOperations : IServiceOperations<AzureCompositeModel>, IArrayOperations
{
/// <summary>
/// Initializes a new instance of the ArrayOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal ArrayOperations(AzureCompositeModel client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AzureCompositeModel
/// </summary>
public AzureCompositeModel Client { get; private set; }
/// <summary>
/// Get complex types with array property
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ArrayWrapper>> GetValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/array/valid").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<ArrayWrapper>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<ArrayWrapper>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put complex types with array property
/// </summary>
/// <param name='array'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> PutValidWithHttpMessagesAsync(IList<string> array = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
ArrayWrapper complexBody = new ArrayWrapper();
if (array != null)
{
complexBody.Array = array;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("complexBody", complexBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/array/valid").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(complexBody != null)
{
_requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get complex types with array property which is empty
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ArrayWrapper>> GetEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetEmpty", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/array/empty").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<ArrayWrapper>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<ArrayWrapper>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put complex types with array property which is empty
/// </summary>
/// <param name='array'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> PutEmptyWithHttpMessagesAsync(IList<string> array = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
ArrayWrapper complexBody = new ArrayWrapper();
if (array != null)
{
complexBody.Array = array;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("complexBody", complexBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutEmpty", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/array/empty").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(complexBody != null)
{
_requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get complex types with array property while server doesn't provide a
/// response payload
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ArrayWrapper>> GetNotProvidedWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetNotProvided", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/array/notprovided").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<ArrayWrapper>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<ArrayWrapper>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
#region License
//L
// 2007 - 2013 Copyright Northwestern University
//
// Distributed under the OSI-approved BSD 3-Clause License.
// See http://ncip.github.com/annotation-and-image-markup/LICENSE.txt for details.
//L
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using ClearCanvas.Common;
using ClearCanvas.Common.Utilities;
using AIM.Annotation.Configuration;
namespace AIM.Annotation
{
internal class AimDataServiceSendQueue
{
public class AimDataServiceSendItem
{
private readonly string _fileName;
private readonly string _destinationServerUrl;
public AimDataServiceSendItem(string fileName, string destinationServerUrl)
{
_fileName = fileName;
_destinationServerUrl = destinationServerUrl;
}
public string DestinationServerUrl
{
get { return _destinationServerUrl; }
}
public string FileName
{
get { return _fileName; }
}
}
private static AimDataServiceSendQueue _instance;
private readonly object _operationLock = new object();
private bool _isActive;
private bool _stopThread;
private Thread _sendThread;
private Dictionary<String, String> _sourceFolders;
private readonly object _subscriptionLock = new object();
private event EventHandler<ItemEventArgs<AimDataServiceSendItem>> _sendProgressUpdate;
private AimDataServiceSendQueue()
{
}
internal static AimDataServiceSendQueue Instance
{
get
{
try
{
if (_instance == null)
_instance = new AimDataServiceSendQueue();
}
catch (Exception e)
{
Platform.Log(LogLevel.Error, e);
_instance = null;
}
return _instance;
}
}
internal event EventHandler<ItemEventArgs<AimDataServiceSendItem>> SendProgressUpdate
{
add
{
lock (_subscriptionLock)
{
_sendProgressUpdate += value;
}
}
remove
{
lock (_subscriptionLock)
{
_sendProgressUpdate -= value;
}
}
}
internal void Start()
{
lock(_operationLock)
{
if (_isActive)
return;
AimSettings.Default.PropertyChanged += OnAimSettingsChanged;
_isActive = true;
_stopThread = false;
_sendThread = new Thread(RunThread);
_sendThread.IsBackground = true;
_sendThread.Priority = ThreadPriority.Lowest;
_sendThread.Start();
Monitor.Wait(_operationLock);
}
}
internal void Stop()
{
lock(_operationLock)
{
if (!_isActive)
return;
_stopThread = true;
Monitor.Pulse(_operationLock);
Monitor.Wait(_operationLock);
AimSettings.Default.PropertyChanged -= OnAimSettingsChanged;
_sendThread.Join();
_sendThread = null;
_isActive = false;
}
}
private void OnAimSettingsChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
Debug.Assert(AimSettings.Default.SendQueuesNames != new object(), "AIMSettings \"SendQueuesNames\" is missing");
if (e.PropertyName == "SendQueuesNames")
{
lock (_operationLock)
{
_sourceFolders = null;
}
}
}
private void RunThread()
{
lock (_operationLock)
{
Monitor.Pulse(_operationLock);
while (true)
{
Monitor.Wait(_operationLock, 300000);
if (_stopThread)
break;
if (_sourceFolders == null)
_sourceFolders = AimSettings.Default.SendQueuesNames;
if (_sourceFolders != null && _sourceFolders.Count > 0)
{
foreach (var sourceFolder in _sourceFolders)
{
SendAnnotationsInFolderToDataService(sourceFolder.Value, sourceFolder.Key);
Monitor.Pulse(_operationLock);
if (_stopThread || _sourceFolders == null)
break;
}
}
Monitor.Pulse(_operationLock);
}
Monitor.Pulse(_operationLock);
}
}
private int SendAnnotationsInFolderToDataService(string folderName, string dataServiceUrl)
{
if (string.IsNullOrEmpty(folderName) || string.IsNullOrEmpty(dataServiceUrl))
{
Platform.Log(LogLevel.Error, "Trying to send queued annotations from an invalid folder ({0}) or to an invalid data service ({1})", folderName, dataServiceUrl);
return 0;
}
var folderPath = System.IO.Path.Combine(AimSettings.Default.AnnotationQueuesFolder, folderName);
if (!System.IO.Directory.Exists(folderPath))
return 0;
var sentCounter = 0;
try
{
var annotationFiles = System.IO.Directory.GetFiles(folderPath, "*.xml", System.IO.SearchOption.TopDirectoryOnly);
const int fileCountToSendAtOnce = 10;
for (var i = 0; i < (annotationFiles.Length + fileCountToSendAtOnce) / fileCountToSendAtOnce; i++)
{
var xmlAnnotations = new Dictionary<string, string>();
var readAnnotationFiles = new List<string>();
using (var xmlModel = new aim_dotnet.XmlModel())
{
var nextBatchMax = Math.Min((i + 1)*fileCountToSendAtOnce, annotationFiles.Length);
for (var j = i*fileCountToSendAtOnce; j < nextBatchMax; j++)
{
var annotationPathName = System.IO.Path.Combine(folderPath, annotationFiles[j]);
try
{
var annotations = xmlModel.ReadAnnotationsFromFile(annotationPathName);
try
{
foreach (var annotation in annotations)
{
xmlAnnotations.Add(annotation.UniqueIdentifier, xmlModel.WriteAnnotationToXmlString(annotation));
}
readAnnotationFiles.Add(annotationPathName);
}
catch (Exception ex)
{
Platform.Log(LogLevel.Error, ex, "Failed to convert annotation to XML string. File: {0}", annotationPathName);
xmlAnnotations.Clear();
}
finally
{
annotations.Clear();
}
}
catch (Exception ex)
{
Platform.Log(LogLevel.Error, ex, "Failed to read annotation file from queue: {0}", annotationPathName);
}
}
}
if (xmlAnnotations.Count > 0)
{
try
{
AIMTCGAService.AIMTCGASubmit.sendAIMTCGAAnnotation(new List<string>(xmlAnnotations.Values).ToArray());
sentCounter += xmlAnnotations.Count;
Debug.Assert(readAnnotationFiles.Count <= xmlAnnotations.Count, "There are more files to delete than read annoations");
xmlAnnotations.Clear();
foreach (var readAnnotationFile in readAnnotationFiles)
{
try
{
System.IO.File.Delete(readAnnotationFile);
}
catch (Exception ex)
{
Platform.Log(LogLevel.Error, ex, "Failed to delete sent annoation file ({0}). The file will be send again.", readAnnotationFile);
}
}
readAnnotationFiles.Clear();
}
catch (Exception ex)
{
Platform.Log(LogLevel.Debug, ex, "Failed to send annotations to the AIM Data Serice ({0}).", dataServiceUrl);
break;
}
}
}
}
catch (Exception ex)
{
Platform.Log(LogLevel.Error, ex, "Failed to send files from {0} to server {1}", folderPath, dataServiceUrl);
}
return sentCounter;
}
}
}
| |
using System;
using System.Collections;
using System.Globalization;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace WebApplication2
{
/// <summary>
/// Summary description for frmAddProcedure.
/// </summary>
public partial class frmUpdStaffActionProc : System.Web.UI.Page
{
private static string strURL =
System.Configuration.ConfigurationSettings.AppSettings["local_url"];
private static string strDB =
System.Configuration.ConfigurationSettings.AppSettings["local_db"];
public SqlConnection epsDbConn=new SqlConnection(strDB);
protected System.Web.UI.WebControls.RadioButtonList rblStatusSS;
private int GetIndexOfLocs (string s)
{
return (lstLocations.Items.IndexOf (lstLocations.Items.FindByValue(s)));
}
private int GetIndexOfVisibility (string s)
{
return (lstVisibility.Items.IndexOf (lstVisibility.Items.FindByValue(s)));
}
private int GetIndexOfPayMethods (string s)
{
return (lstPayMethods.Items.IndexOf (lstPayMethods.Items.FindByValue(s)));
}
private int GetIndexOfAptTypes (string s)
{
return (lstAptTypes.Items.IndexOf (lstAptTypes.Items.FindByValue(s)));
}
protected void Page_Load(object sender, System.EventArgs e)
{
if (!IsPostBack)
{
lblOrg.Text=(Session["OrgName"]).ToString();
loadVisibility();
loadLocs();
loadPayMethods();
loadAptTypes();
lstPayMethods.BorderColor=System.Drawing.Color.Navy;
lstPayMethods.ForeColor=System.Drawing.Color.Navy;
lstVisibility.SelectedIndex=GetIndexOfVisibility(Request.Params["Vis"]);
if (Session["btnAction1"].ToString() == "Update")
{
loadStaffAction();
}
if (Session["PeopleId"] != null)
{
lblName.Text = Session["PeopleName"].ToString();
}
btnAction.Text=Session["btnAction1"].ToString();
if (Session["btnAction1"].ToString() == "Add")
{
lblContent1.Text="You may now prepare a new staff or consultant appointment."
+ " If you have already identified the individual to be appointed, you may"
+ " identify this individual by clicking on 'Identify Person Requested (if any)'."
+ " Or you may complete the request without identifying the person, who will"
+ " then be identified separately by the recruitment staff in your organization.";
}
else
{
lblContent1.Text="You may only review the status of the appointment action at this point."
+ " Any changes will need to be requested from staff responsible for carrying out"
+ " the appointment action.";
}
}
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
}
#endregion
private void loadAptTypesc()
{
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.Connection=this.epsDbConn;
cmd.CommandText="hrs_RetrieveOrgStaffTypesInd";
cmd.Parameters.Add ("@Id",SqlDbType.Int);
cmd.Parameters["@Id"].Value=lstAptTypes.SelectedItem.Value;
DataSet ds=new DataSet();
SqlDataAdapter da=new SqlDataAdapter(cmd);
da.Fill(ds,"ost");
lblSalaryPeriod.Text=ds.Tables["ost"].Rows[0][3].ToString()
+ " per " + ds.Tables["ost"].Rows[0][4].ToString();
}
private void loadAptTypes()
{
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.Connection=this.epsDbConn;
cmd.CommandText="hrs_RetrieveOrgStaffTypes";
cmd.Parameters.Add ("@OrgId",SqlDbType.Int);
cmd.Parameters["@OrgId"].Value=Session["OrgId"].ToString();
DataSet ds=new DataSet();
SqlDataAdapter da=new SqlDataAdapter(cmd);
da.Fill(ds,"StaffTypes");
lstAptTypes.DataSource = ds;
lstAptTypes.DataMember= "StaffTypes";
lstAptTypes.DataTextField = "Name";
lstAptTypes.DataValueField = "Id";
lstAptTypes.DataBind();
lblSalaryPeriod.Text=ds.Tables["StaffTypes"].Rows[0][3].ToString()
+ " per " + ds.Tables["StaffTypes"].Rows[0][4].ToString();
}
private void loadStaffAction()
{
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.Connection=this.epsDbConn;
cmd.CommandText="hrs_RetrieveStaffAction";
cmd.Parameters.Add ("@Id",SqlDbType.Int);
cmd.Parameters["@Id"].Value=Session["Id"].ToString();
DataSet ds=new DataSet();
SqlDataAdapter da=new SqlDataAdapter(cmd);
da.Fill(ds,"StaffAction");
if (Session["PeopleId"] != null)
{
lblName.Text = Session["PeopleName"].ToString();
}
else if (ds.Tables["StaffAction"].Rows[0][0].ToString() == null)
{
lblName.Text= "Unidentified";
Session["PeopleId"]=null;
}
else
{
Session["PeopleId"]=ds.Tables["StaffAction"].Rows[0][0].ToString();
lblName.Text=ds.Tables["StaffAction"].Rows[0][1].ToString();
}
lstLocations.SelectedIndex=
GetIndexOfLocs(ds.Tables["StaffAction"].Rows[0][3].ToString());
lstVisibility.SelectedIndex=
GetIndexOfVisibility(ds.Tables["StaffAction"].Rows[0][4].ToString());
lstPayMethods.SelectedIndex = GetIndexOfPayMethods (ds.Tables["StaffAction"].Rows[0][5].ToString());
Session["Status"]=ds.Tables["StaffAction"].Rows[0][7].ToString();
//Session["StaffTypesId"]=Int32.Parse(Session["StaffTypeId"].ToString());
txtSalary.Text=ds.Tables["StaffAction"].Rows[0][8].ToString();
lstAptTypes.SelectedIndex = GetIndexOfAptTypes(ds.Tables["StaffAction"].Rows[0][9].ToString());
if (Session["Status"].ToString() == null)
{
lblAptStatus.Text="Status: Appointment Action Request Created";
}
else if (Session["Status"].ToString() == "0")
{
lblAptStatus.Text="Status: Appointment Action Requested";
btnAction.Visible=false;
btnSave.Text="Accept Request";
}
else if (Session["Status"].ToString() == "1")
{
lblAptStatus.Text="Status: Appointment Action in Process";
btnAction.Text="OK";
btnSave.Text="Appoint";
}
else if (Session["Status"].ToString() == "2")
{
lblAptStatus.Text="Status: Appointed";
btnAction.Text="OK";
btnPeople.Visible=false;
btnSave.Text="Terminate";
}
else if (Session["Status"].ToString() == "3")
{
lblAptStatus.Text="Status: Appointment Terminated";
btnAction.Text="OK";
btnPeople.Visible=false;
btnSave.Visible=false;
}
else if (Session["Status"].ToString() == "4")
{
lblAptStatus.Text="Status: Appointment Request Rejected";
btnAction.Text="OK";
btnSave.Visible=false;
btnPeople.Visible=false;
}
}
protected void btnAction_Click(object sender, System.EventArgs e)
{
Session["StatusC"] = 0;
if (Session["btnAction1"].ToString() == "Add")
{
addData();
}
else
{
updateData();
}
Done();
}
protected void btnSave_Click(object sender, System.EventArgs e)
{
if (Session["btnAction1"].ToString() == "Add")
{
addData();
}
else
{
updateData();
}
Done();
}
private void updateData()
{
try
{
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.CommandText="hrs_UpdateStaffAction";
cmd.Connection=this.epsDbConn;
cmd.Parameters.Add ("@Id",SqlDbType.Int);
cmd.Parameters["@Id"].Value=Session["Id"].ToString();
cmd.Parameters.Add ("@TypeId",SqlDbType.Int);
cmd.Parameters["@TypeId"].Value=lstAptTypes.SelectedItem.Value;
cmd.Parameters.Add ("@LocId",SqlDbType.Int);
cmd.Parameters["@LocId"].Value=lstLocations.SelectedItem.Value;
cmd.Parameters.Add ("@PM",SqlDbType.Int);
cmd.Parameters["@PM"].Value=lstPayMethods.SelectedItem.Value;
if (Session["PeopleId"] != null)
{
cmd.Parameters.Add ("@PeopleId",SqlDbType.Int);
cmd.Parameters["@PeopleId"].Value= Session["PeopleId"].ToString();
}
cmd.Parameters.Add ("@Sal",SqlDbType.Decimal);
cmd.Parameters["@Sal"].Value=decimal.Parse(txtSalary.Text,
NumberStyles.Any);
//cmd.Parameters.Add ("@PayGrade",SqlDbType.Int);
//cmd.Parameters["@PayGrade"].Value=lstAptTypes.SelectedItem.Value;
cmd.Parameters.Add ("@Vis",SqlDbType.Int);
cmd.Parameters["@Vis"].Value=lstVisibility.SelectedItem.Value;
cmd.Parameters.Add ("@Status",SqlDbType.Int);
if (Session["StatusC"] != null)
{
cmd.Parameters["@Status"].Value=Session["StatusC"].ToString();
}
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
Done();
}
catch
{
if (txtSalary.Text == "")
{
lblContent1.ForeColor=Color.Maroon;
lblContent1.Text="You must enter a Salary Amount or click 'Cancel'";
}
}
}
private void addData()
{
try
{
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.CommandText="hrs_AddStaffAction";
cmd.Connection=this.epsDbConn;
if (Session["PeopleId"] != null)
{
cmd.Parameters.Add ("@PeopleId",SqlDbType.Int);
cmd.Parameters["@PeopleId"].Value= Session["PeopleId"].ToString();
}
cmd.Parameters.Add ("@TypeId",SqlDbType.Int);
cmd.Parameters["@TypeId"].Value=lstAptTypes.SelectedItem.Value;
cmd.Parameters.Add ("@LocId",SqlDbType.Int);
cmd.Parameters["@LocId"].Value=lstLocations.SelectedItem.Value;
//cmd.Parameters.Add ("@PayGrade",SqlDbType.Int);
//cmd.Parameters["@PayGrade"].Value=lstAptTypes.SelectedItem.Value;
cmd.Parameters.Add ("@Status",SqlDbType.Int);
if (Session["StatusC"] != null)
{
cmd.Parameters["@Status"].Value=Session["StatusC"].ToString();
}
cmd.Parameters.Add ("@Sal",SqlDbType.Decimal);
if (txtSalary.Text != "")
{
cmd.Parameters["@Sal"].Value=decimal.Parse(txtSalary.Text,
NumberStyles.Any);
}
cmd.Parameters.Add ("@PM",SqlDbType.Int);
cmd.Parameters["@PM"].Value=lstPayMethods.SelectedItem.Value;
cmd.Parameters.Add ("@Vis",SqlDbType.Int);
cmd.Parameters["@Vis"].Value=lstVisibility.SelectedItem.Value;
cmd.Parameters.Add ("@OrgId",SqlDbType.Int);
cmd.Parameters["@OrgId"].Value=Session["OrgId"].ToString();
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
Done();
}
catch
{
if (txtSalary.Text == "")
{
lblContent1.ForeColor=Color.Maroon;
lblContent1.Text="You must enter a Salary Amount or click 'Cancel'";
}
}
}
private void loadVisibility()
{
SqlCommand cmd=new SqlCommand();
cmd.Connection=this.epsDbConn;
cmd.CommandType=CommandType.StoredProcedure;
cmd.CommandText="ams_RetrieveVisibility";
cmd.Parameters.Add ("@Vis",SqlDbType.Int);
cmd.Parameters["@Vis"].Value=Session["OrgVis"].ToString();
DataSet ds=new DataSet();
SqlDataAdapter da=new SqlDataAdapter (cmd);
da.Fill(ds,"Visibility");
lstVisibility.DataSource = ds;
lstVisibility.DataMember= "Visibility";
lstVisibility.DataTextField = "Name";
lstVisibility.DataValueField = "Id";
lstVisibility.DataBind();
}
private void loadLocs()
{
SqlCommand cmd=new SqlCommand();
cmd.Connection=this.epsDbConn;
cmd.CommandType=CommandType.StoredProcedure;
cmd.CommandText="eps_RetrieveLocations";
cmd.Parameters.Add ("@OrgId",SqlDbType.Int);
cmd.Parameters["@OrgId"].Value=Session["OrgId"].ToString();
cmd.Parameters.Add ("@OrgIdP",SqlDbType.Int);
cmd.Parameters["@OrgIdP"].Value=Session["OrgIdP"].ToString();
cmd.Parameters.Add ("@LicenseId",SqlDbType.Int);
cmd.Parameters["@LicenseId"].Value=Session["LicenseId"].ToString();
cmd.Parameters.Add ("@DomainId",SqlDbType.Int);
cmd.Parameters["@DomainId"].Value=Session["DomainId"].ToString();
DataSet ds=new DataSet();
SqlDataAdapter da=new SqlDataAdapter (cmd);
da.Fill(ds,"Locations");
lstLocations.DataSource = ds;
lstLocations.DataMember= "Locations";
lstLocations.DataTextField = "Name";
lstLocations.DataValueField = "Id";
lstLocations.DataBind();
}
private void loadPayMethods()
{
SqlCommand cmd=new SqlCommand();
cmd.Connection=this.epsDbConn;
cmd.CommandType=CommandType.StoredProcedure;
cmd.CommandText="fms_RetrievePayMethods";
DataSet ds=new DataSet();
SqlDataAdapter da=new SqlDataAdapter (cmd);
da.Fill(ds,"PayMethods");
lstPayMethods.DataSource = ds;
lstPayMethods.DataMember= "PayMethods";
lstPayMethods.DataTextField = "Name";
lstPayMethods.DataValueField = "Id";
lstPayMethods.DataBind();
}
private void Done()
{
Session["PeopleId"]=null;
Response.Redirect (strURL + Session["CSA"].ToString() + ".aspx?");
}
private void btnCancel_Click(object sender, System.EventArgs e)
{
Done();
}
private void peopleAdd()
{lblOrg.Text="h2";
Session["CallerPeople"]="frmUpdStaffActionProc";
Response.Redirect (strURL + "frmPeople.aspx?");
}
protected void btnPeople_Click(object sender, System.EventArgs e)
{
peopleAdd();
lblOrg.Text="h1";
}
protected void lstAptTypes_SelectedIndexChanged(object sender, System.EventArgs e)
{
loadAptTypesc();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void AndNotUInt64()
{
var test = new SimpleBinaryOpTest__AndNotUInt64();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__AndNotUInt64
{
private const int VectorSize = 32;
private const int Op1ElementCount = VectorSize / sizeof(UInt64);
private const int Op2ElementCount = VectorSize / sizeof(UInt64);
private const int RetElementCount = VectorSize / sizeof(UInt64);
private static UInt64[] _data1 = new UInt64[Op1ElementCount];
private static UInt64[] _data2 = new UInt64[Op2ElementCount];
private static Vector256<UInt64> _clsVar1;
private static Vector256<UInt64> _clsVar2;
private Vector256<UInt64> _fld1;
private Vector256<UInt64> _fld2;
private SimpleBinaryOpTest__DataTable<UInt64, UInt64, UInt64> _dataTable;
static SimpleBinaryOpTest__AndNotUInt64()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (ulong)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _clsVar1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (ulong)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _clsVar2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), VectorSize);
}
public SimpleBinaryOpTest__AndNotUInt64()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (ulong)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (ulong)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (ulong)(random.Next(0, int.MaxValue)); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (ulong)(random.Next(0, int.MaxValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<UInt64, UInt64, UInt64>(_data1, _data2, new UInt64[RetElementCount], VectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx2.AndNot(
Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx2.AndNot(
Avx.LoadVector256((UInt64*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt64*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx2.AndNot(
Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.AndNot), new Type[] { typeof(Vector256<UInt64>), typeof(Vector256<UInt64>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.AndNot), new Type[] { typeof(Vector256<UInt64>), typeof(Vector256<UInt64>) })
.Invoke(null, new object[] {
Avx.LoadVector256((UInt64*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt64*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.AndNot), new Type[] { typeof(Vector256<UInt64>), typeof(Vector256<UInt64>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx2.AndNot(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray2Ptr);
var result = Avx2.AndNot(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Avx.LoadVector256((UInt64*)(_dataTable.inArray1Ptr));
var right = Avx.LoadVector256((UInt64*)(_dataTable.inArray2Ptr));
var result = Avx2.AndNot(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray1Ptr));
var right = Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray2Ptr));
var result = Avx2.AndNot(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__AndNotUInt64();
var result = Avx2.AndNot(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx2.AndNot(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector256<UInt64> left, Vector256<UInt64> right, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray1 = new UInt64[Op1ElementCount];
UInt64[] inArray2 = new UInt64[Op2ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray1 = new UInt64[Op1ElementCount];
UInt64[] inArray2 = new UInt64[Op2ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt64[] left, UInt64[] right, UInt64[] result, [CallerMemberName] string method = "")
{
if ((ulong)(~left[0] & right[0]) != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((ulong)(~left[i] & right[i]) != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.AndNot)}<UInt64>(Vector256<UInt64>, Vector256<UInt64>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void AbsByte()
{
var test = new SimpleUnaryOpTest__AbsByte();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__AbsByte
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(SByte);
private const int RetElementCount = VectorSize / sizeof(Byte);
private static SByte[] _data = new SByte[Op1ElementCount];
private static Vector128<SByte> _clsVar;
private Vector128<SByte> _fld;
private SimpleUnaryOpTest__DataTable<Byte, SByte> _dataTable;
static SimpleUnaryOpTest__AbsByte()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (sbyte)(random.Next(sbyte.MinValue + 1, sbyte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar), ref Unsafe.As<SByte, byte>(ref _data[0]), VectorSize);
}
public SimpleUnaryOpTest__AbsByte()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (sbyte)(random.Next(sbyte.MinValue + 1, sbyte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld), ref Unsafe.As<SByte, byte>(ref _data[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (sbyte)(random.Next(sbyte.MinValue + 1, sbyte.MaxValue)); }
_dataTable = new SimpleUnaryOpTest__DataTable<Byte, SByte>(_data, new Byte[RetElementCount], VectorSize);
}
public bool IsSupported => Ssse3.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Ssse3.Abs(
Unsafe.Read<Vector128<SByte>>(_dataTable.inArrayPtr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Ssse3.Abs(
Sse2.LoadVector128((SByte*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Ssse3.Abs(
Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Ssse3).GetMethod(nameof(Ssse3.Abs), new Type[] { typeof(Vector128<SByte>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<SByte>>(_dataTable.inArrayPtr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Ssse3).GetMethod(nameof(Ssse3.Abs), new Type[] { typeof(Vector128<SByte>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((SByte*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Ssse3).GetMethod(nameof(Ssse3.Abs), new Type[] { typeof(Vector128<SByte>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Ssse3.Abs(
_clsVar
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var firstOp = Unsafe.Read<Vector128<SByte>>(_dataTable.inArrayPtr);
var result = Ssse3.Abs(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var firstOp = Sse2.LoadVector128((SByte*)(_dataTable.inArrayPtr));
var result = Ssse3.Abs(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var firstOp = Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArrayPtr));
var result = Ssse3.Abs(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleUnaryOpTest__AbsByte();
var result = Ssse3.Abs(test._fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Ssse3.Abs(_fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<SByte> firstOp, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray = new SByte[Op1ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray = new SByte[Op1ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(SByte[] firstOp, Byte[] result, [CallerMemberName] string method = "")
{
if (result[0] != Math.Abs(firstOp[0]))
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != Math.Abs(firstOp[i]))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Ssse3)}.{nameof(Ssse3.Abs)}<Byte>(Vector128<SByte>): {method} failed:");
Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.