context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
//
// System.Data.SqlClient.SqlResultSet
//
// Author:
// Tim Coleman ([email protected])
//
// Copyright (C) Tim Coleman, 2003
//
//
// 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.
//
#if NET_2_0
using System;
using System.Collections;
using System.Data;
using System.Data.Sql;
using System.Data.SqlTypes;
namespace System.Data.SqlClient {
public sealed class SqlResultSet : MarshalByRefObject, IEnumerable, ISqlResultSet, ISqlReader, ISqlRecord, ISqlGetTypedData, IGetTypedData, ISqlUpdatableRecord, ISqlSetTypedData, IDataReader, IDisposable, IDataUpdatableRecord, IDataRecord, ISetTypedData
{
#region Fields
bool disposed;
#endregion // Fields
#region Properties
public int Depth {
get { throw new NotImplementedException (); }
}
public int FieldCount {
get { throw new NotImplementedException (); }
}
public bool HasRows {
get { throw new NotImplementedException (); }
}
public int HiddenFieldCount {
get { throw new NotImplementedException (); }
}
object IDataRecord.this [int x] {
get { return this [x]; }
}
object IDataRecord.this [string x] {
get { return this [x]; }
}
public bool IsClosed {
get { throw new NotImplementedException (); }
}
public object this [int index] {
get { throw new NotImplementedException (); }
set { throw new NotImplementedException (); }
}
public object this [string name] {
get { throw new NotImplementedException (); }
set { throw new NotImplementedException (); }
}
public int RecordsAffected {
get { throw new NotImplementedException (); }
}
public bool Scrollable {
get { throw new NotImplementedException (); }
}
public ResultSetSensitivity Sensitivity {
get { throw new NotImplementedException (); }
}
public bool Updatable {
get { throw new NotImplementedException (); }
}
#endregion // Properties
#region Methods
[MonoTODO]
public void Close ()
{
throw new NotImplementedException ();
}
[MonoTODO]
public ISqlUpdatableRecord CreateRecord ()
{
throw new NotImplementedException ();
}
[MonoTODO]
public void Delete ()
{
throw new NotImplementedException ();
}
[MonoTODO]
private void Dispose (bool disposing)
{
if (!disposed) {
if (disposing) {
Close ();
}
disposed = true;
}
}
[MonoTODO]
public bool GetBoolean (int i)
{
throw new NotImplementedException ();
}
[MonoTODO]
public byte GetByte (int i)
{
throw new NotImplementedException ();
}
[MonoTODO]
public long GetBytes (int i, long dataIndex, byte[] buffer, int bufferIndex, int length)
{
throw new NotImplementedException ();
}
[MonoTODO]
public char GetChar (int i)
{
throw new NotImplementedException ();
}
[MonoTODO]
public long GetChars (int i, long dataIndex, char[] buffer, int bufferIndex, int length)
{
throw new NotImplementedException ();
}
[MonoTODO]
public IDataReader GetData (int i)
{
throw new NotImplementedException ();
}
[MonoTODO]
public string GetDataTypeName (int i)
{
throw new NotImplementedException ();
}
[MonoTODO]
public DateTime GetDateTime (int i)
{
throw new NotImplementedException ();
}
[MonoTODO]
public decimal GetDecimal (int i)
{
throw new NotImplementedException ();
}
[MonoTODO]
public double GetDouble (int i)
{
throw new NotImplementedException ();
}
[MonoTODO]
public Type GetFieldType (int i)
{
throw new NotImplementedException ();
}
[MonoTODO]
public float GetFloat (int i)
{
throw new NotImplementedException ();
}
[MonoTODO]
public Guid GetGuid (int i)
{
throw new NotImplementedException ();
}
[MonoTODO]
public short GetInt16 (int i)
{
throw new NotImplementedException ();
}
[MonoTODO]
public int GetInt32 (int i)
{
throw new NotImplementedException ();
}
[MonoTODO]
public long GetInt64 (int i)
{
throw new NotImplementedException ();
}
[MonoTODO]
public string GetName (int i)
{
throw new NotImplementedException ();
}
[MonoTODO]
public object GetObjectRef (int i)
{
throw new NotImplementedException ();
}
[MonoTODO]
public int GetOrdinal (string name)
{
throw new NotImplementedException ();
}
[MonoTODO]
public DataTable GetSchemaTable ()
{
throw new NotImplementedException ();
}
[MonoTODO]
public SqlBinary GetSqlBinary (int i)
{
throw new NotImplementedException ();
}
[MonoTODO]
public SqlBoolean GetSqlBoolean (int i)
{
throw new NotImplementedException ();
}
[MonoTODO]
public SqlByte GetSqlByte (int i)
{
throw new NotImplementedException ();
}
[MonoTODO]
public SqlBytes GetSqlBytes (int i)
{
throw new NotImplementedException ();
}
[MonoTODO]
public SqlBytes GetSqlBytesRef (int i)
{
throw new NotImplementedException ();
}
[MonoTODO]
public SqlChars GetSqlChars (int i)
{
throw new NotImplementedException ();
}
[MonoTODO]
public SqlChars GetSqlCharsRef (int i)
{
throw new NotImplementedException ();
}
[MonoTODO]
public SqlDate GetSqlDate (int i)
{
throw new NotImplementedException ();
}
[MonoTODO]
public SqlDateTime GetSqlDateTime (int i)
{
throw new NotImplementedException ();
}
[MonoTODO]
public SqlDecimal GetSqlDecimal (int i)
{
throw new NotImplementedException ();
}
[MonoTODO]
public SqlDouble GetSqlDouble (int i)
{
throw new NotImplementedException ();
}
[MonoTODO]
public SqlGuid GetSqlGuid (int i)
{
throw new NotImplementedException ();
}
[MonoTODO]
public SqlInt16 GetSqlInt16 (int i)
{
throw new NotImplementedException ();
}
[MonoTODO]
public SqlInt32 GetSqlInt32 (int i)
{
throw new NotImplementedException ();
}
[MonoTODO]
public SqlInt64 GetSqlInt64 (int i)
{
throw new NotImplementedException ();
}
[MonoTODO]
public SqlMetaData GetSqlMetaData (int i)
{
throw new NotImplementedException ();
}
[MonoTODO]
public SqlMoney GetSqlMoney (int i)
{
throw new NotImplementedException ();
}
[MonoTODO]
public SqlSingle GetSqlSingle (int i)
{
throw new NotImplementedException ();
}
[MonoTODO]
public SqlString GetSqlString (int i)
{
throw new NotImplementedException ();
}
[MonoTODO]
public SqlTime GetSqlTime (int i)
{
throw new NotImplementedException ();
}
[MonoTODO]
public SqlUtcDateTime GetSqlUtcDateTime (int i)
{
throw new NotImplementedException ();
}
[MonoTODO]
public object GetSqlValue (int i)
{
throw new NotImplementedException ();
}
[MonoTODO]
public int GetSqlValues (object[] values)
{
throw new NotImplementedException ();
}
[MonoTODO]
public SqlXmlReader GetSqlXmlReader (int i)
{
throw new NotImplementedException ();
}
[MonoTODO]
public string GetString (int i)
{
throw new NotImplementedException ();
}
[MonoTODO]
public object GetValue (int i)
{
throw new NotImplementedException ();
}
[MonoTODO]
public int GetValues (object[] values)
{
throw new NotImplementedException ();
}
void IDisposable.Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
[MonoTODO]
IEnumerator IEnumerable.GetEnumerator ()
{
throw new NotImplementedException ();
}
[MonoTODO]
public void Insert (ISqlRecord record)
{
throw new NotImplementedException ();
}
[MonoTODO]
public bool IsDBNull (int i)
{
throw new NotImplementedException ();
}
[MonoTODO]
public bool IsSetAsDefault (int i)
{
throw new NotImplementedException ();
}
[MonoTODO]
public bool NextResult ()
{
throw new NotImplementedException ();
}
[MonoTODO]
public bool Read ()
{
throw new NotImplementedException ();
}
[MonoTODO]
public bool ReadAbsolute (int position)
{
throw new NotImplementedException ();
}
[MonoTODO]
public bool ReadFirst ()
{
throw new NotImplementedException ();
}
[MonoTODO]
public bool ReadLast ()
{
throw new NotImplementedException ();
}
[MonoTODO]
public bool ReadPrevious ()
{
throw new NotImplementedException ();
}
[MonoTODO]
public bool ReadRelative (int position)
{
throw new NotImplementedException ();
}
[MonoTODO]
public void SetBoolean (int i, bool value)
{
throw new NotImplementedException ();
}
[MonoTODO]
public void SetByte (int i, byte value)
{
throw new NotImplementedException ();
}
[MonoTODO]
public void SetBytes (int i, long dataIndex, byte[] buffer, int bufferIndex, int length)
{
throw new NotImplementedException ();
}
[MonoTODO]
public void SetChar (int i, char value)
{
throw new NotImplementedException ();
}
[MonoTODO]
public void SetChars (int i, long dataIndex, char[] buffer, int bufferIndex, int length)
{
throw new NotImplementedException ();
}
[MonoTODO]
public void SetDateTime (int i, DateTime value)
{
throw new NotImplementedException ();
}
[MonoTODO]
public void SetDecimal (int i, decimal value)
{
throw new NotImplementedException ();
}
[MonoTODO]
public void SetDefault (int i)
{
throw new NotImplementedException ();
}
[MonoTODO]
public void SetDouble (int i, double value)
{
throw new NotImplementedException ();
}
[MonoTODO]
public void SetFloat (int i, float value)
{
throw new NotImplementedException ();
}
[MonoTODO]
public void SetGuid (int i, Guid value)
{
throw new NotImplementedException ();
}
[MonoTODO]
public void SetInt16 (int i, short value)
{
throw new NotImplementedException ();
}
[MonoTODO]
public void SetInt32 (int i, int value)
{
throw new NotImplementedException ();
}
[MonoTODO]
public void SetInt64 (int i, long value)
{
throw new NotImplementedException ();
}
[MonoTODO]
public void SetObjectRef (int i, object buffer)
{
throw new NotImplementedException ();
}
[MonoTODO]
public void SetSqlBinary (int i, SqlBinary value)
{
throw new NotImplementedException ();
}
[MonoTODO]
public void SetSqlBoolean (int i, SqlBoolean value)
{
throw new NotImplementedException ();
}
[MonoTODO]
public void SetSqlByte (int i, SqlByte value)
{
throw new NotImplementedException ();
}
[MonoTODO]
public void SetSqlBytes (int i, SqlBytes value)
{
throw new NotImplementedException ();
}
[MonoTODO]
public void SetSqlBytesRef (int i, SqlBytes value)
{
throw new NotImplementedException ();
}
[MonoTODO]
public void SetSqlChars (int i, SqlChars value)
{
throw new NotImplementedException ();
}
[MonoTODO]
public void SetSqlCharsRef (int i, SqlChars value)
{
throw new NotImplementedException ();
}
[MonoTODO]
public void SetSqlDate (int i, SqlDate value)
{
throw new NotImplementedException ();
}
[MonoTODO]
public void SetSqlDateTime (int i, SqlDateTime value)
{
throw new NotImplementedException ();
}
[MonoTODO]
public void SetSqlDecimal (int i, SqlDecimal value)
{
throw new NotImplementedException ();
}
[MonoTODO]
public void SetSqlDouble (int i, SqlDouble value)
{
throw new NotImplementedException ();
}
[MonoTODO]
public void SetSqlGuid (int i, SqlGuid value)
{
throw new NotImplementedException ();
}
[MonoTODO]
public void SetSqlInt16 (int i, SqlInt16 value)
{
throw new NotImplementedException ();
}
[MonoTODO]
public void SetSqlInt32 (int i, SqlInt32 value)
{
throw new NotImplementedException ();
}
[MonoTODO]
public void SetSqlInt64 (int i, SqlInt64 value)
{
throw new NotImplementedException ();
}
[MonoTODO]
public void SetSqlMoney (int i, SqlMoney value)
{
throw new NotImplementedException ();
}
[MonoTODO]
public void SetSqlSingle (int i, SqlSingle value)
{
throw new NotImplementedException ();
}
[MonoTODO]
public void SetSqlString (int i, SqlString value)
{
throw new NotImplementedException ();
}
[MonoTODO]
public void SetSqlTime (int i, SqlTime value)
{
throw new NotImplementedException ();
}
[MonoTODO]
public void SetSqlUtcDateTime (int i, SqlUtcDateTime value)
{
throw new NotImplementedException ();
}
[MonoTODO]
public void SetSqlXmlReader (int i, SqlXmlReader value)
{
throw new NotImplementedException ();
}
[MonoTODO]
public void SetString (int i, string value)
{
throw new NotImplementedException ();
}
[MonoTODO]
public void SetValue (int i, object value)
{
throw new NotImplementedException ();
}
[MonoTODO]
public int SetValues (object[] value)
{
throw new NotImplementedException ();
}
[MonoTODO]
public void Update ()
{
throw new NotImplementedException ();
}
#endregion // Methods
}
}
#endif
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections;
using System.Collections.ObjectModel;
using System.Management.Automation.Internal;
using System.Runtime.Serialization;
using System.Threading;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation.Runspaces
{
#region Exceptions
/// <summary>
/// Defines exception which is thrown when state of the pipeline is different
/// from expected state.
/// </summary>
[Serializable]
public class InvalidPipelineStateException : SystemException
{
/// <summary>
/// Initializes a new instance of the InvalidPipelineStateException class.
/// </summary>
public InvalidPipelineStateException()
: base(StringUtil.Format(RunspaceStrings.InvalidPipelineStateStateGeneral))
{
}
/// <summary>
/// Initializes a new instance of the InvalidPipelineStateException class
/// with a specified error message.
/// </summary>
/// <param name="message">
/// The error message that explains the reason for the exception.
/// </param>
public InvalidPipelineStateException(string message)
: base(message)
{
}
/// <summary>
/// Initializes a new instance of the InvalidPipelineStateException class
/// with a specified error message and a reference to the inner exception that is the cause of this exception.
/// </summary>
/// <param name="message">
/// The error message that explains the reason for the exception.
/// </param>
/// <param name="innerException">
/// The exception that is the cause of the current exception.
/// </param>
public InvalidPipelineStateException(string message, Exception innerException)
: base(message, innerException)
{
}
/// <summary>
/// Initializes a new instance of the InvalidPipelineStateException and defines value of
/// CurrentState and ExpectedState.
/// </summary>
/// <param name="message">The error message that explains the reason for the exception.
/// </param>
/// <param name="currentState">Current state of pipeline.</param>
/// <param name="expectedState">Expected state of pipeline.</param>
internal InvalidPipelineStateException(string message, PipelineState currentState, PipelineState expectedState)
: base(message)
{
_expectedState = expectedState;
_currentState = currentState;
}
#region ISerializable Members
// 2005/04/20-JonN No need to implement GetObjectData
// if all fields are static or [NonSerialized]
/// <summary>
/// Initializes a new instance of the <see cref="InvalidPipelineStateException"/>
/// class with serialized data.
/// </summary>
/// <param name="info">
/// The <see cref="SerializationInfo"/> that holds the serialized object
/// data about the exception being thrown.
/// </param>
/// <param name="context">
/// The <see cref="StreamingContext"/> that contains contextual information
/// about the source or destination.
/// </param>
private InvalidPipelineStateException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
#endregion
/// <summary>
/// Gets CurrentState of the pipeline.
/// </summary>
public PipelineState CurrentState
{
get { return _currentState; }
}
/// <summary>
/// Gets ExpectedState of the pipeline.
/// </summary>
public PipelineState ExpectedState
{
get { return _expectedState; }
}
/// <summary>
/// State of pipeline when exception was thrown.
/// </summary>
[NonSerialized]
private readonly PipelineState _currentState = 0;
/// <summary>
/// States of the pipeline expected in method which throws this exception.
/// </summary>
[NonSerialized]
private readonly PipelineState _expectedState = 0;
}
#endregion Exceptions
#region PipelineState
/// <summary>
/// Enumerated type defining the state of the Pipeline.
/// </summary>
public enum PipelineState
{
/// <summary>
/// The pipeline has not been started.
/// </summary>
NotStarted = 0,
/// <summary>
/// The pipeline is executing.
/// </summary>
Running = 1,
/// <summary>
/// The pipeline is stoping execution.
/// </summary>
Stopping = 2,
/// <summary>
/// The pipeline is completed due to a stop request.
/// </summary>
Stopped = 3,
/// <summary>
/// The pipeline has completed.
/// </summary>
Completed = 4,
/// <summary>
/// The pipeline completed abnormally due to an error.
/// </summary>
Failed = 5,
/// <summary>
/// The pipeline is disconnected from remote running command.
/// </summary>
Disconnected = 6
}
/// <summary>
/// Type which has information about PipelineState and Exception
/// associated with PipelineState.
/// </summary>
public sealed class PipelineStateInfo
{
#region constructors
/// <summary>
/// Constructor for state changes not resulting from an error.
/// </summary>
/// <param name="state">Execution state.</param>
internal PipelineStateInfo(PipelineState state)
: this(state, null)
{
}
/// <summary>
/// Constructor for state changes with an optional error.
/// </summary>
/// <param name="state">The new state.</param>
/// <param name="reason">A non-null exception if the state change was
/// caused by an error,otherwise; null.
/// </param>
internal PipelineStateInfo(PipelineState state, Exception reason)
{
State = state;
Reason = reason;
}
/// <summary>
/// Copy constructor to support cloning.
/// </summary>
/// <param name="pipelineStateInfo">Source information.</param>
/// <throws>
/// ArgumentNullException when <paramref name="pipelineStateInfo"/> is null.
/// </throws>
internal PipelineStateInfo(PipelineStateInfo pipelineStateInfo)
{
Dbg.Assert(pipelineStateInfo != null, "caller should validate the parameter");
State = pipelineStateInfo.State;
Reason = pipelineStateInfo.Reason;
}
#endregion constructors
#region public_properties
/// <summary>
/// The state of the runspace.
/// </summary>
/// <remarks>
/// This value indicates the state of the pipeline after the change.
/// </remarks>
public PipelineState State { get; }
/// <summary>
/// The reason for the state change, if caused by an error.
/// </summary>
/// <remarks>
/// The value of this property is non-null if the state
/// changed due to an error. Otherwise, the value of this
/// property is null.
/// </remarks>
public Exception Reason { get; }
#endregion public_properties
/// <summary>
/// Clones this object.
/// </summary>
/// <returns>Cloned object.</returns>
internal PipelineStateInfo Clone()
{
return new PipelineStateInfo(this);
}
}
/// <summary>
/// Event arguments passed to PipelineStateEvent handlers
/// <see cref="Pipeline.StateChanged"/> event.
/// </summary>
public sealed class PipelineStateEventArgs : EventArgs
{
#region constructors
/// <summary>
/// Constructor PipelineStateEventArgs from PipelineStateInfo.
/// </summary>
/// <param name="pipelineStateInfo">The current state of the
/// pipeline.</param>
/// <throws>
/// ArgumentNullException when <paramref name="pipelineStateInfo"/> is null.
/// </throws>
internal PipelineStateEventArgs(PipelineStateInfo pipelineStateInfo)
{
Dbg.Assert(pipelineStateInfo != null, "caller should validate the parameter");
PipelineStateInfo = pipelineStateInfo;
}
#endregion constructors
#region public_properties
/// <summary>
/// Info about current state of pipeline.
/// </summary>
public PipelineStateInfo PipelineStateInfo { get; }
#endregion public_properties
}
#endregion ExecutionState
/// <summary>
/// Defines a class which can be used to invoke a pipeline of commands.
/// </summary>
public abstract class Pipeline : IDisposable
{
#region constructor
/// <summary>
/// Explicit default constructor.
/// </summary>
internal Pipeline(Runspace runspace)
: this(runspace, new CommandCollection())
{
}
/// <summary>
/// Constructor to initialize both Runspace and Command to invoke.
/// Caller should make sure that "command" is not null.
/// </summary>
/// <param name="runspace">
/// Runspace to use for the command invocation.
/// </param>
/// <param name="command">
/// command to Invoke.
/// Caller should make sure that "command" is not null.
/// </param>
internal Pipeline(Runspace runspace, CommandCollection command)
{
if (runspace == null)
{
PSTraceSource.NewArgumentNullException(nameof(runspace));
}
// This constructor is used only internally.
// Caller should make sure the input is valid
Dbg.Assert(command != null, "Command cannot be null");
InstanceId = runspace.GeneratePipelineId();
Commands = command;
// Reset the AMSI session so that it is re-initialized
// when the next script block is parsed.
AmsiUtils.CloseSession();
}
#endregion constructor
#region properties
/// <summary>
/// Gets the runspace this pipeline is created on.
/// </summary>
public abstract Runspace Runspace { get; }
/// <summary>
/// Gets the property which indicates if this pipeline is nested.
/// </summary>
public abstract bool IsNested { get; }
/// <summary>
/// Gets the property which indicates if this pipeline is a child pipeline.
///
/// IsChild flag makes it possible for the pipeline to differentiate between
/// a true v1 nested pipeline and the cmdlets calling cmdlets case. See bug
/// 211462.
/// </summary>
internal virtual bool IsChild
{
get { return false; }
set { }
}
/// <summary>
/// Gets input writer for this pipeline.
/// </summary>
/// <remarks>
/// When the caller calls Input.Write(), the caller writes to the
/// input of the pipeline. Thus, <paramref name="Input"/>
/// is a PipelineWriter or "thing which can be written to".
/// Note:Input must be closed after Pipeline.InvokeAsync for InvokeAsync to
/// finish.
/// </remarks>
public abstract PipelineWriter Input { get; }
/// <summary>
/// Gets the output reader for this pipeline.
/// </summary>
/// <remarks>
/// When the caller calls Output.Read(), the caller reads from the
/// output of the pipeline. Thus, <paramref name="Output"/>
/// is a PipelineReader or "thing which can be read from".
/// </remarks>
public abstract PipelineReader<PSObject> Output { get; }
/// <summary>
/// Gets the error output reader for this pipeline.
/// </summary>
/// <remarks>
/// When the caller calls Error.Read(), the caller reads from the
/// output of the pipeline. Thus, <paramref name="Error"/>
/// is a PipelineReader or "thing which can be read from".
///
/// This is the non-terminating error stream from the command.
/// In this release, the objects read from this PipelineReader
/// are PSObjects wrapping ErrorRecords.
/// </remarks>
public abstract PipelineReader<object> Error { get; }
/// <summary>
/// Gets Info about current state of the pipeline.
/// </summary>
/// <remarks>
/// This value indicates the state of the pipeline after the change.
/// </remarks>
public abstract PipelineStateInfo PipelineStateInfo { get; }
/// <summary>
/// True if pipeline execution encountered and error.
/// It will always be true if _reason is non-null
/// since an exception occurred. For other error types,
/// It has to be set manually.
/// </summary>
public virtual bool HadErrors
{
get { return _hadErrors; }
}
private bool _hadErrors;
internal void SetHadErrors(bool status)
{
_hadErrors = _hadErrors || status;
}
/// <summary>
/// Gets the unique identifier for this pipeline. This identifier is unique with in
/// the scope of Runspace.
/// </summary>
public long InstanceId { get; }
/// <summary>
/// Gets the collection of commands for this pipeline.
/// </summary>
public CommandCollection Commands { get; private set; }
/// <summary>
/// If this property is true, SessionState is updated for this
/// pipeline state.
/// </summary>
public bool SetPipelineSessionState { get; set; } = true;
/// <summary>
/// Settings for the pipeline invocation thread.
/// </summary>
internal PSInvocationSettings InvocationSettings { get; set; }
/// <summary>
/// If this flag is true, the commands in this Pipeline will redirect the global error output pipe
/// (ExecutionContext.ShellFunctionErrorOutputPipe) to the command's error output pipe.
///
/// When the global error output pipe is not set, $ErrorActionPreference is not checked and all
/// errors are treated as terminating errors.
///
/// On V1, the global error output pipe is redirected to the command's error output pipe only when
/// it has already been redirected. The command-line host achieves this redirection by merging the
/// error output into the output pipe so it checks $ErrorActionPreference all right. However, when
/// the Pipeline class is used programmatically the global error output pipe is not set and the first
/// error terminates the pipeline.
///
/// This flag is used to force the redirection. By default it is false to maintain compatibility with
/// V1, but the V2 hosting interface (PowerShell class) sets this flag to true to ensure the global
/// error output pipe is always set and $ErrorActionPreference is checked when invoking the Pipeline.
/// </summary>
internal bool RedirectShellErrorOutputPipe { get; set; } = false;
#endregion properties
#region events
/// <summary>
/// Event raised when Pipeline's state changes.
/// </summary>
public abstract event EventHandler<PipelineStateEventArgs> StateChanged;
#endregion events
#region methods
/// <summary>
/// Invoke the pipeline, synchronously, returning the results as an array of
/// objects.
/// </summary>
/// <remarks>If using synchronous invoke, do not close
/// input objectWriter. Synchronous invoke will always close the input
/// objectWriter.
/// </remarks>
/// <exception cref="InvalidOperationException">
/// No command is added to pipeline
/// </exception>
/// <exception cref="InvalidPipelineStateException">
/// PipelineState is not NotStarted.
/// </exception>
/// <exception cref="InvalidOperationException">
/// 1) A pipeline is already executing. Pipeline cannot execute
/// concurrently.
/// 2) Attempt is made to invoke a nested pipeline directly. Nested
/// pipeline must be invoked from a running pipeline.
/// </exception>
/// <exception cref="InvalidRunspaceStateException">
/// RunspaceState is not Open
/// </exception>
/// <exception cref="ObjectDisposedException">
/// Pipeline already disposed
/// </exception>
/// <exception cref="ScriptCallDepthException">
/// The script recursed too deeply into script functions.
/// There is a fixed limit on the depth of recursion.
/// </exception>
/// <exception cref="System.Security.SecurityException">
/// A CLR security violation occurred. Typically, this happens
/// because the current CLR permissions do not allow adequate
/// reflection access to a cmdlet assembly.
/// </exception>
/// <exception cref="RuntimeException">
/// Pipeline.Invoke can throw a variety of exceptions derived
/// from RuntimeException. The most likely of these exceptions
/// are listed below.
/// </exception>
/// <exception cref="ParameterBindingException">
/// One of more parameters or parameter values specified for
/// a cmdlet are not valid, or mandatory parameters for a cmdlet
/// were not specified.
/// </exception>
/// <exception cref="CmdletInvocationException">
/// A cmdlet generated a terminating error.
/// </exception>
/// <exception cref="CmdletProviderInvocationException">
/// A provider generated a terminating error.
/// </exception>
/// <exception cref="ActionPreferenceStopException">
/// The ActionPreference.Stop or ActionPreference.Inquire policy
/// triggered a terminating error.
/// </exception>
/// <exception cref="PipelineStoppedException">
/// The pipeline was terminated asynchronously.
/// </exception>
/// <exception cref="MetadataException">
/// If there is an error generating the metadata for dynamic parameters.
/// </exception>
public Collection<PSObject> Invoke()
{
return Invoke(null);
}
/// <summary>
/// Invoke the pipeline, synchronously, returning the results as an array of objects.
/// </summary>
/// <param name="input">an array of input objects to pass to the pipeline.
/// Array may be empty but may not be null</param>
/// <returns>An array of zero or more result objects.</returns>
/// <remarks>If using synchronous exectute, do not close
/// input objectWriter. Synchronous invoke will always close the input
/// objectWriter.
/// </remarks>
/// <exception cref="InvalidOperationException">
/// No command is added to pipeline
/// </exception>
/// <exception cref="InvalidPipelineStateException">
/// PipelineState is not NotStarted.
/// </exception>
/// <exception cref="InvalidOperationException">
/// 1) A pipeline is already executing. Pipeline cannot execute
/// concurrently.
/// 2) Attempt is made to invoke a nested pipeline directly. Nested
/// pipeline must be invoked from a running pipeline.
/// </exception>
/// <exception cref="InvalidRunspaceStateException">
/// RunspaceState is not Open
/// </exception>
/// <exception cref="ObjectDisposedException">
/// Pipeline already disposed
/// </exception>
/// <exception cref="ScriptCallDepthException">
/// The script recursed too deeply into script functions.
/// There is a fixed limit on the depth of recursion.
/// </exception>
/// <exception cref="System.Security.SecurityException">
/// A CLR security violation occurred. Typically, this happens
/// because the current CLR permissions do not allow adequate
/// reflection access to a cmdlet assembly.
/// </exception>
/// <exception cref="RuntimeException">
/// Pipeline.Invoke can throw a variety of exceptions derived
/// from RuntimeException. The most likely of these exceptions
/// are listed below.
/// </exception>
/// <exception cref="ParameterBindingException">
/// One of more parameters or parameter values specified for
/// a cmdlet are not valid, or mandatory parameters for a cmdlet
/// were not specified.
/// </exception>
/// <exception cref="CmdletInvocationException">
/// A cmdlet generated a terminating error.
/// </exception>
/// <exception cref="CmdletProviderInvocationException">
/// A provider generated a terminating error.
/// </exception>
/// <exception cref="ActionPreferenceStopException">
/// The ActionPreference.Stop or ActionPreference.Inquire policy
/// triggered a terminating error.
/// </exception>
/// <exception cref="PipelineStoppedException">
/// The pipeline was terminated asynchronously.
/// </exception>
/// <exception cref="MetadataException">
/// If there is an error generating the metadata for dynamic parameters.
/// </exception>
public abstract Collection<PSObject> Invoke(IEnumerable input);
/// <summary>
/// Invoke the pipeline asynchronously.
/// </summary>
/// <remarks>
/// 1) Results are returned through the <see cref="Pipeline.Output"/> reader.
/// 2) When pipeline is invoked using InvokeAsync, invocation doesn't
/// finish until Input to pipeline is closed. Caller of InvokeAsync must close
/// the input pipe after all input has been written to input pipe. Input pipe
/// is closed by calling Pipeline.Input.Close();
///
/// If you want this pipeline to execute as a standalone command
/// (that is, using command-line parameters only),
/// be sure to call Pipeline.Input.Close() before calling
/// InvokeAsync(). Otherwise, the command will be executed
/// as though it had external input. If you observe that the
/// command isn't doing anything, this may be the reason.
/// </remarks>
/// <exception cref="InvalidOperationException">
/// No command is added to pipeline
/// </exception>
/// <exception cref="InvalidPipelineStateException">
/// PipelineState is not NotStarted.
/// </exception>
/// <exception cref="InvalidOperationException">
/// 1) A pipeline is already executing. Pipeline cannot execute
/// concurrently.
/// 2) InvokeAsync is called on nested pipeline. Nested pipeline
/// cannot be executed Asynchronously.
/// </exception>
/// <exception cref="InvalidRunspaceStateException">
/// RunspaceState is not Open
/// </exception>
/// <exception cref="ObjectDisposedException">
/// Pipeline already disposed
/// </exception>
public abstract void InvokeAsync();
/// <summary>
/// Synchronous call to stop the running pipeline.
/// </summary>
public abstract void Stop();
/// <summary>
/// Asynchronous call to stop the running pipeline.
/// </summary>
public abstract void StopAsync();
/// <summary>
/// Creates a new <see cref="Pipeline"/> that is a copy of the current instance.
/// </summary>
/// <returns>A new <see cref="Pipeline"/> that is a copy of this instance.</returns>
public abstract Pipeline Copy();
/// <summary>
/// Connects synchronously to a running command on a remote server.
/// The pipeline object must be in the disconnected state.
/// </summary>
/// <returns>A collection of result objects.</returns>
public abstract Collection<PSObject> Connect();
/// <summary>
/// Connects asynchronously to a running command on a remote server.
/// </summary>
public abstract void ConnectAsync();
/// <summary>
/// Sets the command collection.
/// </summary>
/// <param name="commands">Command collection to set.</param>
/// <remarks>called by ClientRemotePipeline</remarks>
internal void SetCommandCollection(CommandCollection commands)
{
Commands = commands;
}
/// <summary>
/// Sets the history string to the one that is specified.
/// </summary>
/// <param name="historyString">History string to set.</param>
internal abstract void SetHistoryString(string historyString);
/// <summary>
/// Invokes a remote command and immediately disconnects if
/// transport layer supports it.
/// </summary>
internal abstract void InvokeAsyncAndDisconnect();
#endregion methods
#region Remote data drain/block methods
/// <summary>
/// Blocks data arriving from remote session.
/// </summary>
internal virtual void SuspendIncomingData()
{
throw new PSNotImplementedException();
}
/// <summary>
/// Resumes data arrive from remote session.
/// </summary>
internal virtual void ResumeIncomingData()
{
throw new PSNotImplementedException();
}
/// <summary>
/// Blocking call that waits until the current remote data
/// queue is empty.
/// </summary>
internal virtual void DrainIncomingData()
{
throw new PSNotImplementedException();
}
#endregion
#region IDisposable Members
/// <summary>
/// Disposes the pipeline. If pipeline is running, dispose first
/// stops the pipeline.
/// </summary>
public
void
Dispose()
{
Dispose(!IsChild);
GC.SuppressFinalize(this);
}
/// <summary>
/// Protected dispose which can be overridden by derived classes.
/// </summary>
/// <param name="disposing"></param>
protected virtual
void
Dispose(bool disposing)
{
}
#endregion IDisposable Members
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace MusicApp.WebApi.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
using System;
using OpenCvSharp.Internal;
namespace OpenCvSharp
{
// ReSharper disable InconsistentNaming
/// <summary>
/// The Base Class for Background/Foreground Segmentation.
/// The class is only used to define the common interface for
/// the whole family of background/foreground segmentation algorithms.
/// </summary>
public class BackgroundSubtractorMOG2 : BackgroundSubtractor
{
/// <summary>
/// cv::Ptr<T>
/// </summary>
private Ptr? objectPtr;
#region Init & Disposal
/// <summary>
/// Creates MOG2 Background Subtractor.
/// </summary>
/// <param name="history">Length of the history.</param>
/// <param name="varThreshold">Threshold on the squared Mahalanobis distance between the pixel and the model
/// to decide whether a pixel is well described by the background model. This parameter does not affect the background update.</param>
/// <param name="detectShadows">If true, the algorithm will detect shadows and mark them. It decreases the speed a bit,
/// so if you do not need this feature, set the parameter to false.</param>
/// <returns></returns>
public static BackgroundSubtractorMOG2 Create(
int history = 500, double varThreshold = 16, bool detectShadows = true)
{
NativeMethods.HandleException(
NativeMethods.video_createBackgroundSubtractorMOG2(
history, varThreshold, detectShadows ? 1 : 0, out var ptr));
return new BackgroundSubtractorMOG2(ptr);
}
internal BackgroundSubtractorMOG2(IntPtr ptr)
{
objectPtr = new Ptr(ptr);
this.ptr = objectPtr.Get();
}
/// <summary>
/// Releases managed resources
/// </summary>
protected override void DisposeManaged()
{
objectPtr?.Dispose();
objectPtr = null;
ptr = IntPtr.Zero;
base.DisposeManaged();
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the number of last frames that affect the background model.
/// </summary>
public int History
{
get
{
ThrowIfDisposed();
if (objectPtr == null)
throw new NotSupportedException("objectPtr == null");
NativeMethods.HandleException(
NativeMethods.video_BackgroundSubtractorMOG2_getHistory(objectPtr.CvPtr, out var ret));
GC.KeepAlive(this);
return ret;
}
set
{
ThrowIfDisposed();
if (objectPtr == null)
throw new NotSupportedException("objectPtr == null");
NativeMethods.HandleException(
NativeMethods.video_BackgroundSubtractorMOG2_setHistory(objectPtr.CvPtr, value));
GC.KeepAlive(this);
}
}
/// <summary>
/// Gets or sets the number of gaussian components in the background model.
/// </summary>
public int NMixtures
{
get
{
ThrowIfDisposed();
if (objectPtr == null)
throw new NotSupportedException("objectPtr == null");
NativeMethods.HandleException(
NativeMethods.video_BackgroundSubtractorMOG2_getNMixtures(objectPtr.CvPtr, out var ret));
GC.KeepAlive(this);
return ret;
}
set
{
ThrowIfDisposed();
if (objectPtr == null)
throw new NotSupportedException("objectPtr == null");
NativeMethods.HandleException(
NativeMethods.video_BackgroundSubtractorMOG2_setNMixtures(objectPtr.CvPtr, value));
GC.KeepAlive(this);
}
}
/// <summary>
/// Gets or sets the "background ratio" parameter of the algorithm.
/// If a foreground pixel keeps semi-constant value for about backgroundRatio\*history frames, it's
/// considered background and added to the model as a center of a new component. It corresponds to TB
/// parameter in the paper.
/// </summary>
public double BackgroundRatio
{
get
{
ThrowIfDisposed();
if (objectPtr == null)
throw new NotSupportedException("objectPtr == null");
NativeMethods.HandleException(
NativeMethods.video_BackgroundSubtractorMOG2_getBackgroundRatio(objectPtr.CvPtr, out var ret));
GC.KeepAlive(this);
return ret;
}
set
{
ThrowIfDisposed();
if (objectPtr == null)
throw new NotSupportedException("objectPtr == null");
NativeMethods.HandleException(
NativeMethods.video_BackgroundSubtractorMOG2_setBackgroundRatio(objectPtr.CvPtr, value));
GC.KeepAlive(this);
}
}
/// <summary>
/// Gets or sets the variance threshold for the pixel-model match.
/// The main threshold on the squared Mahalanobis distance to decide if the sample is well described by
/// the background model or not. Related to Cthr from the paper.
/// </summary>
public double VarThreshold
{
get
{
ThrowIfDisposed();
if (objectPtr == null)
throw new NotSupportedException("objectPtr == null");
NativeMethods.HandleException(
NativeMethods.video_BackgroundSubtractorMOG2_getVarThreshold(objectPtr.CvPtr, out var ret));
GC.KeepAlive(this);
return ret;
}
set
{
ThrowIfDisposed();
if (objectPtr == null)
throw new NotSupportedException("objectPtr == null");
NativeMethods.HandleException(
NativeMethods.video_BackgroundSubtractorMOG2_setVarThreshold(objectPtr.CvPtr, value));
GC.KeepAlive(this);
}
}
/// <summary>
/// Gets or sets the variance threshold for the pixel-model match used for new mixture component generation.
/// Threshold for the squared Mahalanobis distance that helps decide when a sample is close to the
/// existing components (corresponds to Tg in the paper). If a pixel is not close to any component, it
/// is considered foreground or added as a new component. 3 sigma =\> Tg=3\*3=9 is default. A smaller Tg
/// value generates more components. A higher Tg value may result in a small number of components but they can grow too large.
/// </summary>
public double VarThresholdGen
{
get
{
ThrowIfDisposed();
if (objectPtr == null)
throw new NotSupportedException("objectPtr == null");
NativeMethods.HandleException(
NativeMethods.video_BackgroundSubtractorMOG2_getVarThresholdGen(objectPtr.CvPtr, out var ret));
GC.KeepAlive(this);
return ret;
}
set
{
ThrowIfDisposed();
if (objectPtr == null)
throw new NotSupportedException("objectPtr == null");
NativeMethods.HandleException(
NativeMethods.video_BackgroundSubtractorMOG2_setVarThresholdGen(objectPtr.CvPtr, value));
GC.KeepAlive(this);
}
}
/// <summary>
/// Gets or sets the initial variance of each gaussian component.
/// </summary>
public double VarInit
{
get
{
ThrowIfDisposed();
if (objectPtr == null)
throw new NotSupportedException("objectPtr == null");
NativeMethods.HandleException(
NativeMethods.video_BackgroundSubtractorMOG2_getVarInit(objectPtr.CvPtr, out var ret));
GC.KeepAlive(this);
return ret;
}
set
{
ThrowIfDisposed();
if (objectPtr == null)
throw new NotSupportedException("objectPtr == null");
NativeMethods.HandleException(
NativeMethods.video_BackgroundSubtractorMOG2_setVarInit(objectPtr.CvPtr, value));
GC.KeepAlive(this);
}
}
/// <summary>
///
/// </summary>
public double VarMin
{
get
{
ThrowIfDisposed();
if (objectPtr == null)
throw new NotSupportedException("objectPtr == null");
NativeMethods.HandleException(
NativeMethods.video_BackgroundSubtractorMOG2_getVarMin(objectPtr.CvPtr, out var ret));
GC.KeepAlive(this);
return ret;
}
set
{
ThrowIfDisposed();
if (objectPtr == null)
throw new NotSupportedException("objectPtr == null");
NativeMethods.HandleException(
NativeMethods.video_BackgroundSubtractorMOG2_setVarMin(objectPtr.CvPtr, value));
GC.KeepAlive(this);
}
}
/// <summary>
///
/// </summary>
public double VarMax
{
get
{
ThrowIfDisposed();
if (objectPtr == null)
throw new NotSupportedException("objectPtr == null");
NativeMethods.HandleException(
NativeMethods.video_BackgroundSubtractorMOG2_getVarMax(objectPtr.CvPtr, out var ret));
GC.KeepAlive(this);
return ret;
}
set
{
ThrowIfDisposed();
if (objectPtr == null)
throw new NotSupportedException("objectPtr == null");
NativeMethods.HandleException(
NativeMethods.video_BackgroundSubtractorMOG2_setVarMax(objectPtr.CvPtr, value));
GC.KeepAlive(this);
}
}
/// <summary>
/// Gets or sets the complexity reduction threshold.
/// This parameter defines the number of samples needed to accept to prove the component exists. CT=0.05
/// is a default value for all the samples. By setting CT=0 you get an algorithm very similar to the standard Stauffer&Grimson algorithm.
/// </summary>
public double ComplexityReductionThreshold
{
get
{
ThrowIfDisposed();
if (objectPtr == null)
throw new NotSupportedException("objectPtr == null");
NativeMethods.HandleException(
NativeMethods.video_BackgroundSubtractorMOG2_getComplexityReductionThreshold(objectPtr.CvPtr, out var ret));
GC.KeepAlive(this);
return ret;
}
set
{
ThrowIfDisposed();
if (objectPtr == null)
throw new NotSupportedException("objectPtr == null");
NativeMethods.HandleException(
NativeMethods.video_BackgroundSubtractorMOG2_setComplexityReductionThreshold(objectPtr.CvPtr, value));
GC.KeepAlive(this);
}
}
/// <summary>
/// Gets or sets the shadow detection flag.
/// If true, the algorithm detects shadows and marks them. See createBackgroundSubtractorKNN for details.
/// </summary>
public bool DetectShadows
{
get
{
ThrowIfDisposed();
if (objectPtr == null)
throw new NotSupportedException("objectPtr == null");
NativeMethods.HandleException(
NativeMethods.video_BackgroundSubtractorMOG2_getDetectShadows(objectPtr.CvPtr, out var ret));
GC.KeepAlive(this);
return ret != 0;
}
set
{
ThrowIfDisposed();
if (objectPtr == null)
throw new NotSupportedException("objectPtr == null");
NativeMethods.HandleException(
NativeMethods.video_BackgroundSubtractorMOG2_setDetectShadows(objectPtr.CvPtr, value ? 1 : 0));
GC.KeepAlive(this);
}
}
/// <summary>
/// Gets or sets the shadow value.
/// Shadow value is the value used to mark shadows in the foreground mask. Default value is 127.
/// Value 0 in the mask always means background, 255 means foreground.
/// </summary>
public int ShadowValue
{
get
{
ThrowIfDisposed();
if (objectPtr == null)
throw new NotSupportedException("objectPtr == null");
NativeMethods.HandleException(
NativeMethods.video_BackgroundSubtractorMOG2_getShadowValue(objectPtr.CvPtr, out var ret));
GC.KeepAlive(this);
return ret;
}
set
{
ThrowIfDisposed();
if (objectPtr == null)
throw new NotSupportedException("objectPtr == null");
NativeMethods.HandleException(
NativeMethods.video_BackgroundSubtractorMOG2_setShadowValue(objectPtr.CvPtr, value));
GC.KeepAlive(this);
}
}
/// <summary>
/// Gets or sets the shadow threshold.
/// A shadow is detected if pixel is a darker version of the background. The shadow threshold (Tau in
/// the paper) is a threshold defining how much darker the shadow can be. Tau= 0.5 means that if a pixel
/// is more than twice darker then it is not shadow. See Prati, Mikic, Trivedi and Cucchiara,
/// *Detecting Moving Shadows...*, IEEE PAMI,2003.
/// </summary>
public double ShadowThreshold
{
get
{
ThrowIfDisposed();
if (objectPtr == null)
throw new NotSupportedException("objectPtr == null");
NativeMethods.HandleException(
NativeMethods.video_BackgroundSubtractorMOG2_getShadowThreshold(objectPtr.CvPtr, out var ret));
GC.KeepAlive(this);
return ret;
}
set
{
ThrowIfDisposed();
if (objectPtr == null)
throw new NotSupportedException("objectPtr == null");
NativeMethods.HandleException(
NativeMethods.video_BackgroundSubtractorMOG2_setShadowThreshold(objectPtr.CvPtr, value));
GC.KeepAlive(this);
}
}
#endregion
internal class Ptr : OpenCvSharp.Ptr
{
public Ptr(IntPtr ptr) : base(ptr)
{
}
public override IntPtr Get()
{
NativeMethods.HandleException(
NativeMethods.video_Ptr_BackgroundSubtractorMOG2_get(ptr, out var ret));
GC.KeepAlive(this);
return ret;
}
protected override void DisposeUnmanaged()
{
NativeMethods.HandleException(
NativeMethods.video_Ptr_BackgroundSubtractorMOG2_delete(ptr));
base.DisposeUnmanaged();
}
}
}
}
| |
/*
* Farseer Physics Engine:
* Copyright (c) 2012 Ian Qvist
*
* Original source Box2D:
* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
using System.Diagnostics;
using FarseerPhysics.Common;
using FarseerPhysics.Common.ConvexHull;
using Microsoft.Xna.Framework;
namespace FarseerPhysics.Collision.Shapes
{
/// <summary>
/// Represents a simple non-selfintersecting convex polygon.
/// Create a convex hull from the given array of points.
/// </summary>
public class PolygonShape : Shape
{
/// <summary>
/// Create a convex hull from the given array of local points.
/// The number of vertices must be in the range [3, Settings.MaxPolygonVertices].
/// Warning: the points may be re-ordered, even if they form a convex polygon
/// Warning: collinear points are handled but not removed. Collinear points may lead to poor stacking behavior.
/// </summary>
public Vertices Vertices
{
get => _vertices;
set => SetVerticesNoCopy(new Vertices(value));
}
public Vertices Normals => _normals;
public override int ChildCount => 1;
Vertices _vertices;
Vertices _normals;
/// <summary>
/// Initializes a new instance of the <see cref="PolygonShape"/> class.
/// </summary>
/// <param name="vertices">The vertices.</param>
/// <param name="density">The density.</param>
public PolygonShape(Vertices vertices, float density) : base(density)
{
ShapeType = ShapeType.Polygon;
_radius = Settings.PolygonRadius;
this.Vertices = vertices;
}
/// <summary>
/// Create a new PolygonShape with the specified density.
/// </summary>
/// <param name="density">The density.</param>
public PolygonShape(float density) : base(density)
{
Debug.Assert(density >= 0f);
ShapeType = ShapeType.Polygon;
_radius = Settings.PolygonRadius;
_vertices = new Vertices(Settings.MaxPolygonVertices);
_normals = new Vertices(Settings.MaxPolygonVertices);
}
internal PolygonShape() : base(0)
{
ShapeType = ShapeType.Polygon;
_radius = Settings.PolygonRadius;
_vertices = new Vertices(Settings.MaxPolygonVertices);
_normals = new Vertices(Settings.MaxPolygonVertices);
}
/// <summary>
/// sets the vertices without copying over the data from verts to the local List.
/// </summary>
/// <param name="verts">Verts.</param>
public void SetVerticesNoCopy(Vertices verts)
{
Debug.Assert(verts.Count >= 3 && verts.Count <= Settings.MaxPolygonVertices);
_vertices = verts;
if (Settings.UseConvexHullPolygons)
{
// FPE note: This check is required as the GiftWrap algorithm early exits on triangles
// So instead of giftwrapping a triangle, we just force it to be clock wise.
if (_vertices.Count <= 3)
_vertices.ForceCounterClockWise();
else
_vertices = GiftWrap.GetConvexHull(_vertices);
}
if (_normals == null)
_normals = new Vertices(_vertices.Count);
else
_normals.Clear();
// Compute normals. Ensure the edges have non-zero length.
for (var i = 0; i < _vertices.Count; ++i)
{
var next = i + 1 < _vertices.Count ? i + 1 : 0;
var edge = _vertices[next] - _vertices[i];
Debug.Assert(edge.LengthSquared() > Settings.Epsilon * Settings.Epsilon);
// FPE optimization: Normals.Add(MathHelper.Cross(edge, 1.0f));
var temp = new Vector2(edge.Y, -edge.X);
Nez.Vector2Ext.Normalize(ref temp);
_normals.Add(temp);
}
// Compute the polygon mass data
ComputeProperties();
}
protected override void ComputeProperties()
{
// Polygon mass, centroid, and inertia.
// Let rho be the polygon density in mass per unit area.
// Then:
// mass = rho * int(dA)
// centroid.X = (1/mass) * rho * int(x * dA)
// centroid.Y = (1/mass) * rho * int(y * dA)
// I = rho * int((x*x + y*y) * dA)
//
// We can compute these integrals by summing all the integrals
// for each triangle of the polygon. To evaluate the integral
// for a single triangle, we make a change of variables to
// the (u,v) coordinates of the triangle:
// x = x0 + e1x * u + e2x * v
// y = y0 + e1y * u + e2y * v
// where 0 <= u && 0 <= v && u + v <= 1.
//
// We integrate u from [0,1-v] and then v from [0,1].
// We also need to use the Jacobian of the transformation:
// D = cross(e1, e2)
//
// Simplification: triangle centroid = (1/3) * (p1 + p2 + p3)
//
// The rest of the derivation is handled by computer algebra.
Debug.Assert(Vertices.Count >= 3);
//FPE optimization: Early exit as polygons with 0 density does not have any properties.
if (_density <= 0)
return;
//FPE optimization: Consolidated the calculate centroid and mass code to a single method.
var center = Vector2.Zero;
var area = 0.0f;
var I = 0.0f;
// pRef is the reference point for forming triangles.
// It's location doesn't change the result (except for rounding error).
var s = Vector2.Zero;
// This code would put the reference point inside the polygon.
for (int i = 0; i < Vertices.Count; ++i)
s += Vertices[i];
s *= 1.0f / Vertices.Count;
const float k_inv3 = 1.0f / 3.0f;
for (int i = 0; i < Vertices.Count; ++i)
{
// Triangle vertices.
Vector2 e1 = Vertices[i] - s;
Vector2 e2 = i + 1 < Vertices.Count ? Vertices[i + 1] - s : Vertices[0] - s;
var D = MathUtils.Cross(e1, e2);
var triangleArea = 0.5f * D;
area += triangleArea;
// Area weighted centroid
center += triangleArea * k_inv3 * (e1 + e2);
float ex1 = e1.X, ey1 = e1.Y;
float ex2 = e2.X, ey2 = e2.Y;
var intx2 = ex1 * ex1 + ex2 * ex1 + ex2 * ex2;
var inty2 = ey1 * ey1 + ey2 * ey1 + ey2 * ey2;
I += (0.25f * k_inv3 * D) * (intx2 + inty2);
}
//The area is too small for the engine to handle.
Debug.Assert(area > Settings.Epsilon);
// We save the area
MassData.Area = area;
// Total mass
MassData.Mass = _density * area;
// Center of mass
center *= 1.0f / area;
MassData.Centroid = center + s;
// Inertia tensor relative to the local origin (point s).
MassData.Inertia = _density * I;
// Shift to center of mass then to original body origin.
MassData.Inertia += MassData.Mass *
(Vector2.Dot(MassData.Centroid, MassData.Centroid) - Vector2.Dot(center, center));
}
public override bool TestPoint(ref Transform transform, ref Vector2 point)
{
Vector2 pLocal = MathUtils.MulT(transform.Q, point - transform.P);
for (int i = 0; i < Vertices.Count; ++i)
{
float dot = Vector2.Dot(Normals[i], pLocal - Vertices[i]);
if (dot > 0.0f)
{
return false;
}
}
return true;
}
public override bool RayCast(out RayCastOutput output, ref RayCastInput input, ref Transform transform,
int childIndex)
{
output = new RayCastOutput();
// Put the ray into the polygon's frame of reference.
Vector2 p1 = MathUtils.MulT(transform.Q, input.Point1 - transform.P);
Vector2 p2 = MathUtils.MulT(transform.Q, input.Point2 - transform.P);
Vector2 d = p2 - p1;
float lower = 0.0f, upper = input.MaxFraction;
int index = -1;
for (int i = 0; i < Vertices.Count; ++i)
{
// p = p1 + a * d
// dot(normal, p - v) = 0
// dot(normal, p1 - v) + a * dot(normal, d) = 0
float numerator = Vector2.Dot(Normals[i], Vertices[i] - p1);
float denominator = Vector2.Dot(Normals[i], d);
if (denominator == 0.0f)
{
if (numerator < 0.0f)
{
return false;
}
}
else
{
// Note: we want this predicate without division:
// lower < numerator / denominator, where denominator < 0
// Since denominator < 0, we have to flip the inequality:
// lower < numerator / denominator <==> denominator * lower > numerator.
if (denominator < 0.0f && numerator < lower * denominator)
{
// Increase lower.
// The segment enters this half-space.
lower = numerator / denominator;
index = i;
}
else if (denominator > 0.0f && numerator < upper * denominator)
{
// Decrease upper.
// The segment exits this half-space.
upper = numerator / denominator;
}
}
// The use of epsilon here causes the assert on lower to trip
// in some cases. Apparently the use of epsilon was to make edge
// shapes work, but now those are handled separately.
//if (upper < lower - b2_epsilon)
if (upper < lower)
{
return false;
}
}
Debug.Assert(0.0f <= lower && lower <= input.MaxFraction);
if (index >= 0)
{
output.Fraction = lower;
output.Normal = MathUtils.Mul(transform.Q, Normals[index]);
return true;
}
return false;
}
/// <summary>
/// Given a transform, compute the associated axis aligned bounding box for a child shape.
/// </summary>
/// <param name="aabb">The aabb results.</param>
/// <param name="transform">The world transform of the shape.</param>
/// <param name="childIndex">The child shape index.</param>
public override void ComputeAABB(out AABB aabb, ref Transform transform, int childIndex)
{
var lower = MathUtils.Mul(ref transform, Vertices[0]);
var upper = lower;
for (int i = 1; i < Vertices.Count; ++i)
{
var v = MathUtils.Mul(ref transform, Vertices[i]);
lower = Vector2.Min(lower, v);
upper = Vector2.Max(upper, v);
}
var r = new Vector2(Radius, Radius);
aabb.LowerBound = lower - r;
aabb.UpperBound = upper + r;
}
public override float ComputeSubmergedArea(ref Vector2 normal, float offset, ref Transform xf, out Vector2 sc)
{
sc = Vector2.Zero;
//Transform plane into shape co-ordinates
var normalL = MathUtils.MulT(xf.Q, normal);
float offsetL = offset - Vector2.Dot(normal, xf.P);
float[] depths = new float[Settings.MaxPolygonVertices];
int diveCount = 0;
int intoIndex = -1;
int outoIndex = -1;
bool lastSubmerged = false;
int i;
for (i = 0; i < Vertices.Count; i++)
{
depths[i] = Vector2.Dot(normalL, Vertices[i]) - offsetL;
bool isSubmerged = depths[i] < -Settings.Epsilon;
if (i > 0)
{
if (isSubmerged)
{
if (!lastSubmerged)
{
intoIndex = i - 1;
diveCount++;
}
}
else
{
if (lastSubmerged)
{
outoIndex = i - 1;
diveCount++;
}
}
}
lastSubmerged = isSubmerged;
}
switch (diveCount)
{
case 0:
if (lastSubmerged)
{
//Completely submerged
sc = MathUtils.Mul(ref xf, MassData.Centroid);
return MassData.Mass / Density;
}
//Completely dry
return 0;
case 1:
if (intoIndex == -1)
{
intoIndex = Vertices.Count - 1;
}
else
{
outoIndex = Vertices.Count - 1;
}
break;
}
int intoIndex2 = (intoIndex + 1) % Vertices.Count;
int outoIndex2 = (outoIndex + 1) % Vertices.Count;
float intoLambda = (0 - depths[intoIndex]) / (depths[intoIndex2] - depths[intoIndex]);
float outoLambda = (0 - depths[outoIndex]) / (depths[outoIndex2] - depths[outoIndex]);
Vector2 intoVec =
new Vector2(Vertices[intoIndex].X * (1 - intoLambda) + Vertices[intoIndex2].X * intoLambda,
Vertices[intoIndex].Y * (1 - intoLambda) + Vertices[intoIndex2].Y * intoLambda);
Vector2 outoVec =
new Vector2(Vertices[outoIndex].X * (1 - outoLambda) + Vertices[outoIndex2].X * outoLambda,
Vertices[outoIndex].Y * (1 - outoLambda) + Vertices[outoIndex2].Y * outoLambda);
//Initialize accumulator
float area = 0;
Vector2 center = new Vector2(0, 0);
Vector2 p2 = Vertices[intoIndex2];
const float k_inv3 = 1.0f / 3.0f;
//An awkward loop from intoIndex2+1 to outIndex2
i = intoIndex2;
while (i != outoIndex2)
{
i = (i + 1) % Vertices.Count;
Vector2 p3;
if (i == outoIndex2)
p3 = outoVec;
else
p3 = Vertices[i];
//Add the triangle formed by intoVec,p2,p3
{
Vector2 e1 = p2 - intoVec;
Vector2 e2 = p3 - intoVec;
float D = MathUtils.Cross(e1, e2);
float triangleArea = 0.5f * D;
area += triangleArea;
// Area weighted centroid
center += triangleArea * k_inv3 * (intoVec + p2 + p3);
}
p2 = p3;
}
//Normalize and transform centroid
center *= 1.0f / area;
sc = MathUtils.Mul(ref xf, center);
return area;
}
public bool CompareTo(PolygonShape shape)
{
if (Vertices.Count != shape.Vertices.Count)
return false;
for (int i = 0; i < Vertices.Count; i++)
{
if (Vertices[i] != shape.Vertices[i])
return false;
}
return (Radius == shape.Radius && MassData == shape.MassData);
}
public override Shape Clone()
{
var clone = new PolygonShape();
clone.ShapeType = ShapeType;
clone._radius = _radius;
clone._density = _density;
clone._vertices = new Vertices(_vertices);
clone._normals = new Vertices(_normals);
clone.MassData = MassData;
return clone;
}
}
}
| |
using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Printing;
using System.Drawing.Imaging;
using System.Windows.Forms;
namespace CoolPrintPreview
{
/// <summary>
/// Specifies the zoom mode for the <see cref="CoolPrintPreviewControl"/> control.
/// </summary>
internal enum ZoomMode
{
/// <summary>
/// Show the preview in actual size.
/// </summary>
ActualSize,
/// <summary>
/// Show a full page.
/// </summary>
FullPage,
/// <summary>
/// Show a full page width.
/// </summary>
PageWidth,
/// <summary>
/// Show two full pages.
/// </summary>
TwoPages,
/// <summary>
/// Use the zoom factor specified by the <see cref="CoolPrintPreviewControl.Zoom"/> property.
/// </summary>
Custom
}
/// <summary>
/// Represents a preview of one or two pages in a <see cref="PrintDocument"/>.
/// </summary>
/// <remarks>
/// This control is similar to the standard <see cref="PrintPreviewControl"/> but
/// it displays pages as they are rendered. By contrast, the standard control
/// waits until the entire document is rendered before it displays anything.
/// </remarks>
internal class CoolPrintPreviewControl : UserControl
{
//-------------------------------------------------------------
#region ** fields
PrintDocument _doc;
ZoomMode _zoomMode;
double _zoom;
int _startPage;
Brush _backBrush;
Point _ptLast;
PointF _himm2pix = new PointF(-1, -1);
PageImageList _img = new PageImageList();
bool _cancel, _rendering;
const int MARGIN = 4;
#endregion
//-------------------------------------------------------------
#region ** ctor
/// <summary>
/// Initializes a new instance of a <see cref="CoolPrintPreviewControl"/> control.
/// </summary>
public CoolPrintPreviewControl()
{
BackColor = SystemColors.AppWorkspace;
ZoomMode = ZoomMode.FullPage;
StartPage = 0;
SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
}
#endregion
//-------------------------------------------------------------
#region ** object model
/// <summary>
/// Gets or sets the <see cref="PrintDocument"/> being previewed.
/// </summary>
public PrintDocument Document
{
get { return _doc; }
set
{
if (value != _doc)
{
_doc = value;
RefreshPreview();
}
}
}
/// <summary>
/// Regenerates the preview to reflect changes in the document layout.
/// </summary>
public void RefreshPreview()
{
// render into PrintController
if (_doc != null)
{
// prepare to render preview document
_img.Clear();
PrintController savePC = _doc.PrintController;
// render preview document
try
{
_cancel = false;
_rendering = true;
_doc.PrintController = new PreviewPrintController();
_doc.PrintPage += _doc_PrintPage;
_doc.EndPrint += _doc_EndPrint;
_doc.Print();
}
finally
{
_cancel = false;
_rendering = false;
_doc.PrintPage -= _doc_PrintPage;
_doc.EndPrint -= _doc_EndPrint;
_doc.PrintController = savePC;
}
}
// update
OnPageCountChanged(EventArgs.Empty);
UpdatePreview();
UpdateScrollBars();
}
/// <summary>
/// Stops rendering the <see cref="Document"/>.
/// </summary>
public void Cancel()
{
_cancel = true;
}
/// <summary>
/// Gets a value that indicates whether the <see cref="Document"/> is being rendered.
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsRendering
{
get { return _rendering; }
}
/// <summary>
/// Gets or sets how the zoom should be adjusted when the control is resized.
/// </summary>
[DefaultValue(ZoomMode.FullPage)]
public ZoomMode ZoomMode
{
get { return _zoomMode; }
set
{
if (value != _zoomMode)
{
_zoomMode = value;
UpdateScrollBars();
OnZoomModeChanged(EventArgs.Empty);
}
}
}
/// <summary>
/// Gets or sets a custom zoom factor used when the <see cref="ZoomMode"/> property
/// is set to <b>Custom</b>.
/// </summary>
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public double Zoom
{
get { return _zoom; }
set
{
if (value != _zoom || ZoomMode != ZoomMode.Custom)
{
ZoomMode = ZoomMode.Custom;
_zoom = value;
UpdateScrollBars();
OnZoomModeChanged(EventArgs.Empty);
}
}
}
/// <summary>
/// Gets or sets the first page being previewed.
/// </summary>
/// <remarks>
/// There may be one or two pages visible depending on the setting of the
/// <see cref="ZoomMode"/> property.
/// </remarks>
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public int StartPage
{
get { return _startPage; }
set
{
// validate new setting
if (value > PageCount - 1) value = PageCount - 1;
if (value < 0) value = 0;
// apply new setting
if (value != _startPage)
{
_startPage = value;
UpdateScrollBars();
OnStartPageChanged(EventArgs.Empty);
}
}
}
/// <summary>
/// Gets the number of pages available for preview.
/// </summary>
/// <remarks>
/// This number increases as the document is rendered into the control.
/// </remarks>
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public int PageCount
{
get { return _img.Count; }
}
/// <summary>
/// Gets or sets the control's background color.
/// </summary>
[DefaultValue(typeof(Color), "AppWorkspace")]
public override Color BackColor
{
get { return base.BackColor; }
set
{
base.BackColor = value;
_backBrush = new SolidBrush(value);
}
}
/// <summary>
/// Gets a list containing the images of the pages in the document.
/// </summary>
[Browsable(false)]
public PageImageList PageImages
{
get { return _img; }
}
/// <summary>
/// Prints the current document honoring the selected page range.
/// </summary>
public void Print()
{
// select pages to print
var ps = _doc.PrinterSettings;
int first = ps.MinimumPage - 1;
int last = ps.MaximumPage - 1;
switch (ps.PrintRange)
{
case PrintRange.AllPages:
Document.Print();
return;
case PrintRange.CurrentPage:
first = last = StartPage;
break;
case PrintRange.Selection:
first = last = StartPage;
if (ZoomMode == ZoomMode.TwoPages)
{
last = Math.Min(first + 1, PageCount - 1);
}
break;
case PrintRange.SomePages:
first = ps.FromPage - 1;
last = ps.ToPage - 1;
break;
}
// print using helper class
var dp = new DocumentPrinter(this, first, last);
dp.Print();
}
#endregion
//-------------------------------------------------------------
#region ** events
/// <summary>
/// Occurs when the value of the <see cref="StartPage"/> property changes.
/// </summary>
public event EventHandler StartPageChanged;
/// <summary>
/// Raises the <see cref="StartPageChanged"/> event.
/// </summary>
/// <param name="e"><see cref="EventArgs"/> that provides the event data.</param>
protected void OnStartPageChanged(EventArgs e)
{
if (StartPageChanged != null)
{
StartPageChanged(this, e);
}
}
/// <summary>
/// Occurs when the value of the <see cref="PageCount"/> property changes.
/// </summary>
public event EventHandler PageCountChanged;
/// <summary>
/// Raises the <see cref="PageCountChanged"/> event.
/// </summary>
/// <param name="e"><see cref="EventArgs"/> that provides the event data/</param>
protected void OnPageCountChanged(EventArgs e)
{
if (PageCountChanged != null)
{
PageCountChanged(this, e);
}
}
/// <summary>
/// Occurs when the value of the <see cref="ZoomMode"/> property changes.
/// </summary>
public event EventHandler ZoomModeChanged;
/// <summary>
/// Raises the <see cref="ZoomModeChanged"/> event.
/// </summary>
/// <param name="e"><see cref="EventArgs"/> that contains the event data.</param>
protected void OnZoomModeChanged(EventArgs e)
{
if (ZoomModeChanged != null)
{
ZoomModeChanged(this, e);
}
}
#endregion
//-------------------------------------------------------------
#region ** overrides
// painting
protected override void OnPaintBackground(PaintEventArgs e)
{
// we're painting it all, so don't call base class
//base.OnPaintBackground(e);
}
protected override void OnPaint(PaintEventArgs e)
{
Image img = GetImage(StartPage);
if (img != null)
{
Rectangle rc = GetImageRectangle(img);
if (rc.Width > 2 && rc.Height > 2)
{
// adjust for scrollbars
rc.Offset(AutoScrollPosition);
// render single page
if (_zoomMode != ZoomMode.TwoPages)
{
RenderPage(e.Graphics, img, rc);
}
else // render two pages
{
// render first page
rc.Width = (rc.Width - MARGIN) / 2;
RenderPage(e.Graphics, img, rc);
// render second page
img = GetImage(StartPage + 1);
if (img != null)
{
// update bounds in case orientation changed
rc = GetImageRectangle(img);
rc.Width = (rc.Width - MARGIN) / 2;
// render second page
rc.Offset(rc.Width + MARGIN, 0);
RenderPage(e.Graphics, img, rc);
}
}
}
}
// paint background
e.Graphics.FillRectangle(_backBrush, ClientRectangle);
}
protected override void OnSizeChanged(EventArgs e)
{
UpdateScrollBars();
base.OnSizeChanged(e);
}
// pan by dragging preview pane
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
if (e.Button == MouseButtons.Left && AutoScrollMinSize != Size.Empty)
{
Cursor = Cursors.NoMove2D;
_ptLast = new Point(e.X, e.Y);
}
}
protected override void OnMouseUp(MouseEventArgs e)
{
base.OnMouseUp(e);
if (e.Button == MouseButtons.Left && Cursor == Cursors.NoMove2D)
Cursor = Cursors.Default;
}
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
if (Cursor == Cursors.NoMove2D)
{
int dx = e.X - _ptLast.X;
int dy = e.Y - _ptLast.Y;
if (dx != 0 || dy != 0)
{
Point pt = AutoScrollPosition;
AutoScrollPosition = new Point(-(pt.X + dx), -(pt.Y + dy));
_ptLast = new Point(e.X, e.Y);
}
}
}
// zoom in/out using control+wheel
protected override void OnMouseWheel(MouseEventArgs e)
{
if ((Control.ModifierKeys & Keys.Control) != 0)
{
// calculate event position in document percentage units
var asp = this.AutoScrollPosition;
var sms = this.AutoScrollMinSize;
var ptMouse = e.Location;
var ptDoc = new PointF(
sms.Width > 0 ? (ptMouse.X - asp.X) / (float)sms.Width : 0,
sms.Height > 0 ? (ptMouse.Y - asp.Y) / (float)sms.Height : 0
);
// update the zoom
var zoom = Zoom * (e.Delta > 0 ? 1.1 : 0.9);
Zoom = Math.Min(5, Math.Max(.1, zoom));
// restore position in document percentage units
sms = this.AutoScrollMinSize;
this.AutoScrollPosition = new Point(
(int)(ptDoc.X * sms.Width - ptMouse.X),
(int)(ptDoc.Y * sms.Height - ptMouse.Y));
}
else
{
// allow base class to scroll only if not zooming
base.OnMouseWheel(e);
}
}
// keyboard support
protected override bool IsInputKey(Keys keyData)
{
switch (keyData)
{
case Keys.Left:
case Keys.Up:
case Keys.Right:
case Keys.Down:
case Keys.PageUp:
case Keys.PageDown:
case Keys.Home:
case Keys.End:
return true;
}
return base.IsInputKey(keyData);
}
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (e.Handled)
return;
switch (e.KeyCode)
{
// arrow keys scroll or browse, depending on ZoomMode
case Keys.Left:
case Keys.Up:
case Keys.Right:
case Keys.Down:
// browse
if (ZoomMode == ZoomMode.FullPage || ZoomMode == ZoomMode.TwoPages)
{
switch (e.KeyCode)
{
case Keys.Left:
case Keys.Up:
StartPage--;
break;
case Keys.Right:
case Keys.Down:
StartPage++;
break;
}
break;
}
// scroll
Point pt = AutoScrollPosition;
switch (e.KeyCode)
{
case Keys.Left: pt.X += 20; break;
case Keys.Right: pt.X -= 20; break;
case Keys.Up: pt.Y += 20; break;
case Keys.Down: pt.Y -= 20; break;
}
AutoScrollPosition = new Point(-pt.X, -pt.Y);
break;
// page up/down browse pages
case Keys.PageUp:
StartPage--;
break;
case Keys.PageDown:
StartPage++;
break;
// home/end
case Keys.Home:
AutoScrollPosition = Point.Empty;
StartPage = 0;
break;
case Keys.End:
AutoScrollPosition = Point.Empty;
StartPage = PageCount - 1;
break;
default:
return;
}
// if we got here, the event was handled
e.Handled = true;
}
#endregion
//-------------------------------------------------------------
#region ** implementation
void _doc_PrintPage(object sender, PrintPageEventArgs e)
{
SyncPageImages(false);
if (_cancel)
{
e.Cancel = true;
}
}
void _doc_EndPrint(object sender, PrintEventArgs e)
{
SyncPageImages(true);
}
void SyncPageImages(bool lastPageReady)
{
var pv = (PreviewPrintController)_doc.PrintController;
if (pv != null)
{
var pageInfo = pv.GetPreviewPageInfo();
int count = lastPageReady ? pageInfo.Length : pageInfo.Length - 1;
for (int i = _img.Count; i < count; i++)
{
var img = pageInfo[i].Image;
_img.Add(img);
OnPageCountChanged(EventArgs.Empty);
if (StartPage < 0) StartPage = 0;
if (i == StartPage || i == StartPage + 1)
{
Refresh();
}
Application.DoEvents();
}
}
}
Image GetImage(int page)
{
return page > -1 && page < PageCount ? _img[page] : null;
}
Rectangle GetImageRectangle(Image img)
{
// start with regular image rectangle
Size sz = GetImageSizeInPixels(img);
Rectangle rc = new Rectangle(0, 0, sz.Width, sz.Height);
// calculate zoom
Rectangle rcCli = this.ClientRectangle;
switch (_zoomMode)
{
case ZoomMode.ActualSize:
_zoom = 1;
break;
case ZoomMode.TwoPages:
rc.Width *= 2; // << two pages side-by-side
goto case ZoomMode.FullPage;
case ZoomMode.FullPage:
double zoomX = (rc.Width > 0) ? rcCli.Width / (double)rc.Width : 0;
double zoomY = (rc.Height > 0) ? rcCli.Height / (double)rc.Height : 0;
_zoom = Math.Min(zoomX, zoomY);
break;
case ZoomMode.PageWidth:
_zoom = (rc.Width > 0) ? rcCli.Width / (double)rc.Width : 0;
break;
}
// apply zoom factor
rc.Width = (int)(rc.Width * _zoom);
rc.Height = (int)(rc.Height * _zoom);
// center image
int dx = (rcCli.Width - rc.Width) / 2;
if (dx > 0) rc.X += dx;
int dy = (rcCli.Height - rc.Height) / 2;
if (dy > 0) rc.Y += dy;
// add some extra space
rc.Inflate(-MARGIN, -MARGIN);
if (_zoomMode == ZoomMode.TwoPages)
{
rc.Inflate(-MARGIN / 2, 0);
}
// done
return rc;
}
Size GetImageSizeInPixels(Image img)
{
// get image size
SizeF szf = img.PhysicalDimension;
// if it is a metafile, convert to pixels
if (img is Metafile)
{
// get screen resolution
if (_himm2pix.X < 0)
{
using (Graphics g = this.CreateGraphics())
{
_himm2pix.X = g.DpiX / 2540f;
_himm2pix.Y = g.DpiY / 2540f;
}
}
// convert himetric to pixels
szf.Width *= _himm2pix.X;
szf.Height *= _himm2pix.Y;
}
// done
return Size.Truncate(szf);
}
void RenderPage(Graphics g, Image img, Rectangle rc)
{
// draw the page
rc.Offset(1, 1);
g.DrawRectangle(Pens.Black, rc);
rc.Offset(-1, -1);
g.FillRectangle(Brushes.White, rc);
g.DrawImage(img, rc);
g.DrawRectangle(Pens.Black, rc);
// exclude cliprect to paint background later
rc.Width++;
rc.Height++;
g.ExcludeClip(rc);
rc.Offset(1, 1);
g.ExcludeClip(rc);
}
void UpdateScrollBars()
{
// get image rectangle to adjust scroll size
Rectangle rc = Rectangle.Empty;
Image img = this.GetImage(StartPage);
if (img != null)
{
rc = GetImageRectangle(img);
}
// calculate new scroll size
Size scrollSize = new Size(0, 0);
switch (_zoomMode)
{
case ZoomMode.PageWidth:
scrollSize = new Size(0, rc.Height + 2 * MARGIN);
break;
case ZoomMode.ActualSize:
case ZoomMode.Custom:
scrollSize = new Size(rc.Width + 2 * MARGIN, rc.Height + 2 * MARGIN);
break;
}
// apply if needed
if (scrollSize != AutoScrollMinSize)
{
AutoScrollMinSize = scrollSize;
}
// ready to update
UpdatePreview();
}
void UpdatePreview()
{
// validate current page
if (_startPage < 0) _startPage = 0;
if (_startPage > PageCount - 1) _startPage = PageCount - 1;
// repaint
Invalidate();
}
#endregion
//-------------------------------------------------------------
#region ** nested class
// helper class that prints the selected page range in a PrintDocument.
internal class DocumentPrinter : PrintDocument
{
int _first, _last, _index;
PageImageList _imgList;
public DocumentPrinter(CoolPrintPreviewControl preview, int first, int last)
{
// save page range and image list
_first = first;
_last = last;
_imgList = preview.PageImages;
// copy page and printer settings from original document
DefaultPageSettings = preview.Document.DefaultPageSettings;
PrinterSettings = preview.Document.PrinterSettings;
}
protected override void OnBeginPrint(PrintEventArgs e)
{
// start from the first page
_index = _first;
}
protected override void OnPrintPage(PrintPageEventArgs e)
{
// render the current page and increment the index
e.Graphics.PageUnit = GraphicsUnit.Display;
e.Graphics.DrawImage(_imgList[_index++], e.PageBounds);
// stop when we reach the last page in the range
e.HasMorePages = _index <= _last;
}
}
#endregion
}
}
| |
#if !DISABLE_PLAYFABENTITY_API
using System;
using System.Collections.Generic;
using PlayFab.SharedModels;
namespace PlayFab.ProfilesModels
{
public enum EffectType
{
Allow,
Deny
}
/// <summary>
/// An entity object and its associated meta data.
/// </summary>
[Serializable]
public class EntityDataObject
{
/// <summary>
/// Un-escaped JSON object, if DataAsObject is true.
/// </summary>
public object DataObject;
/// <summary>
/// Escaped string JSON body of the object, if DataAsObject is default or false.
/// </summary>
public string EscapedDataObject;
/// <summary>
/// Name of this object.
/// </summary>
public string ObjectName;
}
/// <summary>
/// Combined entity type and ID structure which uniquely identifies a single entity.
/// </summary>
[Serializable]
public class EntityKey
{
/// <summary>
/// Unique ID of the entity.
/// </summary>
public string Id;
/// <summary>
/// Entity type. See https://api.playfab.com/docs/tutorials/entities/entitytypes
/// </summary>
public string Type;
}
[Serializable]
public class EntityLineage
{
/// <summary>
/// The Character Id of the associated entity.
/// </summary>
public string CharacterId;
/// <summary>
/// The Group Id of the associated entity.
/// </summary>
public string GroupId;
/// <summary>
/// The Master Player Account Id of the associated entity.
/// </summary>
public string MasterPlayerAccountId;
/// <summary>
/// The Namespace Id of the associated entity.
/// </summary>
public string NamespaceId;
/// <summary>
/// The Title Id of the associated entity.
/// </summary>
public string TitleId;
/// <summary>
/// The Title Player Account Id of the associated entity.
/// </summary>
public string TitlePlayerAccountId;
}
[Serializable]
public class EntityPermissionStatement
{
/// <summary>
/// The action this statement effects. May be 'Read', 'Write' or '*' for both read and write.
/// </summary>
public string Action;
/// <summary>
/// A comment about the statement. Intended solely for bookkeeping and debugging.
/// </summary>
public string Comment;
/// <summary>
/// Additional conditions to be applied for entity resources.
/// </summary>
public object Condition;
/// <summary>
/// The effect this statement will have. It may be either Allow or Deny
/// </summary>
public EffectType Effect;
/// <summary>
/// The principal this statement will effect.
/// </summary>
public object Principal;
/// <summary>
/// The resource this statements effects. Similar to 'pfrn:data--title![Title ID]/Profile/*'
/// </summary>
public string Resource;
}
[Serializable]
public class EntityProfileBody
{
/// <summary>
/// The entity id and type.
/// </summary>
public EntityKey Entity;
/// <summary>
/// The chain of responsibility for this entity. Use Lineage.
/// </summary>
public string EntityChain;
/// <summary>
/// The files on this profile.
/// </summary>
public Dictionary<string,EntityProfileFileMetadata> Files;
/// <summary>
/// The friendly name of the entity. This field may serve different purposes for different entity types. i.e.: for a title
/// player account it could represent the display name of the player, whereas on a character it could be character's name.
/// </summary>
public string FriendlyName;
/// <summary>
/// The language on this profile.
/// </summary>
public string Language;
/// <summary>
/// The lineage of this profile.
/// </summary>
public EntityLineage Lineage;
/// <summary>
/// The objects on this profile.
/// </summary>
public Dictionary<string,EntityDataObject> Objects;
/// <summary>
/// The permissions that govern access to this entity profile and its properties. Only includes permissions set on this
/// profile, not global statements from titles and namespaces.
/// </summary>
public List<EntityPermissionStatement> Permissions;
/// <summary>
/// The version number of the profile in persistent storage at the time of the read. Used for optional optimistic
/// concurrency during update.
/// </summary>
public int VersionNumber;
}
/// <summary>
/// An entity file's meta data. To get a download URL call File/GetFiles API.
/// </summary>
[Serializable]
public class EntityProfileFileMetadata
{
/// <summary>
/// Checksum value for the file
/// </summary>
public string Checksum;
/// <summary>
/// Name of the file
/// </summary>
public string FileName;
/// <summary>
/// Last UTC time the file was modified
/// </summary>
public DateTime LastModified;
/// <summary>
/// Storage service's reported byte count
/// </summary>
public int Size;
}
[Serializable]
public class GetEntityProfileRequest : PlayFabRequestCommon
{
/// <summary>
/// Determines whether the objects will be returned as an escaped JSON string or as a un-escaped JSON object. Default is
/// JSON string.
/// </summary>
public bool? DataAsObject;
/// <summary>
/// The entity to perform this action on.
/// </summary>
public EntityKey Entity;
}
[Serializable]
public class GetEntityProfileResponse : PlayFabResultCommon
{
/// <summary>
/// Entity profile
/// </summary>
public EntityProfileBody Profile;
}
[Serializable]
public class GetEntityProfilesRequest : PlayFabRequestCommon
{
/// <summary>
/// Determines whether the objects will be returned as an escaped JSON string or as a un-escaped JSON object. Default is
/// JSON string.
/// </summary>
public bool? DataAsObject;
/// <summary>
/// Entity keys of the profiles to load. Must be between 1 and 25
/// </summary>
public List<EntityKey> Entities;
}
[Serializable]
public class GetEntityProfilesResponse : PlayFabResultCommon
{
/// <summary>
/// Entity profiles
/// </summary>
public List<EntityProfileBody> Profiles;
}
[Serializable]
public class GetGlobalPolicyRequest : PlayFabRequestCommon
{
}
[Serializable]
public class GetGlobalPolicyResponse : PlayFabResultCommon
{
/// <summary>
/// The permissions that govern access to all entities under this title or namespace.
/// </summary>
public List<EntityPermissionStatement> Permissions;
}
public enum OperationTypes
{
Created,
Updated,
Deleted,
None
}
[Serializable]
public class SetEntityProfilePolicyRequest : PlayFabRequestCommon
{
/// <summary>
/// The entity to perform this action on.
/// </summary>
public EntityKey Entity;
/// <summary>
/// The statements to include in the access policy.
/// </summary>
public List<EntityPermissionStatement> Statements;
}
[Serializable]
public class SetEntityProfilePolicyResponse : PlayFabResultCommon
{
/// <summary>
/// The permissions that govern access to this entity profile and its properties. Only includes permissions set on this
/// profile, not global statements from titles and namespaces.
/// </summary>
public List<EntityPermissionStatement> Permissions;
}
[Serializable]
public class SetGlobalPolicyRequest : PlayFabRequestCommon
{
/// <summary>
/// The permissions that govern access to all entities under this title or namespace.
/// </summary>
public List<EntityPermissionStatement> Permissions;
}
[Serializable]
public class SetGlobalPolicyResponse : PlayFabResultCommon
{
}
[Serializable]
public class SetProfileLanguageRequest : PlayFabRequestCommon
{
/// <summary>
/// The entity to perform this action on.
/// </summary>
public EntityKey Entity;
/// <summary>
/// The expected version of a profile to perform this update on
/// </summary>
public int ExpectedVersion;
/// <summary>
/// The language to set on the given entity. Deletes the profile's language if passed in a null string.
/// </summary>
public string Language;
}
[Serializable]
public class SetProfileLanguageResponse : PlayFabResultCommon
{
/// <summary>
/// The type of operation that occured on the profile's language
/// </summary>
public OperationTypes? OperationResult;
/// <summary>
/// The updated version of the profile after the language update
/// </summary>
public int? VersionNumber;
}
}
#endif
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using RocketFireWeb.Areas.HelpPage.ModelDescriptions;
using RocketFireWeb.Areas.HelpPage.Models;
namespace RocketFireWeb.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
//BSD, 2014-present, WinterDev
//----------------------------------------------------------------------------
// Anti-Grain Geometry - Version 2.4
// Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com)
//
// C# Port port by: Lars Brubaker
// [email protected]
// Copyright (C) 2007
//
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
//
//----------------------------------------------------------------------------
// Contact: [email protected]
// [email protected]
// http://www.antigrain.com
//----------------------------------------------------------------------------
//
// class ClippingPixelFormtProxy
//
//----------------------------------------------------------------------------
using PixelFarm.Drawing;
using PixelFarm.CpuBlit.VertexProcessing;
namespace PixelFarm.CpuBlit.PixelProcessing
{
public sealed class ClipProxyImage : ProxyImage
{
Q1Rect _clippingRect;
public ClipProxyImage(PixelProcessing.IBitmapBlender refImage)
: base(refImage)
{
_clippingRect = new Q1Rect(0, 0, (int)refImage.Width - 1, (int)refImage.Height - 1);
}
public bool SetClippingBox(int x1, int y1, int x2, int y2)
{
Q1Rect cb = new Q1Rect(x1, y1, x2, y2, true);
if (Q1Rect.Clip(cb, new Q1Rect(0, 0, (int)Width - 1, (int)Height - 1), out cb))
{
_clippingRect = cb;
return true;
}
_clippingRect = new Q1Rect(1, 1, 0, 0);
return false;
}
public bool InClipArea(int x, int y) => _clippingRect.Contains(x, y);
public void Clear(Color color)
{
Color c = color;
int w = this.Width;
if (w != 0)
{
for (int y = this.Height - 1; y >= 0; --y)
{
base.CopyHL(0, y, w, c);
}
}
}
public Q1Rect ClipBox => _clippingRect;
int XMin => _clippingRect.Left;
int YMin => _clippingRect.Bottom;
int XMax => _clippingRect.Right;
int YMax => _clippingRect.Top;
public override Color GetPixel(int x, int y)
{
return InClipArea(x, y) ? base.GetPixel(x, y) : new Color();
}
public override void CopyHL(int x1, int y, int x2, Color c)
{
if (x1 > x2) { int t = (int)x2; x2 = (int)x1; x1 = t; }
if (y > YMax) return;
if (y < YMin) return;
if (x1 > XMax) return;
if (x2 < XMin) return;
if (x1 < XMin) x1 = XMin;
if (x2 > XMax) x2 = (int)XMax;
base.CopyHL(x1, y, (int)(x2 - x1 + 1), c);
}
public override void CopyVL(int x, int y1, int y2, Color c)
{
if (y1 > y2) { int t = (int)y2; y2 = (int)y1; y1 = t; }
if (x > XMax) return;
if (x < XMin) return;
if (y1 > YMax) return;
if (y2 < YMin) return;
if (y1 < YMin) y1 = YMin;
if (y2 > YMax) y2 = YMax;
base.CopyVL(x, y1, (y2 - y1 + 1), c);
}
public override void BlendHL(int x1, int y, int x2, Color c, byte cover)
{
if (x1 > x2)
{
int t = (int)x2;
x2 = x1;
x1 = t;
}
if (y > YMax)
return;
if (y < YMin)
return;
if (x1 > XMax)
return;
if (x2 < XMin)
return;
if (x1 < XMin)
x1 = XMin;
if (x2 > XMax)
x2 = XMax;
base.BlendHL(x1, y, x2, c, cover);
}
public override void BlendVL(int x, int y1, int y2, Color c, byte cover)
{
if (y1 > y2) { int t = y2; y2 = y1; y1 = t; }
if (x > XMax) return;
if (x < XMin) return;
if (y1 > YMax) return;
if (y2 < YMin) return;
if (y1 < YMin) y1 = YMin;
if (y2 > YMax) y2 = YMax;
base.BlendVL(x, y1, y2, c, cover);
}
public override void BlendSolidHSpan(int x, int y, int len, Color c, byte[] covers, int coversIndex)
{
#if false
FileStream file = new FileStream("pixels.txt", FileMode.Append, FileAccess.Write);
StreamWriter sw = new StreamWriter(file);
sw.Write("h-x=" + x.ToString() + ",y=" + y.ToString() + ",len=" + len.ToString() + "\n");
sw.Close();
file.Close();
#endif
if (y > YMax) return;
if (y < YMin) return;
if (x < XMin)
{
len -= XMin - x;
if (len <= 0) return;
coversIndex += XMin - x;
x = XMin;
}
if (x + len > XMax)
{
len = XMax - x + 1;
if (len <= 0) return;
}
base.BlendSolidHSpan(x, y, len, c, covers, coversIndex);
}
public override void BlendSolidVSpan(int x, int y, int len, Color c, byte[] covers, int coversIndex)
{
#if false
FileStream file = new FileStream("pixels.txt", FileMode.Append, FileAccess.Write);
StreamWriter sw = new StreamWriter(file);
sw.Write("v-x=" + x.ToString() + ",y=" + y.ToString() + ",len=" + len.ToString() + "\n");
sw.Close();
file.Close();
#endif
if (x > XMax) return;
if (x < XMin) return;
if (y < YMin)
{
len -= (YMin - y);
if (len <= 0) return;
coversIndex += YMin - y;
y = YMin;
}
if (y + len > YMax)
{
len = (YMax - y + 1);
if (len <= 0) return;
}
base.BlendSolidVSpan(x, y, len, c, covers, coversIndex);
}
public override void CopyColorHSpan(int x, int y, int len, Color[] colors, int colorsIndex)
{
if (y > YMax) return;
if (y < YMin) return;
if (x < XMin)
{
int d = XMin - x;
len -= d;
if (len <= 0) return;
colorsIndex += d;
x = XMin;
}
if (x + len > XMax)
{
len = (XMax - x + 1);
if (len <= 0) return;
}
base.CopyColorHSpan(x, y, len, colors, colorsIndex);
}
public override void CopyColorVSpan(int x, int y, int len, Color[] colors, int colorsIndex)
{
if (x > XMax) return;
if (x < XMin) return;
if (y < YMin)
{
int d = YMin - y;
len -= d;
if (len <= 0) return;
colorsIndex += d;
y = YMin;
}
if (y + len > YMax)
{
len = (YMax - y + 1);
if (len <= 0) return;
}
base.CopyColorVSpan(x, y, len, colors, colorsIndex);
}
public override void BlendColorHSpan(int x, int y, int in_len, Color[] colors, int colorsIndex, byte[] covers, int coversIndex, bool firstCoverForAll)
{
int len = (int)in_len;
if (y > YMax)
return;
if (y < YMin)
return;
if (x < XMin)
{
int d = XMin - x;
len -= d;
if (len <= 0) return;
if (covers != null) coversIndex += d;
colorsIndex += d;
x = XMin;
}
if (x + len - 1 > XMax)
{
len = XMax - x + 1;
if (len <= 0) return;
}
base.BlendColorHSpan(x, y, len, colors, colorsIndex, covers, coversIndex, firstCoverForAll);
}
public override void SetPixel(int x, int y, Color color)
{
if ((uint)x < Width && (uint)y < Height)
{
base.SetPixel(x, y, color);
}
}
public override void CopyFrom(IBitmapSrc sourceImage,
Q1Rect sourceImageRect,
int destXOffset,
int destYOffset)
{
Q1Rect destRect = sourceImageRect.CreateNewFromOffset(destXOffset, destYOffset);
if (Q1Rect.IntersectRectangles(destRect, _clippingRect, out Q1Rect clippedSourceRect))
{
// move it back relative to the source
base.CopyFrom(sourceImage, clippedSourceRect.CreateNewFromOffset(-destXOffset, -destYOffset), destXOffset, destYOffset);
}
}
public override void BlendColorVSpan(int x, int y, int len, Color[] colors, int colorsIndex, byte[] covers, int coversIndex, bool firstCoverForAll)
{
if (x > XMax) return;
if (x < XMin) return;
if (y < YMin)
{
int d = YMin - y;
len -= d;
if (len <= 0) return;
if (covers != null) coversIndex += d;
colorsIndex += d;
y = YMin;
}
if (y + len > YMax)
{
len = (YMax - y + 1);
if (len <= 0) return;
}
base.BlendColorVSpan(x, y, len, colors, colorsIndex, covers, coversIndex, firstCoverForAll);
}
//public void reset_clipping(bool visibility)
//{
// if (visibility)
// {
// m_ClippingRect.Left = 0;
// m_ClippingRect.Bottom = 0;
// m_ClippingRect.Right = (int)Width - 1;
// m_ClippingRect.Top = (int)Height - 1;
// }
// else
// {
// m_ClippingRect.Left = 1;
// m_ClippingRect.Bottom = 1;
// m_ClippingRect.Right = 0;
// m_ClippingRect.Top = 0;
// }
//}
}
}
| |
// -----------------------------------------------------------------------------------------
// <copyright file="StorageUriTests.cs" company="Microsoft">
// Copyright 2013 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.
// </copyright>
// -----------------------------------------------------------------------------------------
using System.Runtime.Remoting;
using System.Runtime.Remoting.Messaging;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.WindowsAzure.Storage.Core
{
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure.Storage.Queue;
using Microsoft.WindowsAzure.Storage.Table;
using Microsoft.WindowsAzure.Storage.File;
using System;
using System.Collections.Generic;
using System.Net;
#if WINDOWS_DESKTOP
using Microsoft.VisualStudio.TestTools.UnitTesting;
#else
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
#endif
[TestClass]
public class TokenAuthenticationTest : TestBase
{
/// <summary>
/// This is the test state used by the periodic token updater.
/// It can be anything in practice, in our test case it is simply a string holder.
/// </summary>
private class TestState
{
public string Buffer { get; set; }
public TestState(string buffer)
{
this.Buffer = buffer;
}
}
/// <summary>
/// This is the fast token updater.
/// It simply appends '0' to the current token.
/// </summary>
private static Task<NewTokenAndFrequency> FastTokenUpdater(Object state, CancellationToken cancellationToken)
{
return
Task<NewTokenAndFrequency>.Factory.StartNew(
() =>
{
TestState testState = (TestState)state;
testState.Buffer += "0";
return new NewTokenAndFrequency(testState.Buffer, TimeSpan.FromSeconds(5));
}, cancellationToken);
}
/// <summary>
/// This is the super slow token updater. It simulates situations where a token needs to be retrieved from a potato server.
/// It waits for 10 seconds and then simply appends '0' to the current token.
/// </summary>
private static Task<NewTokenAndFrequency> SlowTokenUpdater(Object state, CancellationToken cancellationToken)
{
return
Task<NewTokenAndFrequency>.Factory.StartNew(
() =>
{
TestState testState = (TestState)state;
testState.Buffer += "0";
Task.Delay(TimeSpan.FromSeconds(10), cancellationToken).Wait(cancellationToken);
return new NewTokenAndFrequency(testState.Buffer, TimeSpan.FromSeconds(5));
}, cancellationToken);
}
/// <summary>
/// This updater throws exceptions. It simulates situations where errors occur while retrieving a token from a potato server.
/// </summary>
private static Task<NewTokenAndFrequency> BrokenTokenUpdater(Object state, CancellationToken cancellationToken)
{
return
Task<NewTokenAndFrequency>.Factory.StartNew(
() =>
{
throw new ServerException();
}, cancellationToken);
}
[TestMethod]
[Description("Basic timer triggering test.")]
[TestCategory(ComponentCategory.Core)]
[TestCategory(TestTypeCategory.UnitTest)]
[TestCategory(SmokeTestCategory.Smoke)]
[TestCategory(TenantTypeCategory.Cloud)]
public void TimerShouldTriggerPeriodically()
{
// token updater is triggered every 5 seconds
TestState state = new TestState("0");
TokenCredential tokenCredential = new TokenCredential("0", FastTokenUpdater, state, TimeSpan.FromSeconds(5));
// make sure the token starts with the right value, t=0
Assert.AreEqual("0", tokenCredential.Token);
// wait until timer triggers for the first time and validate token value, t=6
Task.Delay(TimeSpan.FromSeconds(6)).Wait();
Assert.AreEqual("00", tokenCredential.Token);
// wait until timer triggers for the second time and validate token value, t=12
Task.Delay(TimeSpan.FromSeconds(6)).Wait();
Assert.AreEqual("000", tokenCredential.Token);
// stop the time and make sure it does not trigger anymore, t=18
tokenCredential.Dispose();
Task.Delay(TimeSpan.FromSeconds(6)).Wait();
Assert.AreEqual("000", tokenCredential.Token);
}
[TestMethod]
[Description("Make sure the token updater only gets triggered after the previous update finishes.")]
[TestCategory(ComponentCategory.Core)]
[TestCategory(TestTypeCategory.UnitTest)]
[TestCategory(SmokeTestCategory.Smoke)]
[TestCategory(TenantTypeCategory.Cloud)]
public void UpdaterShouldRunOneAtATime()
{
// token updater is triggered every 5 seconds
// however, the slow updater takes 10 seconds to provide a new token
TestState state = new TestState("0");
TokenCredential tokenCredential = new TokenCredential("0", SlowTokenUpdater, state, TimeSpan.FromSeconds(5));
// make sure the token starts with the right value, t=0
Assert.AreEqual("0", tokenCredential.Token);
// check on the token while updater is running, t=6
Task.Delay(TimeSpan.FromSeconds(6)).Wait();
Assert.AreEqual("0", tokenCredential.Token);
// check on the token after updater is done for the first time, t=16
// the first updater should have finished at t=15
Task.Delay(TimeSpan.FromSeconds(10)).Wait();
Assert.AreEqual("00", tokenCredential.Token);
// check on the token while updater is running, t=22
// the second updater should have been triggered at t=20
Task.Delay(TimeSpan.FromSeconds(6)).Wait();
Assert.AreEqual("00", tokenCredential.Token);
// check on the token after updater is done for the second time, t=32
// the second updater should have finished at t=30
Task.Delay(TimeSpan.FromSeconds(10)).Wait();
Assert.AreEqual("000", tokenCredential.Token);
// stop the timer and make sure it is not triggered anymore, t=50
tokenCredential.Dispose();
Task.Delay(TimeSpan.FromSeconds(18)).Wait();
Assert.AreEqual("000", tokenCredential.Token);
}
/// <summary>
/// TODO: this does not seem to be the desired bahvior, validate with JR.
/// </summary>
[TestMethod]
[Description("Test the situation where the periodic token updater throws an exception.")]
[TestCategory(ComponentCategory.Core)]
[TestCategory(TestTypeCategory.UnitTest)]
[TestCategory(SmokeTestCategory.Smoke)]
[TestCategory(TenantTypeCategory.Cloud)]
public void ErrorThrownWhenTimerIsTriggered()
{
// token updater is triggered every 5 seconds
TestState state = new TestState("0");
TokenCredential tokenCredential = new TokenCredential("0", BrokenTokenUpdater, state, TimeSpan.FromSeconds(5));
// make sure the token starts with the right value, t=0
Assert.AreEqual("0", tokenCredential.Token);
// wait until timer triggers for the first time and validate token value, t=6
Task.Delay(TimeSpan.FromSeconds(6)).Wait();
Assert.AreEqual("0", tokenCredential.Token);
// wait until timer triggers for the second time and validate token value, 6=12
Task.Delay(TimeSpan.FromSeconds(6)).Wait();
Assert.AreEqual("0", tokenCredential.Token);
// stop the time and make sure it does not trigger anymore, t=18
tokenCredential.Dispose();
Task.Delay(TimeSpan.FromSeconds(6)).Wait();
Assert.AreEqual("0", tokenCredential.Token);
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V10.Resources
{
/// <summary>Resource name for the <c>ProductBiddingCategoryConstant</c> resource.</summary>
public sealed partial class ProductBiddingCategoryConstantName : gax::IResourceName, sys::IEquatable<ProductBiddingCategoryConstantName>
{
/// <summary>The possible contents of <see cref="ProductBiddingCategoryConstantName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>productBiddingCategoryConstants/{country_code}~{level}~{id}</c>.
/// </summary>
CountryCodeLevelId = 1,
}
private static gax::PathTemplate s_countryCodeLevelId = new gax::PathTemplate("productBiddingCategoryConstants/{country_code_level_id}");
/// <summary>
/// Creates a <see cref="ProductBiddingCategoryConstantName"/> containing an unparsed resource name.
/// </summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="ProductBiddingCategoryConstantName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static ProductBiddingCategoryConstantName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new ProductBiddingCategoryConstantName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="ProductBiddingCategoryConstantName"/> with the pattern
/// <c>productBiddingCategoryConstants/{country_code}~{level}~{id}</c>.
/// </summary>
/// <param name="countryCodeId">The <c>CountryCode</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="levelId">The <c>Level</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="idId">The <c>Id</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// A new instance of <see cref="ProductBiddingCategoryConstantName"/> constructed from the provided ids.
/// </returns>
public static ProductBiddingCategoryConstantName FromCountryCodeLevelId(string countryCodeId, string levelId, string idId) =>
new ProductBiddingCategoryConstantName(ResourceNameType.CountryCodeLevelId, countryCodeId: gax::GaxPreconditions.CheckNotNullOrEmpty(countryCodeId, nameof(countryCodeId)), levelId: gax::GaxPreconditions.CheckNotNullOrEmpty(levelId, nameof(levelId)), idId: gax::GaxPreconditions.CheckNotNullOrEmpty(idId, nameof(idId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ProductBiddingCategoryConstantName"/> with
/// pattern <c>productBiddingCategoryConstants/{country_code}~{level}~{id}</c>.
/// </summary>
/// <param name="countryCodeId">The <c>CountryCode</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="levelId">The <c>Level</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="idId">The <c>Id</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ProductBiddingCategoryConstantName"/> with pattern
/// <c>productBiddingCategoryConstants/{country_code}~{level}~{id}</c>.
/// </returns>
public static string Format(string countryCodeId, string levelId, string idId) =>
FormatCountryCodeLevelId(countryCodeId, levelId, idId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ProductBiddingCategoryConstantName"/> with
/// pattern <c>productBiddingCategoryConstants/{country_code}~{level}~{id}</c>.
/// </summary>
/// <param name="countryCodeId">The <c>CountryCode</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="levelId">The <c>Level</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="idId">The <c>Id</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ProductBiddingCategoryConstantName"/> with pattern
/// <c>productBiddingCategoryConstants/{country_code}~{level}~{id}</c>.
/// </returns>
public static string FormatCountryCodeLevelId(string countryCodeId, string levelId, string idId) =>
s_countryCodeLevelId.Expand($"{(gax::GaxPreconditions.CheckNotNullOrEmpty(countryCodeId, nameof(countryCodeId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(levelId, nameof(levelId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(idId, nameof(idId)))}");
/// <summary>
/// Parses the given resource name string into a new <see cref="ProductBiddingCategoryConstantName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>productBiddingCategoryConstants/{country_code}~{level}~{id}</c></description></item>
/// </list>
/// </remarks>
/// <param name="productBiddingCategoryConstantName">
/// The resource name in string form. Must not be <c>null</c>.
/// </param>
/// <returns>The parsed <see cref="ProductBiddingCategoryConstantName"/> if successful.</returns>
public static ProductBiddingCategoryConstantName Parse(string productBiddingCategoryConstantName) =>
Parse(productBiddingCategoryConstantName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="ProductBiddingCategoryConstantName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>productBiddingCategoryConstants/{country_code}~{level}~{id}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="productBiddingCategoryConstantName">
/// The resource name in string form. Must not be <c>null</c>.
/// </param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="ProductBiddingCategoryConstantName"/> if successful.</returns>
public static ProductBiddingCategoryConstantName Parse(string productBiddingCategoryConstantName, bool allowUnparsed) =>
TryParse(productBiddingCategoryConstantName, allowUnparsed, out ProductBiddingCategoryConstantName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="ProductBiddingCategoryConstantName"/>
/// instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>productBiddingCategoryConstants/{country_code}~{level}~{id}</c></description></item>
/// </list>
/// </remarks>
/// <param name="productBiddingCategoryConstantName">
/// The resource name in string form. Must not be <c>null</c>.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="ProductBiddingCategoryConstantName"/>, or <c>null</c> if
/// parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string productBiddingCategoryConstantName, out ProductBiddingCategoryConstantName result) =>
TryParse(productBiddingCategoryConstantName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="ProductBiddingCategoryConstantName"/>
/// instance; optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>productBiddingCategoryConstants/{country_code}~{level}~{id}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="productBiddingCategoryConstantName">
/// The resource name in string form. Must not be <c>null</c>.
/// </param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="ProductBiddingCategoryConstantName"/>, or <c>null</c> if
/// parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string productBiddingCategoryConstantName, bool allowUnparsed, out ProductBiddingCategoryConstantName result)
{
gax::GaxPreconditions.CheckNotNull(productBiddingCategoryConstantName, nameof(productBiddingCategoryConstantName));
gax::TemplatedResourceName resourceName;
if (s_countryCodeLevelId.TryParseName(productBiddingCategoryConstantName, out resourceName))
{
string[] split0 = ParseSplitHelper(resourceName[0], new char[] { '~', '~', });
if (split0 == null)
{
result = null;
return false;
}
result = FromCountryCodeLevelId(split0[0], split0[1], split0[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(productBiddingCategoryConstantName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private static string[] ParseSplitHelper(string s, char[] separators)
{
string[] result = new string[separators.Length + 1];
int i0 = 0;
for (int i = 0; i <= separators.Length; i++)
{
int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length;
if (i1 < 0 || i1 == i0)
{
return null;
}
result[i] = s.Substring(i0, i1 - i0);
i0 = i1 + 1;
}
return result;
}
private ProductBiddingCategoryConstantName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string countryCodeId = null, string idId = null, string levelId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
CountryCodeId = countryCodeId;
IdId = idId;
LevelId = levelId;
}
/// <summary>
/// Constructs a new instance of a <see cref="ProductBiddingCategoryConstantName"/> class from the component
/// parts of pattern <c>productBiddingCategoryConstants/{country_code}~{level}~{id}</c>
/// </summary>
/// <param name="countryCodeId">The <c>CountryCode</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="levelId">The <c>Level</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="idId">The <c>Id</c> ID. Must not be <c>null</c> or empty.</param>
public ProductBiddingCategoryConstantName(string countryCodeId, string levelId, string idId) : this(ResourceNameType.CountryCodeLevelId, countryCodeId: gax::GaxPreconditions.CheckNotNullOrEmpty(countryCodeId, nameof(countryCodeId)), levelId: gax::GaxPreconditions.CheckNotNullOrEmpty(levelId, nameof(levelId)), idId: gax::GaxPreconditions.CheckNotNullOrEmpty(idId, nameof(idId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>CountryCode</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CountryCodeId { get; }
/// <summary>
/// The <c>Id</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string IdId { get; }
/// <summary>
/// The <c>Level</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LevelId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.CountryCodeLevelId: return s_countryCodeLevelId.Expand($"{CountryCodeId}~{LevelId}~{IdId}");
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as ProductBiddingCategoryConstantName);
/// <inheritdoc/>
public bool Equals(ProductBiddingCategoryConstantName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(ProductBiddingCategoryConstantName a, ProductBiddingCategoryConstantName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(ProductBiddingCategoryConstantName a, ProductBiddingCategoryConstantName b) => !(a == b);
}
public partial class ProductBiddingCategoryConstant
{
/// <summary>
/// <see cref="ProductBiddingCategoryConstantName"/>-typed view over the <see cref="ResourceName"/> resource
/// name property.
/// </summary>
internal ProductBiddingCategoryConstantName ResourceNameAsProductBiddingCategoryConstantName
{
get => string.IsNullOrEmpty(ResourceName) ? null : ProductBiddingCategoryConstantName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="ProductBiddingCategoryConstantName"/>-typed view over the
/// <see cref="ProductBiddingCategoryConstantParent"/> resource name property.
/// </summary>
internal ProductBiddingCategoryConstantName ProductBiddingCategoryConstantParentAsProductBiddingCategoryConstantName
{
get => string.IsNullOrEmpty(ProductBiddingCategoryConstantParent) ? null : ProductBiddingCategoryConstantName.Parse(ProductBiddingCategoryConstantParent, allowUnparsed: true);
set => ProductBiddingCategoryConstantParent = value?.ToString() ?? "";
}
}
}
| |
using System;
namespace C5
{
/// <summary>
/// A read-only wrapper for a generic list collection
/// <i>Suitable as a wrapper for LinkedList, HashedLinkedList, ArrayList and HashedArray.
/// <see cref="T:C5.LinkedList`1"/>,
/// <see cref="T:C5.HashedLinkedList`1"/>,
/// <see cref="T:C5.ArrayList`1"/> or
/// <see cref="T:C5.HashedArray`1"/>.
/// </i>
/// </summary>
[Serializable]
public class GuardedList<T> : GuardedSequenced<T>, IList<T>, System.Collections.Generic.IList<T>
{
#region Fields
private readonly IList<T> innerlist;
private readonly GuardedList<T>? underlying;
private readonly bool slidableView = false;
#endregion
#region Constructor
/// <summary>
/// Wrap a list in a read-only wrapper. A list gets wrapped as read-only,
/// a list view gets wrapped as read-only and non-slidable.
/// </summary>
/// <param name="list">The list</param>
public GuardedList(IList<T> list)
: base(list)
{
innerlist = list;
// If wrapping a list view, make innerlist = the view, and make
// underlying = a guarded version of the view's underlying list
if (list.Underlying != null)
{
underlying = new GuardedList<T>(list.Underlying, null, false);
}
}
private GuardedList(IList<T> list, GuardedList<T>? underlying, bool slidableView)
: base(list)
{
innerlist = list; this.underlying = underlying; this.slidableView = slidableView;
}
#endregion
#region IList<T> Members
/// <summary>
///
/// </summary>
/// <value>The first item of the wrapped list</value>
public T First => innerlist.First;
/// <summary>
///
/// </summary>
/// <value>The last item of the wrapped list</value>
public T Last => innerlist.Last;
/// <summary>
/// </summary>
/// <exception cref="ReadOnlyCollectionException"> if used as setter</exception>
/// <value>True if wrapped list has FIFO semantics for the Add(T item) and Remove() methods</value>
public bool FIFO
{
get => innerlist.FIFO;
set => throw new ReadOnlyCollectionException("List is read only");
}
/// <summary>
///
/// </summary>
public virtual bool IsFixedSize => true;
/// <summary>
/// </summary>
/// <exception cref="ReadOnlyCollectionException"> if used as setter</exception>
/// <value>The i'th item of the wrapped list</value>
public T this[int i]
{
get => innerlist[i];
set => throw new ReadOnlyCollectionException("List is read only");
}
/// <summary>
///
/// </summary>
/// <value></value>
public virtual Speed IndexingSpeed => innerlist.IndexingSpeed;
/// <summary>
/// </summary>
/// <exception cref="ReadOnlyCollectionException"> since this is a read-only wrapper</exception>
/// <param name="index"></param>
/// <param name="item"></param>
public void Insert(int index, T item)
{
throw new ReadOnlyCollectionException();
}
/// <summary>
/// </summary>
/// <exception cref="ReadOnlyCollectionException"> since this is a read-only wrapper</exception>
/// <param name="pointer"></param>
/// <param name="item"></param>
public void Insert(IList<T> pointer, T item)
{
throw new ReadOnlyCollectionException();
}
/// <summary>
/// </summary>
/// <exception cref="ReadOnlyCollectionException"> since this is a read-only wrapper</exception>
/// <param name="item"></param>
public void InsertFirst(T item)
{
throw new ReadOnlyCollectionException("List is read only");
}
/// <summary>
/// </summary>
/// <exception cref="ReadOnlyCollectionException"> since this is a read-only wrapper</exception>
/// <param name="item"></param>
public void InsertLast(T item)
{
throw new ReadOnlyCollectionException("List is read only");
}
/// <summary>
/// </summary>
/// <exception cref="ReadOnlyCollectionException"> since this is a read-only wrapper</exception>
/// <param name="item"></param>
/// <param name="target"></param>
public void InsertBefore(T item, T target)
{
throw new ReadOnlyCollectionException("List is read only");
}
/// <summary>
/// </summary>
/// <exception cref="ReadOnlyCollectionException"> since this is a read-only wrapper</exception>
/// <param name="item"></param>
/// <param name="target"></param>
public void InsertAfter(T item, T target)
{
throw new ReadOnlyCollectionException("List is read only");
}
/// <summary>
/// </summary>
/// <exception cref="ReadOnlyCollectionException"> since this is a read-only wrapper</exception>
/// <param name="i"></param>
/// <param name="items"></param>
public void InsertAll(int i, System.Collections.Generic.IEnumerable<T> items)
{ throw new ReadOnlyCollectionException("List is read only"); }
/// <summary>
/// Perform FindAll on the wrapped list. The result is <b>not</b> necessarily read-only.
/// </summary>
/// <param name="filter">The filter to use</param>
/// <returns></returns>
public IList<T> FindAll(Func<T, bool> filter) { return innerlist.FindAll(filter); }
/// <summary>
/// Perform Map on the wrapped list. The result is <b>not</b> necessarily read-only.
/// </summary>
/// <typeparam name="V">The type of items of the new list</typeparam>
/// <param name="mapper">The mapper to use.</param>
/// <returns>The mapped list</returns>
public IList<V> Map<V>(Func<T, V> mapper) { return innerlist.Map(mapper); }
/// <summary>
/// Perform Map on the wrapped list. The result is <b>not</b> necessarily read-only.
/// </summary>
/// <typeparam name="V">The type of items of the new list</typeparam>
/// <param name="mapper">The delegate defining the map.</param>
/// <param name="itemequalityComparer">The itemequalityComparer to use for the new list</param>
/// <returns>The new list.</returns>
public IList<V> Map<V>(Func<T, V> mapper, System.Collections.Generic.IEqualityComparer<V> itemequalityComparer) { return innerlist.Map(mapper, itemequalityComparer); }
/// <summary>
/// </summary>
/// <exception cref="ReadOnlyCollectionException"> since this is a read-only wrapper</exception>
/// <returns></returns>
public T Remove() { throw new ReadOnlyCollectionException("List is read only"); }
/// <summary>
/// </summary>
/// <exception cref="ReadOnlyCollectionException"> since this is a read-only wrapper</exception>
/// <returns></returns>
public T RemoveFirst() { throw new ReadOnlyCollectionException("List is read only"); }
/// <summary>
/// </summary>
/// <exception cref="ReadOnlyCollectionException"> since this is a read-only wrapper</exception>
/// <returns></returns>
public T RemoveLast() { throw new ReadOnlyCollectionException("List is read only"); }
/// <summary>
/// Create the indicated view on the wrapped list and wrap it read-only.
/// </summary>
/// <param name="start"></param>
/// <param name="count"></param>
/// <returns></returns>
public IList<T>? View(int start, int count)
{
IList<T>? view = innerlist.View(start, count);
return view == null ? null : new GuardedList<T>(view, underlying ?? this, true);
}
/// <summary>
/// Create the indicated view on the wrapped list and wrap it read-only.
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public IList<T>? ViewOf(T item)
{
IList<T>? view = innerlist.ViewOf(item);
return view == null ? null : new GuardedList<T>(view, underlying ?? this, true);
}
/// <summary>
/// Create the indicated view on the wrapped list and wrap it read-only.
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public IList<T>? LastViewOf(T item)
{
IList<T>? view = innerlist.LastViewOf(item);
return view == null ? null : new GuardedList<T>(view, underlying ?? this, true);
}
/// <summary>
/// </summary>
/// <value>The wrapped underlying list of the wrapped view </value>
public IList<T>? Underlying => underlying;
/// <summary>
///
/// </summary>
/// <value>The offset of the wrapped list as a view.</value>
public int Offset => innerlist.Offset;
/// <summary>
///
/// </summary>
/// <value></value>
public virtual bool IsValid => innerlist.IsValid;
/// <summary>
/// </summary>
/// <exception cref="ReadOnlyCollectionException"> if this is a wrapped view and not a view that was made on a wrapper</exception>
/// <param name="offset"></param>
public IList<T> Slide(int offset)
{
if (slidableView)
{
innerlist.Slide(offset);
return this;
}
else
{
throw new ReadOnlyCollectionException("List is read only");
}
}
/// <summary>
/// </summary>
/// <exception cref="ReadOnlyCollectionException"> since this is a read-only wrapper</exception>
/// <param name="offset"></param>
/// <param name="size"></param>
public IList<T> Slide(int offset, int size)
{
if (slidableView)
{
innerlist.Slide(offset, size);
return this;
}
else
{
throw new ReadOnlyCollectionException("List is read only");
}
}
/// <summary>
///
/// </summary>
/// <exception cref="ReadOnlyCollectionException"> since this is a read-only wrapper</exception>
/// <param name="offset"></param>
/// <returns></returns>
public bool TrySlide(int offset)
{
if (slidableView)
{
return innerlist.TrySlide(offset);
}
else
{
throw new ReadOnlyCollectionException("List is read only");
}
}
/// <summary>
///
/// </summary>
/// <exception cref="ReadOnlyCollectionException"> since this is a read-only wrapper</exception>
/// <param name="offset"></param>
/// <param name="size"></param>
/// <returns></returns>
public bool TrySlide(int offset, int size)
{
if (slidableView)
{
return innerlist.TrySlide(offset, size);
}
else
{
throw new ReadOnlyCollectionException("List is read only");
}
}
/// <summary>
///
/// </summary>
/// <param name="otherView"></param>
/// <returns></returns>
public IList<T>? Span(IList<T> otherView)
{
if (!(otherView is GuardedList<T> otherGuardedList))
{
throw new IncompatibleViewException();
}
IList<T>? span = innerlist.Span(otherGuardedList.innerlist);
if (span == null)
{
return null;
}
return new GuardedList<T>(span, underlying ?? otherGuardedList.underlying ?? this, true);
}
/// <summary>
/// <exception cref="ReadOnlyCollectionException"> since this is a read-only wrapper</exception>
/// </summary>
public void Reverse() { throw new ReadOnlyCollectionException("List is read only"); }
/// <summary>
/// </summary>
/// <exception cref="ReadOnlyCollectionException"> since this is a read-only wrapper</exception>
/// <param name="start"></param>
/// <param name="count"></param>
public void Reverse(int start, int count)
{ throw new ReadOnlyCollectionException("List is read only"); }
/// <summary>
/// Check if wrapped list is sorted according to the default sorting order
/// for the item type T, as defined by the <see cref="T:C5.Comparer`1"/> class
/// </summary>
/// <exception cref="NotComparableException">if T is not comparable</exception>
/// <returns>True if the list is sorted, else false.</returns>
public bool IsSorted() { return innerlist.IsSorted(System.Collections.Generic.Comparer<T>.Default); }
/// <summary>
/// Check if wrapped list is sorted
/// </summary>
/// <param name="c">The sorting order to use</param>
/// <returns>True if sorted</returns>
public bool IsSorted(System.Collections.Generic.IComparer<T> c) { return innerlist.IsSorted(c); }
/// <summary>
/// </summary>
/// <exception cref="ReadOnlyCollectionException"> since this is a read-only wrapper</exception>
public void Sort()
{ throw new ReadOnlyCollectionException("List is read only"); }
/// <summary>
/// </summary>
/// <exception cref="ReadOnlyCollectionException"> since this is a read-only wrapper</exception>
/// <param name="c"></param>
public void Sort(System.Collections.Generic.IComparer<T> c)
{ throw new ReadOnlyCollectionException("List is read only"); }
/// <summary>
/// </summary>
/// <exception cref="ReadOnlyCollectionException"> since this is a read-only wrapper</exception>
public void Shuffle()
{ throw new ReadOnlyCollectionException("List is read only"); }
/// <summary>
/// </summary>
/// <exception cref="ReadOnlyCollectionException"> since this is a read-only wrapper</exception>
/// <param name="rnd"></param>
public void Shuffle(Random rnd)
{ throw new ReadOnlyCollectionException("List is read only"); }
#endregion
#region IIndexed<T> Members
/// <summary> </summary>
/// <value>A directed collection of the items in the indicated interval of the wrapped collection</value>
public IDirectedCollectionValue<T> this[int start, int end] => new GuardedDirectedCollectionValue<T>(innerlist[start, end]);
/// <summary>
/// Find the (first) index of an item in the wrapped collection
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public int IndexOf(T item) { return innerlist.IndexOf(item); }
/// <summary>
/// Find the last index of an item in the wrapped collection
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public int LastIndexOf(T item) { return innerlist.LastIndexOf(item); }
/// <summary>
/// </summary>
/// <exception cref="ReadOnlyCollectionException"> since this is a read-only wrapper</exception>
/// <param name="i"></param>
/// <returns></returns>
public T RemoveAt(int i)
{ throw new ReadOnlyCollectionException("List is read only"); }
/// <summary>
/// </summary>
/// <exception cref="ReadOnlyCollectionException"> since this is a read-only wrapper</exception>
/// <param name="start"></param>
/// <param name="count"></param>
public void RemoveInterval(int start, int count)
{ throw new ReadOnlyCollectionException("List is read only"); }
#endregion
#region IDirectedEnumerable<T> Members
IDirectedEnumerable<T> IDirectedEnumerable<T>.Backwards()
{ return Backwards(); }
#endregion
#region IStack<T> Members
/// <summary>
///
/// </summary>
/// <exception cref="ReadOnlyCollectionException"> since this is a read-only wrapper</exception>
/// <returns>-</returns>
public void Push(T item)
{ throw new ReadOnlyCollectionException("Collection cannot be modified through this guard object"); }
/// <summary>
///
/// </summary>
/// <exception cref="ReadOnlyCollectionException"> since this is a read-only wrapper</exception>
/// <returns>-</returns>
public T Pop()
{ throw new ReadOnlyCollectionException("Collection cannot be modified through this guard object"); }
#endregion
#region IQueue<T> Members
/// <summary>
///
/// </summary>
/// <exception cref="ReadOnlyCollectionException"> since this is a read-only wrapper</exception>
/// <returns>-</returns>
public void Enqueue(T item)
{ throw new ReadOnlyCollectionException("Collection cannot be modified through this guard object"); }
/// <summary>
///
/// </summary>
/// <exception cref="ReadOnlyCollectionException"> since this is a read-only wrapper</exception>
/// <returns>-</returns>
public T Dequeue()
{ throw new ReadOnlyCollectionException("Collection cannot be modified through this guard object"); }
#endregion
#region IDisposable Members
/// <summary>
/// Ignore: this may be called by a foreach or using statement.
/// </summary>
public void Dispose() { }
#endregion
#region System.Collections.Generic.IList<T> Members
void System.Collections.Generic.IList<T>.RemoveAt(int index)
{
throw new ReadOnlyCollectionException("Collection cannot be modified through this guard object");
}
void System.Collections.Generic.ICollection<T>.Add(T item)
{
throw new ReadOnlyCollectionException("Collection cannot be modified through this guard object");
}
#endregion
#region System.Collections.ICollection Members
bool System.Collections.ICollection.IsSynchronized => false;
[Obsolete]
Object System.Collections.ICollection.SyncRoot => innerlist.SyncRoot;
void System.Collections.ICollection.CopyTo(Array arr, int index)
{
if (index < 0 || index + Count > arr.Length)
{
throw new ArgumentOutOfRangeException();
}
foreach (T item in this)
{
arr.SetValue(item, index++);
}
}
#endregion
#region System.Collections.IList Members
Object System.Collections.IList.this[int index]
{
get => this[index]!;
set => throw new ReadOnlyCollectionException("Collection cannot be modified through this guard object");
}
int System.Collections.IList.Add(Object o)
{
throw new ReadOnlyCollectionException("Collection cannot be modified through this guard object");
}
bool System.Collections.IList.Contains(Object o)
{
return Contains((T)o);
}
int System.Collections.IList.IndexOf(Object o)
{
return Math.Max(-1, IndexOf((T)o));
}
void System.Collections.IList.Insert(int index, Object o)
{
throw new ReadOnlyCollectionException("Collection cannot be modified through this guard object");
}
void System.Collections.IList.Remove(Object o)
{
throw new ReadOnlyCollectionException("Collection cannot be modified through this guard object");
}
void System.Collections.IList.RemoveAt(int index)
{
throw new ReadOnlyCollectionException("Collection cannot be modified through this guard object");
}
#endregion
}
}
| |
/*
* Creato da SharpDevelop.
* Utente: lucabonotto
* Data: 05/04/2008
* Ora: 13.35
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
namespace LBSoft.IndustrialCtrls.Knobs
{
/// <summary>
/// Description of LBKnob.
/// </summary>
public partial class LBKnob : UserControl
{
#region Enumerators
public enum KnobStyle
{
Circular = 0,
}
#endregion
#region Properties variables
private float minValue = 0.0F;
private float maxValue = 1.0F;
private float stepValue = 0.1F;
private float currValue = 0.0F;
private KnobStyle style = KnobStyle.Circular;
private LBKnobRenderer renderer = null;
private Color scaleColor = Color.Green;
private Color knobColor = Color.Black ;
private Color indicatorColor = Color.Red;
private float indicatorOffset = 10F;
#endregion
#region Class variables
private RectangleF drawRect;
private RectangleF rectScale;
private RectangleF rectKnob;
private float drawRatio;
private LBKnobRenderer defaultRenderer = null;
private bool isKnobRotating = false;
private PointF knobCenter;
private PointF knobIndicatorPos;
#endregion
#region Constructor
public LBKnob()
{
InitializeComponent();
// Set the styles for drawing
SetStyle(ControlStyles.AllPaintingInWmPaint |
ControlStyles.ResizeRedraw |
ControlStyles.DoubleBuffer |
ControlStyles.SupportsTransparentBackColor,
true);
// Transparent background
this.BackColor = Color.Transparent;
this.defaultRenderer = new LBKnobRenderer();
this.defaultRenderer.Knob = this;
this.CalculateDimensions();
}
#endregion
#region Properties
[
Category("Knob"),
Description("Minimum value of the knob")
]
public float MinValue
{
set
{
this.minValue = value;
this.Invalidate();
}
get { return this.minValue; }
}
[
Category("Knob"),
Description("Maximum value of the knob")
]
public float MaxValue
{
set
{
this.maxValue = value;
this.Invalidate();
}
get { return this.maxValue; }
}
[
Category("Knob"),
Description("Step value of the knob")
]
public float StepValue
{
set
{
this.stepValue = value;
this.Invalidate();
}
get { return this.stepValue; }
}
[
Category("Knob"),
Description("Current value of the knob")
]
public float Value
{
set
{
if ( value != this.currValue )
{
this.currValue = value;
this.knobIndicatorPos = this.GetPositionFromValue ( this.currValue );
this.Invalidate();
LBKnobEventArgs e = new LBKnobEventArgs();
e.Value = this.currValue;
this.OnKnobChangeValue( e );
}
}
get { return this.currValue; }
}
[
Category("Knob"),
Description("Style of the knob")
]
public KnobStyle Style
{
set
{
this.style = value;
this.Invalidate();
}
get { return this.style; }
}
[
Category("Knob"),
Description("Color of the knob")
]
public Color KnobColor
{
set
{
this.knobColor = value;
this.Invalidate();
}
get { return this.knobColor; }
}
[
Category("Knob"),
Description("Color of the scale")
]
public Color ScaleColor
{
set
{
this.scaleColor = value;
this.Invalidate();
}
get { return this.scaleColor; }
}
[
Category("Knob"),
Description("Color of the indicator")
]
public Color IndicatorColor
{
set
{
this.indicatorColor = value;
this.Invalidate();
}
get { return this.indicatorColor; }
}
[
Category("Knob"),
Description("Offset of the indicator from the kob border")
]
public float IndicatorOffset
{
set
{
this.indicatorOffset = value;
this.CalculateDimensions();
this.Invalidate();
}
get { return this.indicatorOffset; }
}
[Browsable(false)]
public LBKnobRenderer Renderer
{
get { return this.renderer; }
set
{
this.renderer = value;
if ( this.renderer != null )
renderer.Knob = this;
Invalidate();
}
}
[Browsable(false)]
public PointF KnobCenter
{
get { return this.knobCenter; }
}
#endregion
#region Events delegates
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
bool blResult = true;
/// <summary>
/// Specified WM_KEYDOWN enumeration value.
/// </summary>
const int WM_KEYDOWN = 0x0100;
/// <summary>
/// Specified WM_SYSKEYDOWN enumeration value.
/// </summary>
const int WM_SYSKEYDOWN = 0x0104;
float val = this.Value;
if ((msg.Msg == WM_KEYDOWN) || (msg.Msg == WM_SYSKEYDOWN))
{
switch(keyData)
{
case Keys.Up:
val += this.StepValue;
if ( val <= this.MaxValue )
this.Value = val;
break;
case Keys.Down:
val -= this.StepValue;
if ( val >= this.MinValue )
this.Value = val;
break;
case Keys.PageUp:
if ( val < this.MaxValue )
{
val += ( this.StepValue * 10 );
this.Value = val;
}
break;
case Keys.PageDown:
if ( val > this.MinValue )
{
val -= ( this.StepValue * 10 );
this.Value = val;
}
break;
case Keys.Home:
this.Value = this.MinValue;
break;
case Keys.End:
this.Value = this.MaxValue;
break;
default:
blResult = base.ProcessCmdKey(ref msg,keyData);
break;
}
}
return blResult;
}
[System.ComponentModel.EditorBrowsableAttribute()]
protected override void OnClick(EventArgs e)
{
this.Focus();
this.Invalidate();
base.OnClick(e);
}
void OnMouseUp(object sender, MouseEventArgs e)
{
this.isKnobRotating = false;
if ( this.rectKnob.Contains ( e.Location ) == false )
return;
float val = this.GetValueFromPosition ( e.Location );
if ( val != this.Value )
{
this.Value = val;
this.Invalidate();
}
}
void OnMouseDown(object sender, MouseEventArgs e)
{
if ( this.rectKnob.Contains ( e.Location ) == false )
return;
this.isKnobRotating = true;
this.Focus();
}
void OnMouseMove(object sender, MouseEventArgs e)
{
if ( this.isKnobRotating == false )
return;
float val = this.GetValueFromPosition ( e.Location );
if ( val != this.Value )
{
this.Value = val;
this.Invalidate ();
}
}
void OnKeyDown(object sender, KeyEventArgs e)
{
float val = this.Value;
switch ( e.KeyCode )
{
case Keys.Up:
val = this.Value + this.StepValue;
break;
case Keys.Down:
val = this.Value - this.StepValue;
break;
}
if ( val < this.MinValue )
val = this.MinValue;
if ( val > this.MaxValue )
val = this.MaxValue;
this.Value = val;
}
[System.ComponentModel.EditorBrowsableAttribute()]
protected override void OnSizeChanged(EventArgs e)
{
base.OnSizeChanged(e);
this.CalculateDimensions();
this.Invalidate();
}
[System.ComponentModel.EditorBrowsableAttribute()]
protected override void OnPaint(PaintEventArgs e)
{
RectangleF _rc = new RectangleF(0, 0, this.Width, this.Height );
e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
if ( this.Renderer == null )
{
this.defaultRenderer.DrawBackground( e.Graphics, _rc );
this.defaultRenderer.DrawScale( e.Graphics, this.rectScale );
this.defaultRenderer.DrawKnob( e.Graphics, this.rectKnob );
this.defaultRenderer.DrawKnobIndicator( e.Graphics, this.rectKnob, this.knobIndicatorPos );
return;
}
this.Renderer.DrawBackground( e.Graphics, _rc );
this.Renderer.DrawScale( e.Graphics, this.rectScale );
this.Renderer.DrawKnob( e.Graphics, this.rectKnob );
this.Renderer.DrawKnobIndicator( e.Graphics, this.rectKnob, this.knobIndicatorPos );
}
#endregion
#region Virtual functions
protected virtual void CalculateDimensions()
{
// Rectangle
float x, y, w, h;
x = 0;
y = 0;
w = this.Size.Width;
h = this.Size.Height;
// Calculate ratio
drawRatio = (Math.Min(w,h)) / 200;
if ( drawRatio == 0.0 )
drawRatio = 1;
// Draw rectangle
drawRect.X = x;
drawRect.Y = y;
drawRect.Width = w - 2;
drawRect.Height = h - 2;
if ( w < h )
drawRect.Height = w;
else if ( w > h )
drawRect.Width = h;
if ( drawRect.Width < 10 )
drawRect.Width = 10;
if ( drawRect.Height < 10 )
drawRect.Height = 10;
this.rectScale = this.drawRect;
this.rectKnob = this.drawRect;
this.rectKnob.Inflate ( -20 * this.drawRatio, -20 * this.drawRatio );
this.knobCenter.X = this.rectKnob.Left + ( this.rectKnob.Width * 0.5F );
this.knobCenter.Y = this.rectKnob.Top + ( this.rectKnob.Height * 0.5F );
this.knobIndicatorPos = this.GetPositionFromValue ( this.Value );
}
public virtual float GetValueFromPosition ( PointF position )
{
float degree = 0.0F;
float v = 0.0F;
PointF center = this.KnobCenter;
if ( position.X <= center.X )
{
degree = (center.Y - position.Y ) / (center.X - position.X );
degree = (float)Math.Atan(degree);
degree = (float)((degree) * (180F / Math.PI) + 45F);
v = (degree * ( this.MaxValue - this.MinValue )/ 270F);
}
else
{
if ( position.X > center.X )
{
degree = (position.Y - center.Y ) / (position.X - center.X );
degree = (float)Math.Atan(degree);
degree = (float)(225F + (degree) * (180F / Math.PI));
v = (degree * ( this.MaxValue - this.MinValue ) / 270F);
}
}
if ( v > this.MaxValue )
v = this.MaxValue;
if (v < this.MinValue )
v = this.MinValue;
return v;
}
public virtual PointF GetPositionFromValue ( float val )
{
PointF pos = new PointF( 0.0F, 0.0F );
// Elimina la divisione per 0
if ( ( this.MaxValue - this.MinValue ) == 0 )
return pos;
float _indicatorOffset = this.IndicatorOffset * this.drawRatio;
float degree = 270F * val / ( this.MaxValue - this.MinValue );
degree = (degree + 135F) * (float)Math.PI / 180F;
pos.X = (int)(Math.Cos(degree) * ((this.rectKnob.Width * 0.5F)- indicatorOffset ) + this.rectKnob.X + ( this.rectKnob.Width * 0.5F));
pos.Y = (int)(Math.Sin(degree) * ((this.rectKnob.Width * 0.5F)- indicatorOffset ) + this.rectKnob.Y + ( this.rectKnob.Height * 0.5F));
return pos;
}
#endregion
#region Fire events
public event KnobChangeValue KnobChangeValue;
protected virtual void OnKnobChangeValue( LBKnobEventArgs e )
{
if( this.KnobChangeValue != null )
this.KnobChangeValue( this, e );
}
#endregion
}
#region Classes for event and event delagates args
#region Event args class
/// <summary>
/// Class for events delegates
/// </summary>
public class LBKnobEventArgs : EventArgs
{
private float val;
public LBKnobEventArgs()
{
}
public float Value
{
get { return this.val; }
set { this.val = value; }
}
}
#endregion
#region Delegates
public delegate void KnobChangeValue ( object sender, LBKnobEventArgs e );
#endregion
#endregion
}
| |
// ZipOutputStream.cs
//
// Copyright (C) 2001 Mike Krueger
// Copyright (C) 2004 John Reilly
//
// This file was translated from java, it was part of the GNU Classpath
// Copyright (C) 2001 Free Software Foundation, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
using System;
using System.IO;
using System.Collections;
using System.Text;
using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.Zip.Compression;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
namespace ICSharpCode.SharpZipLib.Zip
{
/// <summary>
/// This is a DeflaterOutputStream that writes the files into a zip
/// archive one after another. It has a special method to start a new
/// zip entry. The zip entries contains information about the file name
/// size, compressed size, CRC, etc.
///
/// It includes support for Stored and Deflated entries.
/// This class is not thread safe.
/// <br/>
/// <br/>Author of the original java version : Jochen Hoenicke
/// </summary>
/// <example> This sample shows how to create a zip file
/// <code>
/// using System;
/// using System.IO;
///
/// using ICSharpCode.SharpZipLib.Core;
/// using ICSharpCode.SharpZipLib.Zip;
///
/// class MainClass
/// {
/// public static void Main(string[] args)
/// {
/// string[] filenames = Directory.GetFiles(args[0]);
/// byte[] buffer = new byte[4096];
///
/// using ( ZipOutputStream s = new ZipOutputStream(File.Create(args[1])) ) {
///
/// s.SetLevel(9); // 0 - store only to 9 - means best compression
///
/// foreach (string file in filenames) {
/// ZipEntry entry = new ZipEntry(file);
/// s.PutNextEntry(entry);
///
/// using (FileStream fs = File.OpenRead(file)) {
/// StreamUtils.Copy(fs, s, buffer);
/// }
/// }
/// }
/// }
/// }
/// </code>
/// </example>
public class ZipOutputStream : DeflaterOutputStream
{
#region Instance Fields
private ArrayList entries = new ArrayList();
private Crc32 crc = new Crc32();
private ZipEntry curEntry;
int defaultCompressionLevel = Deflater.DEFAULT_COMPRESSION;
CompressionMethod curMethod = CompressionMethod.Deflated;
/// <summary>
/// Used to track the size of data for an entry during writing.
/// </summary>
private long size;
/// <summary>
/// Offset to be recorded for each entry in the central header.
/// </summary>
private long offset;
private byte[] zipComment = new byte[0];
bool patchEntryHeader;
long crcPatchPos = -1;
long sizePatchPos = -1;
// Default is dynamic which is not backwards compatible and can cause problems
// with XP's built in compression which cant read Zip64 archives.
// However it does avoid the situation were a large file is added and cannot be completed correctly.
UseZip64 useZip64_ = UseZip64.Dynamic;
#endregion
#region Constructors
/// <summary>
/// Creates a new Zip output stream, writing a zip archive.
/// </summary>
/// <param name="baseOutputStream">
/// The output stream to which the archive contents are written.
/// </param>
public ZipOutputStream(Stream baseOutputStream)
: base(baseOutputStream, new Deflater(Deflater.DEFAULT_COMPRESSION, true))
{
}
#endregion
/// <summary>
/// Gets boolean indicating central header has been added for this archive...
/// No further entries can be added once this has been done.
/// </summary>
public bool IsFinished
{
get {
return entries == null;
}
}
/// <summary>
/// Set the zip file comment.
/// </summary>
/// <param name="comment">
/// The comment string
/// </param>
/// <exception name ="ArgumentOutOfRangeException">
/// Encoding of comment is longer than 0xffff bytes.
/// </exception>
public void SetComment(string comment)
{
byte[] commentBytes = ZipConstants.ConvertToArray(comment);
if (commentBytes.Length > 0xffff) {
throw new ArgumentOutOfRangeException("comment");
}
zipComment = commentBytes;
}
/// <summary>
/// Sets default compression level. The new level will be activated
/// immediately.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">
/// Level specified is not supported.
/// </exception>
/// <see cref="Deflater"/>
public void SetLevel(int level)
{
defaultCompressionLevel = level;
def.SetLevel(level);
}
/// <summary>
/// Get the current deflate compression level
/// </summary>
/// <returns>The current compression level</returns>
public int GetLevel()
{
return def.GetLevel();
}
/// <summary>
/// Get / set a value indicating how Zip64 Extension usage is determined when adding entries.
/// </summary>
public UseZip64 UseZip64
{
get { return useZip64_; }
set { useZip64_ = value; }
}
/// <summary>
/// Write an unsigned short in little endian byte order.
/// </summary>
private void WriteLeShort(int value)
{
unchecked {
baseOutputStream.WriteByte((byte)(value & 0xff));
baseOutputStream.WriteByte((byte)((value >> 8) & 0xff));
}
}
/// <summary>
/// Write an int in little endian byte order.
/// </summary>
private void WriteLeInt(int value)
{
unchecked {
WriteLeShort(value);
WriteLeShort(value >> 16);
}
}
/// <summary>
/// Write an int in little endian byte order.
/// </summary>
private void WriteLeLong(long value)
{
unchecked {
WriteLeInt((int)value);
WriteLeInt((int)(value >> 32));
}
}
/// <summary>
/// Starts a new Zip entry. It automatically closes the previous
/// entry if present.
/// All entry elements bar name are optional, but must be correct if present.
/// If the compression method is stored and the output is not patchable
/// the compression for that entry is automatically changed to deflate level 0
/// </summary>
/// <param name="entry">
/// the entry.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// if entry passed is null.
/// </exception>
/// <exception cref="System.IO.IOException">
/// if an I/O error occured.
/// </exception>
/// <exception cref="System.InvalidOperationException">
/// if stream was finished
/// </exception>
/// <exception cref="ZipException">
/// Too many entries in the Zip file<br/>
/// Entry name is too long<br/>
/// Finish has already been called<br/>
/// </exception>
public void PutNextEntry(ZipEntry entry)
{
if ( entry == null ) {
throw new ArgumentNullException("entry");
}
if (entries == null) {
throw new InvalidOperationException("ZipOutputStream was finished");
}
if (curEntry != null) {
CloseEntry();
}
if (entries.Count == int.MaxValue) {
throw new ZipException("Too many entries for Zip file");
}
CompressionMethod method = entry.CompressionMethod;
int compressionLevel = defaultCompressionLevel;
// Clear flags that the library manages internally
entry.Flags &= (int)GeneralBitFlags.UnicodeText;
patchEntryHeader = false;
bool headerInfoAvailable = true;
if (method == CompressionMethod.Stored) {
// Cant store values in a data descriptor as you cant extract stored files
// if the length isnt known.
entry.Flags &= ~8;
if (entry.CompressedSize >= 0) {
if (entry.Size < 0) {
entry.Size = entry.CompressedSize;
} else if (entry.Size != entry.CompressedSize) {
throw new ZipException("Method STORED, but compressed size != size");
}
} else {
if (entry.Size >= 0) {
entry.CompressedSize = entry.Size;
}
}
if (entry.Size < 0 || entry.Crc < 0) {
if (CanPatchEntries == true) {
headerInfoAvailable = false;
}
else {
// Can't patch entries so storing is not possible.
method = CompressionMethod.Deflated;
compressionLevel = 0;
}
}
}
if (method == CompressionMethod.Deflated) {
if (entry.Size == 0) {
// No need to compress - no data.
entry.CompressedSize = entry.Size;
entry.Crc = 0;
method = CompressionMethod.Stored;
} else if ( (entry.CompressedSize < 0) || (entry.Size < 0) || (entry.Crc < 0) ) {
headerInfoAvailable = false;
}
}
if (headerInfoAvailable == false) {
if (CanPatchEntries == false) {
// Only way to record size and compressed size is to append a data descriptor
// after compressed data.
entry.Flags |= 8;
} else {
patchEntryHeader = true;
}
}
if (Password != null) {
entry.IsCrypted = true;
if (entry.Crc < 0) {
// Need to append a data descriptor as the crc isnt available for use
// with encryption, the date is used instead. Setting the flag
// indicates this to the decompressor.
entry.Flags |= 8;
}
}
entry.Offset = offset;
entry.CompressionMethod = (CompressionMethod)method;
curMethod = method;
sizePatchPos = -1;
if ( (useZip64_ == UseZip64.On) || ((entry.Size < 0) && (useZip64_ == UseZip64.Dynamic)) ) {
entry.ForceZip64();
}
// Write the local file header
WriteLeInt(ZipConstants.LocalHeaderSignature);
WriteLeShort(entry.Version);
WriteLeShort(entry.Flags);
WriteLeShort((byte)method);
WriteLeInt((int)entry.DosTime);
// TODO: Refactor header writing. Its done in several places.
if (headerInfoAvailable == true) {
WriteLeInt((int)entry.Crc);
if ( entry.LocalHeaderRequiresZip64 ) {
WriteLeInt(-1);
WriteLeInt(-1);
}
else {
WriteLeInt(entry.IsCrypted ? (int)entry.CompressedSize + ZipConstants.CryptoHeaderSize : (int)entry.CompressedSize);
WriteLeInt((int)entry.Size);
}
} else {
if (patchEntryHeader == true) {
crcPatchPos = baseOutputStream.Position;
}
WriteLeInt(0); // Crc
if ( patchEntryHeader ) {
sizePatchPos = baseOutputStream.Position;
}
// For local header both sizes appear in Zip64 Extended Information
if ( entry.LocalHeaderRequiresZip64 && patchEntryHeader ) {
WriteLeInt(-1);
WriteLeInt(-1);
}
else {
WriteLeInt(0); // Compressed size
WriteLeInt(0); // Uncompressed size
}
}
byte[] name = ZipConstants.ConvertToArray(entry.Flags, entry.Name);
if (name.Length > 0xFFFF) {
throw new ZipException("Entry name too long.");
}
ZipExtraData ed = new ZipExtraData(entry.ExtraData);
if (entry.LocalHeaderRequiresZip64 && (headerInfoAvailable || patchEntryHeader)) {
ed.StartNewEntry();
if (headerInfoAvailable) {
ed.AddLeLong(entry.Size);
ed.AddLeLong(entry.CompressedSize);
}
else {
ed.AddLeLong(-1);
ed.AddLeLong(-1);
}
ed.AddNewEntry(1);
if ( !ed.Find(1) ) {
throw new ZipException("Internal error cant find extra data");
}
if ( patchEntryHeader ) {
sizePatchPos = ed.CurrentReadIndex;
}
}
else {
ed.Delete(1);
}
byte[] extra = ed.GetEntryData();
WriteLeShort(name.Length);
WriteLeShort(extra.Length);
if ( name.Length > 0 ) {
baseOutputStream.Write(name, 0, name.Length);
}
if ( entry.LocalHeaderRequiresZip64 && patchEntryHeader ) {
sizePatchPos += baseOutputStream.Position;
}
if ( extra.Length > 0 ) {
baseOutputStream.Write(extra, 0, extra.Length);
}
offset += ZipConstants.LocalHeaderBaseSize + name.Length + extra.Length;
// Activate the entry.
curEntry = entry;
crc.Reset();
if (method == CompressionMethod.Deflated) {
def.Reset();
def.SetLevel(compressionLevel);
}
size = 0;
if (entry.IsCrypted == true) {
if (entry.Crc < 0) { // so testing Zip will says its ok
WriteEncryptionHeader(entry.DosTime << 16);
} else {
WriteEncryptionHeader(entry.Crc);
}
}
}
/// <summary>
/// Closes the current entry, updating header and footer information as required
/// </summary>
/// <exception cref="System.IO.IOException">
/// An I/O error occurs.
/// </exception>
/// <exception cref="System.InvalidOperationException">
/// No entry is active.
/// </exception>
public void CloseEntry()
{
if (curEntry == null) {
throw new InvalidOperationException("No open entry");
}
// First finish the deflater, if appropriate
if (curMethod == CompressionMethod.Deflated) {
base.Finish();
}
long csize = (curMethod == CompressionMethod.Deflated) ? def.TotalOut : size;
if (curEntry.Size < 0) {
curEntry.Size = size;
} else if (curEntry.Size != size) {
throw new ZipException("size was " + size + ", but I expected " + curEntry.Size);
}
if (curEntry.CompressedSize < 0) {
curEntry.CompressedSize = csize;
} else if (curEntry.CompressedSize != csize) {
throw new ZipException("compressed size was " + csize + ", but I expected " + curEntry.CompressedSize);
}
if (curEntry.Crc < 0) {
curEntry.Crc = crc.Value;
} else if (curEntry.Crc != crc.Value) {
throw new ZipException("crc was " + crc.Value + ", but I expected " + curEntry.Crc);
}
offset += csize;
if (curEntry.IsCrypted == true) {
curEntry.CompressedSize += ZipConstants.CryptoHeaderSize;
}
// Patch the header if possible
if (patchEntryHeader == true) {
patchEntryHeader = false;
long curPos = baseOutputStream.Position;
baseOutputStream.Seek(crcPatchPos, SeekOrigin.Begin);
WriteLeInt((int)curEntry.Crc);
if ( curEntry.LocalHeaderRequiresZip64 ) {
if ( sizePatchPos == -1 ) {
throw new ZipException("Entry requires zip64 but this has been turned off");
}
baseOutputStream.Seek(sizePatchPos, SeekOrigin.Begin);
WriteLeLong(curEntry.Size);
WriteLeLong(curEntry.CompressedSize);
}
else {
WriteLeInt((int)curEntry.CompressedSize);
WriteLeInt((int)curEntry.Size);
}
baseOutputStream.Seek(curPos, SeekOrigin.Begin);
}
// Add data descriptor if flagged as required
if ((curEntry.Flags & 8) != 0) {
WriteLeInt(ZipConstants.DataDescriptorSignature);
WriteLeInt((int)curEntry.Crc);
if ( curEntry.LocalHeaderRequiresZip64 ) {
WriteLeLong(curEntry.CompressedSize);
WriteLeLong(curEntry.Size);
offset += ZipConstants.Zip64DataDescriptorSize;
}
else {
WriteLeInt((int)curEntry.CompressedSize);
WriteLeInt((int)curEntry.Size);
offset += ZipConstants.DataDescriptorSize;
}
}
entries.Add(curEntry);
curEntry = null;
}
void WriteEncryptionHeader(long crcValue)
{
offset += ZipConstants.CryptoHeaderSize;
InitializePassword(Password);
byte[] cryptBuffer = new byte[ZipConstants.CryptoHeaderSize];
Random rnd = new Random();
rnd.NextBytes(cryptBuffer);
cryptBuffer[11] = (byte)(crcValue >> 24);
EncryptBlock(cryptBuffer, 0, cryptBuffer.Length);
baseOutputStream.Write(cryptBuffer, 0, cryptBuffer.Length);
}
/// <summary>
/// Writes the given buffer to the current entry.
/// </summary>
/// <exception cref="ZipException">
/// Archive size is invalid
/// </exception>
/// <exception cref="System.InvalidOperationException">
/// No entry is active.
/// </exception>
public override void Write(byte[] buffer, int offset, int count)
{
if (curEntry == null) {
throw new InvalidOperationException("No open entry.");
}
if ( buffer == null ) {
throw new ArgumentNullException("buffer");
}
if ( offset < 0 ) {
#if NETCF_1_0
throw new ArgumentOutOfRangeException("offset");
#else
throw new ArgumentOutOfRangeException("offset", "Cannot be negative");
#endif
}
if ( count < 0 ) {
#if NETCF_1_0
throw new ArgumentOutOfRangeException("count");
#else
throw new ArgumentOutOfRangeException("count", "Cannot be negative");
#endif
}
if ( (buffer.Length - offset) < count ) {
throw new ArgumentException("Invalid offset/count combination");
}
crc.Update(buffer, offset, count);
size += count;
switch (curMethod) {
case CompressionMethod.Deflated:
base.Write(buffer, offset, count);
break;
case CompressionMethod.Stored:
if (Password != null) {
// TODO: Stored & encrypted output can use a lot of memory/cpu with local copying..
byte[] localBuffer = new byte[count];
Array.Copy(buffer, offset, localBuffer, 0, count);
EncryptBlock(localBuffer, 0, count);
baseOutputStream.Write(localBuffer, offset, count);
} else {
baseOutputStream.Write(buffer, offset, count);
}
break;
}
}
/// <summary>
/// Finishes the stream. This will write the central directory at the
/// end of the zip file and flush the stream.
/// </summary>
/// <remarks>
/// This is automatically called when the stream is closed.
/// </remarks>
/// <exception cref="System.IO.IOException">
/// An I/O error occurs.
/// </exception>
/// <exception cref="ZipException">
/// Comment exceeds the maximum length<br/>
/// Entry name exceeds the maximum length
/// </exception>
public override void Finish()
{
if (entries == null) {
return;
}
if (curEntry != null) {
CloseEntry();
}
long numEntries = entries.Count;
long sizeEntries = 0;
foreach (ZipEntry entry in entries) {
WriteLeInt(ZipConstants.CentralHeaderSignature);
WriteLeShort(ZipConstants.VersionMadeBy);
WriteLeShort(entry.Version);
WriteLeShort(entry.Flags);
WriteLeShort((short)entry.CompressionMethod);
WriteLeInt((int)entry.DosTime);
WriteLeInt((int)entry.Crc);
if ( entry.IsZip64Forced() ||
(entry.CompressedSize >= uint.MaxValue) )
{
WriteLeInt(-1);
}
else {
WriteLeInt((int)entry.CompressedSize);
}
if ( entry.IsZip64Forced() ||
(entry.Size >= uint.MaxValue) )
{
WriteLeInt(-1);
}
else {
WriteLeInt((int)entry.Size);
}
byte[] name = ZipConstants.ConvertToArray(entry.Flags, entry.Name);
if (name.Length > 0xffff) {
throw new ZipException("Name too long.");
}
ZipExtraData ed = new ZipExtraData(entry.ExtraData);
if ( entry.CentralHeaderRequiresZip64 ) {
ed.StartNewEntry();
if ( entry.IsZip64Forced() ||
(entry.Size >= 0xffffffff) )
{
ed.AddLeLong(entry.Size);
}
if ( entry.IsZip64Forced() ||
(entry.CompressedSize >= 0xffffffff) )
{
ed.AddLeLong(entry.CompressedSize);
}
if ( entry.Offset >= 0xffffffff )
{
ed.AddLeLong(entry.Offset);
}
ed.AddNewEntry(1);
}
else {
ed.Delete(1);
}
byte[] extra = ed.GetEntryData();
byte[] entryComment =
(entry.Comment != null) ?
ZipConstants.ConvertToArray(entry.Flags, entry.Comment) :
new byte[0];
if (entryComment.Length > 0xffff) {
throw new ZipException("Comment too long.");
}
WriteLeShort(name.Length);
WriteLeShort(extra.Length);
WriteLeShort(entryComment.Length);
WriteLeShort(0); // disk number
WriteLeShort(0); // internal file attributes
// external file attributes
if (entry.ExternalFileAttributes != -1) {
WriteLeInt(entry.ExternalFileAttributes);
} else {
if (entry.IsDirectory) { // mark entry as directory (from nikolam.AT.perfectinfo.com)
WriteLeInt(16);
} else {
WriteLeInt(0);
}
}
if ( entry.Offset >= uint.MaxValue ) {
WriteLeInt(-1);
}
else {
WriteLeInt((int)entry.Offset);
}
if ( name.Length > 0 ) {
baseOutputStream.Write(name, 0, name.Length);
}
if ( extra.Length > 0 ) {
baseOutputStream.Write(extra, 0, extra.Length);
}
if ( entryComment.Length > 0 ) {
baseOutputStream.Write(entryComment, 0, entryComment.Length);
}
sizeEntries += ZipConstants.CentralHeaderBaseSize + name.Length + extra.Length + entryComment.Length;
}
using ( ZipHelperStream zhs = new ZipHelperStream(baseOutputStream) ) {
zhs.WriteEndOfCentralDirectory(numEntries, sizeEntries, offset, zipComment);
}
entries = null;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
namespace System.Internal
{
/// <summary>
/// The job of this class is to collect and track handle usage in windows forms. Ideally, a developer should never
/// have to call dispose() on any windows forms object. The problem in making this happen is in objects that are
/// very small to the VM garbage collector, but take up huge amounts of resources to the system. A good example of
/// this is a Win32 region handle. To the VM, a Region object is a small six ubyte object, so there isn't much need
/// to garbage collect it anytime soon. To Win32, however, a region handle consumes expensive USER and GDI
/// resources. Ideally we would like to be able to mark an object as "expensive" so it uses a different garbage
/// collection algorithm. In absence of that, we use the HandleCollector class, which runs a daemon thread to
/// garbage collect when handle usage goes up.
/// </summary>
internal class DebugHandleTracker
{
private static Hashtable s_handleTypes = new Hashtable();
private static DebugHandleTracker s_tracker;
static DebugHandleTracker()
{
s_tracker = new DebugHandleTracker();
if (CompModSwitches.HandleLeak.Level > TraceLevel.Off || CompModSwitches.TraceCollect.Enabled)
{
HandleCollector.HandleAdded += new HandleChangeEventHandler(s_tracker.OnHandleAdd);
HandleCollector.HandleRemoved += new HandleChangeEventHandler(s_tracker.OnHandleRemove);
}
}
private DebugHandleTracker()
{
}
private static object s_internalSyncObject = new object();
/// <summary>
/// All handles available at this time will be not be considered as leaks when CheckLeaks is called to report leaks.
/// </summary>
public static void IgnoreCurrentHandlesAsLeaks()
{
lock (s_internalSyncObject)
{
if (CompModSwitches.HandleLeak.Level >= TraceLevel.Warning)
{
HandleType[] types = new HandleType[s_handleTypes.Values.Count];
s_handleTypes.Values.CopyTo(types, 0);
for (int i = 0; i < types.Length; i++)
{
types[i]?.IgnoreCurrentHandlesAsLeaks();
}
}
}
}
/// <summary>
/// Called at shutdown to check for handles that are currently allocated. Normally, there should be none.
/// This will print a list of all handle leaks.
/// </summary>
public static void CheckLeaks()
{
lock (s_internalSyncObject)
{
if (CompModSwitches.HandleLeak.Level >= TraceLevel.Warning)
{
GC.Collect();
GC.WaitForPendingFinalizers();
HandleType[] types = new HandleType[s_handleTypes.Values.Count];
s_handleTypes.Values.CopyTo(types, 0);
Debug.WriteLine("------------Begin--CheckLeaks--------------------");
for (int i = 0; i < types.Length; i++)
{
types[i]?.CheckLeaks();
}
Debug.WriteLine("-------------End--CheckLeaks---------------------");
}
}
}
/// <summary>
/// Ensures leak detection has been initialized.
/// </summary>
public static void Initialize()
{
// Calling this method forces the class to be loaded, thus running the
// static constructor which does all the work.
}
/// <summary>
/// Called by the Win32 handle collector when a new handle is created.
/// </summary>
private void OnHandleAdd(string handleName, IntPtr handle, int handleCount)
{
HandleType type = (HandleType)s_handleTypes[handleName];
if (type == null)
{
type = new HandleType(handleName);
s_handleTypes[handleName] = type;
}
type.Add(handle);
}
/// <summary>
/// Called by the Win32 handle collector when a new handle is created.
/// </summary>
private void OnHandleRemove(string handleName, IntPtr handle, int HandleCount)
{
HandleType type = (HandleType)s_handleTypes[handleName];
bool removed = false;
if (type != null)
{
removed = type.Remove(handle);
}
if (!removed)
{
if (CompModSwitches.HandleLeak.Level >= TraceLevel.Error)
{
// It seems to me we shouldn't call HandleCollector.Remove more than once
// for a given handle, but we do just that for HWND's (NativeWindow.DestroyWindow
// and Control.WmNCDestroy).
Debug.WriteLine("*************************************************");
Debug.WriteLine("While removing, couldn't find handle: " + Convert.ToString(unchecked((int)handle), 16));
Debug.WriteLine("Handle Type : " + handleName);
Debug.WriteLine(Environment.StackTrace);
Debug.WriteLine("-------------------------------------------------");
}
}
}
/// <summary>
/// Represents a specific type of handle.
/// </summary>
private class HandleType
{
public readonly string name;
private int _handleCount;
private HandleEntry[] _buckets;
private const int NumberOfBuckets = 10;
/// <summary>
/// Creates a new handle type.
/// </summary>
public HandleType(string name)
{
this.name = name;
_buckets = new HandleEntry[NumberOfBuckets];
}
/// <summary>
/// Adds a handle to this handle type for monitoring.
/// </summary>
public void Add(IntPtr handle)
{
lock (this)
{
int hash = ComputeHash(handle);
if (CompModSwitches.HandleLeak.Level >= TraceLevel.Info)
{
Debug.WriteLine("-------------------------------------------------");
Debug.WriteLine("Handle Allocating: " + Convert.ToString(unchecked((int)handle), 16));
Debug.WriteLine("Handle Type : " + name);
if (CompModSwitches.HandleLeak.Level >= TraceLevel.Verbose)
Debug.WriteLine(Environment.StackTrace);
}
HandleEntry entry = _buckets[hash];
while (entry != null)
{
Debug.Assert(entry.handle != handle, "Duplicate handle of type " + name);
entry = entry.next;
}
_buckets[hash] = new HandleEntry(_buckets[hash], handle);
_handleCount++;
}
}
/// <summary>
/// Checks and reports leaks for handle monitoring.
/// </summary>
public void CheckLeaks()
{
lock (this)
{
bool reportedFirstLeak = false;
if (_handleCount > 0)
{
for (int i = 0; i < NumberOfBuckets; i++)
{
HandleEntry e = _buckets[i];
while (e != null)
{
if (!e.ignorableAsLeak)
{
if (!reportedFirstLeak)
{
Debug.WriteLine("\r\nHandle leaks detected for handles of type " + name + ":");
reportedFirstLeak = true;
}
Debug.WriteLine(e.ToString(this));
}
e = e.next;
}
}
}
}
}
/// <summary>
/// Marks all the handles currently stored, as ignorable, so that they will not be reported as leaks later.
/// </summary>
public void IgnoreCurrentHandlesAsLeaks()
{
lock (this)
{
if (_handleCount > 0)
{
for (int i = 0; i < NumberOfBuckets; i++)
{
HandleEntry e = _buckets[i];
while (e != null)
{
e.ignorableAsLeak = true;
e = e.next;
}
}
}
}
}
/// <summary>
/// Computes the hash bucket for this handle.
/// </summary>
private int ComputeHash(IntPtr handle)
{
return (unchecked((int)handle) & 0xFFFF) % NumberOfBuckets;
}
/// <summary>
/// Removes the given handle from our monitor list.
/// </summary>
public bool Remove(IntPtr handle)
{
lock (this)
{
int hash = ComputeHash(handle);
if (CompModSwitches.HandleLeak.Level >= TraceLevel.Info)
{
Debug.WriteLine("-------------------------------------------------");
Debug.WriteLine("Handle Releaseing: " + Convert.ToString(unchecked((int)handle), 16));
Debug.WriteLine("Handle Type : " + name);
if (CompModSwitches.HandleLeak.Level >= TraceLevel.Verbose)
Debug.WriteLine(Environment.StackTrace);
}
HandleEntry e = _buckets[hash];
HandleEntry last = null;
while (e != null && e.handle != handle)
{
last = e;
e = e.next;
}
if (e != null)
{
if (last == null)
{
_buckets[hash] = e.next;
}
else
{
last.next = e.next;
}
_handleCount--;
return true;
}
return false;
}
}
/// <summary>
/// Denotes a single entry in our handle list.
/// </summary>
private class HandleEntry
{
public readonly IntPtr handle;
public HandleEntry next;
public readonly string callStack;
public bool ignorableAsLeak;
/// <summary>
/// Creates a new handle entry
/// </summary>
public HandleEntry(HandleEntry next, IntPtr handle)
{
this.handle = handle;
this.next = next;
if (CompModSwitches.HandleLeak.Level > TraceLevel.Off)
{
callStack = Environment.StackTrace;
}
else
{
callStack = null;
}
}
/// <summary>
/// Converts this handle to a printable string. the string consists of the handle value along with
/// the callstack for it's allocation.
/// </summary>
public string ToString(HandleType type)
{
StackParser sp = new StackParser(callStack);
// Discard all of the stack up to and including the "Handle.create" call
sp.DiscardTo("HandleCollector.Add");
// Skip the next call as it is always a debug wrapper
sp.DiscardNext();
// Now recreate the leak list with a lot of stack entries
sp.Truncate(40);
string description = "";
return Convert.ToString(unchecked((int)handle), 16) + description + ": " + sp.ToString();
}
/// <summary>
/// Simple stack parsing class to manipulate our callstack.
/// </summary>
private class StackParser
{
internal string releventStack;
internal int startIndex;
internal int endIndex;
internal int length;
/// <summary>
/// Creates a new stackparser with the given callstack
/// </summary>
public StackParser(string callStack)
{
releventStack = callStack;
length = releventStack.Length;
}
/// <summary>
/// Determines if the given string contains token. This is a case sensitive match.
/// </summary>
private static bool ContainsString(string str, string token)
{
int stringLength = str.Length;
int tokenLength = token.Length;
for (int s = 0; s < stringLength; s++)
{
int t = 0;
while (t < tokenLength && str[s + t] == token[t])
{
t++;
}
if (t == tokenLength)
{
return true;
}
}
return false;
}
/// <summary>
/// Discards the next line of the stack trace.
/// </summary>
public void DiscardNext()
{
GetLine();
}
/// <summary>
/// Discards all lines up to and including the line that contains discardText.
/// </summary>
public void DiscardTo(string discardText)
{
while (startIndex < length)
{
string line = GetLine();
if (line == null || ContainsString(line, discardText))
{
break;
}
}
}
/// <summary>
/// Retrieves the next line of the stack.
/// </summary>
private string GetLine()
{
endIndex = releventStack.IndexOf('\r', startIndex);
if (endIndex < 0)
{
endIndex = length - 1;
}
string line = releventStack.Substring(startIndex, endIndex - startIndex);
char ch;
while (endIndex < length && ((ch = releventStack[endIndex]) == '\r' || ch == '\n'))
{
endIndex++;
}
if (startIndex == endIndex) return null;
startIndex = endIndex;
line = line.Replace('\t', ' ');
return line;
}
/// <summary>
/// Retrieves the string of the parsed stack trace
/// </summary>
public override string ToString()
{
return releventStack.Substring(startIndex);
}
/// <summary>
/// Truncates the stack trace, saving the given # of lines.
/// </summary>
public void Truncate(int lines)
{
string truncatedStack = "";
while (lines-- > 0 && startIndex < length)
{
if (truncatedStack == null)
{
truncatedStack = GetLine();
}
else
{
truncatedStack += ": " + GetLine();
}
truncatedStack += Environment.NewLine;
}
releventStack = truncatedStack;
startIndex = 0;
endIndex = 0;
length = releventStack.Length;
}
}
}
}
}
}
| |
// 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;
namespace System.Numerics.Tests
{
public class ComparisonTest
{
private const int NumberOfRandomIterations = 1;
[Fact]
public static void ComparisonTests()
{
int seed = 100;
RunTests(seed);
}
public static void RunTests(int seed)
{
Random random = new Random(seed);
RunPositiveTests(random);
RunNegativeTests(random);
}
private static void RunPositiveTests(Random random)
{
BigInteger bigInteger1, bigInteger2;
int expectedResult;
byte[] byteArray;
bool isNegative;
//1 Inputs from BigInteger Properties
// BigInteger.MinusOne, BigInteger.MinusOne
VerifyComparison(BigInteger.MinusOne, BigInteger.MinusOne, 0);
// BigInteger.MinusOne, BigInteger.Zero
VerifyComparison(BigInteger.MinusOne, BigInteger.Zero, -1);
// BigInteger.MinusOne, BigInteger.One
VerifyComparison(BigInteger.MinusOne, BigInteger.One, -1);
// BigInteger.MinusOne, Large Negative
VerifyComparison(BigInteger.MinusOne, -1L * ((BigInteger)Int64.MaxValue), 1);
// BigInteger.MinusOne, Small Negative
VerifyComparison(BigInteger.MinusOne, -1L * ((BigInteger)Int16.MaxValue), 1);
// BigInteger.MinusOne, Large Number
VerifyComparison(BigInteger.MinusOne, (BigInteger)Int32.MaxValue + 1, -1);
// BigInteger.MinusOne, Small Number
VerifyComparison(BigInteger.MinusOne, (BigInteger)Int32.MaxValue - 1, -1);
// BigInteger.MinusOne, One Less
VerifyComparison(BigInteger.MinusOne, BigInteger.MinusOne - 1, 1);
// BigInteger.Zero, BigInteger.Zero
VerifyComparison(BigInteger.Zero, BigInteger.Zero, 0);
// BigInteger.Zero, Large Negative
VerifyComparison(BigInteger.Zero, -1L * ((BigInteger)Int32.MaxValue + 1), 1);
// BigInteger.Zero, Small Negative
VerifyComparison(BigInteger.Zero, -1L * ((BigInteger)Int32.MaxValue - 1), 1);
// BigInteger.Zero, Large Number
VerifyComparison(BigInteger.Zero, (BigInteger)Int32.MaxValue + 1, -1);
// BigInteger.Zero, Small Number
VerifyComparison(BigInteger.Zero, (BigInteger)Int32.MaxValue - 1, -1);
// BigInteger.One, BigInteger.One
VerifyComparison(BigInteger.One, BigInteger.One, 0);
// BigInteger.One, BigInteger.MinusOne
VerifyComparison(BigInteger.One, BigInteger.MinusOne, 1);
// BigInteger.One, BigInteger.Zero
VerifyComparison(BigInteger.One, BigInteger.Zero, 1);
// BigInteger.One, Large Negative
VerifyComparison(BigInteger.One, -1 * ((BigInteger)Int32.MaxValue + 1), 1);
// BigInteger.One, Small Negative
VerifyComparison(BigInteger.One, -1 * ((BigInteger)Int32.MaxValue - 1), 1);
// BigInteger.One, Large Number
VerifyComparison(BigInteger.One, (BigInteger)Int32.MaxValue + 1, -1);
// BigInteger.One, Small Number
VerifyComparison(BigInteger.One, (BigInteger)Int32.MaxValue - 1, -1);
//Basic Checks
// BigInteger.MinusOne, (Int32) -1
VerifyComparison(BigInteger.MinusOne, (Int32)(-1), 0);
// BigInteger.Zero, (Int32) 0
VerifyComparison(BigInteger.Zero, (Int32)(0), 0);
// BigInteger.One, 1
VerifyComparison(BigInteger.One, (Int32)(1), 0);
//1 Inputs Around the boundary of UInt32
// -1 * UInt32.MaxValue, -1 * UInt32.MaxValue
VerifyComparison(-1L * (BigInteger)UInt32.MaxValue - 1, -1L * (BigInteger)UInt32.MaxValue - 1, 0);
// -1 * UInt32.MaxValue, -1 * UInt32.MaxValue -1
VerifyComparison(-1L * (BigInteger)UInt32.MaxValue, (-1L * (BigInteger)UInt32.MaxValue) - 1L, 1);
// UInt32.MaxValue, -1 * UInt32.MaxValue
VerifyComparison((BigInteger)UInt32.MaxValue, -1L * (BigInteger)UInt32.MaxValue, 1);
// UInt32.MaxValue, UInt32.MaxValue
VerifyComparison((BigInteger)UInt32.MaxValue, (BigInteger)UInt32.MaxValue, 0);
// UInt32.MaxValue, UInt32.MaxValue + 1
VerifyComparison((BigInteger)UInt32.MaxValue, (BigInteger)UInt32.MaxValue + 1, -1);
// UInt64.MaxValue, UInt64.MaxValue
VerifyComparison((BigInteger)UInt64.MaxValue, (BigInteger)UInt64.MaxValue, 0);
// UInt64.MaxValue + 1, UInt64.MaxValue
VerifyComparison((BigInteger)UInt64.MaxValue + 1, UInt64.MaxValue, 1);
//Other cases
// -1 * Large Bigint, -1 * Large BigInt
VerifyComparison(-1L * ((BigInteger)Int32.MaxValue + 1), -1L * ((BigInteger)Int32.MaxValue + 1), 0);
// Large Bigint, Large Negative BigInt
VerifyComparison((BigInteger)Int32.MaxValue + 1, -1L * ((BigInteger)Int32.MaxValue + 1), 1);
// Large Bigint, UInt32.MaxValue
VerifyComparison((BigInteger)Int64.MaxValue + 1, (BigInteger)UInt32.MaxValue, 1);
// Large Bigint, One More
VerifyComparison((BigInteger)Int32.MaxValue + 1, ((BigInteger)Int32.MaxValue) + 2, -1);
// -1 * Small Bigint, -1 * Small BigInt
VerifyComparison(-1L * ((BigInteger)Int32.MaxValue - 1), -1L * ((BigInteger)Int32.MaxValue - 1), 0);
// Small Bigint, Small Negative BigInt
VerifyComparison((BigInteger)Int32.MaxValue - 1, -1L * ((BigInteger)Int32.MaxValue - 1), 1);
// Small Bigint, UInt32.MaxValue
VerifyComparison((BigInteger)Int32.MaxValue - 1, (BigInteger)UInt32.MaxValue - 1, -1);
// Small Bigint, One More
VerifyComparison((BigInteger)Int32.MaxValue - 2, ((BigInteger)Int32.MaxValue) - 1, -1);
//BigInteger vs. Int32
// One Larger (BigInteger), Int32.MaxValue
VerifyComparison((BigInteger)Int32.MaxValue + 1, Int32.MaxValue, 1);
// Larger BigInteger, Int32.MaxValue
VerifyComparison((BigInteger)UInt64.MaxValue + 1, Int32.MaxValue, 1);
// Smaller BigInteger, Int32.MaxValue
VerifyComparison((BigInteger)Int16.MinValue - 1, Int32.MaxValue, -1);
// One Smaller (BigInteger), Int32.MaxValue
VerifyComparison((BigInteger)Int32.MaxValue - 1, Int32.MaxValue, -1);
// (BigInteger) Int32.MaxValue, Int32.MaxValue
VerifyComparison((BigInteger)Int32.MaxValue, Int32.MaxValue, 0);
//BigInteger vs. UInt32
// One Larger (BigInteger), UInt32.MaxValue
VerifyComparison((BigInteger)UInt32.MaxValue + 1, UInt32.MaxValue, 1);
// Larger BigInteger, UInt32.MaxValue
VerifyComparison((BigInteger)Int64.MaxValue + 1, UInt32.MaxValue, 1);
// Smaller BigInteger, UInt32.MaxValue
VerifyComparison((BigInteger)Int16.MinValue - 1, UInt32.MaxValue, -1);
// One Smaller (BigInteger), UInt32.MaxValue
VerifyComparison((BigInteger)UInt32.MaxValue - 1, UInt32.MaxValue, -1);
// (BigInteger UInt32.MaxValue, UInt32.MaxValue
VerifyComparison((BigInteger)UInt32.MaxValue, UInt32.MaxValue, 0);
//BigInteger vs. UInt64
// One Larger (BigInteger), UInt64.MaxValue
VerifyComparison((BigInteger)UInt64.MaxValue + 1, UInt64.MaxValue, 1);
// Larger BigInteger, UInt64.MaxValue
VerifyComparison((BigInteger)UInt64.MaxValue + 100, UInt64.MaxValue, 1);
// Smaller BigInteger, UInt64.MaxValue
VerifyComparison((BigInteger)Int16.MinValue - 1, UInt64.MaxValue, -1);
VerifyComparison((BigInteger)Int16.MaxValue - 1, UInt64.MaxValue, -1);
VerifyComparison((BigInteger)Int32.MaxValue + 1, UInt64.MaxValue, -1);
// One Smaller (BigInteger), UInt64.MaxValue
VerifyComparison((BigInteger)UInt64.MaxValue - 1, UInt64.MaxValue, -1);
// (BigInteger UInt64.MaxValue, UInt64.MaxValue
VerifyComparison((BigInteger)UInt64.MaxValue, UInt64.MaxValue, 0);
//BigInteger vs. Int64
// One Smaller (BigInteger), Int64.MaxValue
VerifyComparison((BigInteger)Int64.MaxValue - 1, Int64.MaxValue, -1);
// Larger BigInteger, Int64.MaxValue
VerifyComparison((BigInteger)UInt64.MaxValue + 100, Int64.MaxValue, 1);
// Smaller BigInteger, Int32.MaxValue
VerifyComparison((BigInteger)Int16.MinValue - 1, Int64.MaxValue, -1);
// (BigInteger Int64.MaxValue, Int64.MaxValue
VerifyComparison((BigInteger)Int64.MaxValue, Int64.MaxValue, 0);
// One Larger (BigInteger), Int64.MaxValue
VerifyComparison((BigInteger)Int64.MaxValue + 1, Int64.MaxValue, 1);
//1 Random Inputs
// Random BigInteger only differs by sign
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
do
{
byteArray = GetRandomByteArray(random);
}
while (MyBigIntImp.IsZero(byteArray));
BigInteger b2 = new BigInteger(byteArray);
if (b2 > (BigInteger)0)
{
VerifyComparison(b2, -1L * b2, 1);
}
else
{
VerifyComparison(b2, -1L * b2, -1);
}
}
// Random BigInteger, Random BigInteger
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
expectedResult = GetRandomInputForComparison(random, out bigInteger1, out bigInteger2);
VerifyComparison(bigInteger1, bigInteger2, expectedResult);
}
// Random BigInteger
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
byteArray = GetRandomByteArray(random);
isNegative = 0 == random.Next(0, 2);
VerifyComparison(new BigInteger(byteArray), isNegative, new BigInteger(byteArray), isNegative, 0);
}
//1 Identical values constructed multiple ways
// BigInteger.Zero, BigInteger constructed with a byte[] isNegative=true
VerifyComparison(BigInteger.Zero, false, new BigInteger(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 }), true, 0);
// BigInteger.Zero, BigInteger constructed with a byte[] isNegative=false
VerifyComparison(BigInteger.Zero, false, new BigInteger(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 }), false, 0);
// BigInteger.Zero, BigInteger constructed from an Int64
VerifyComparison(BigInteger.Zero, 0L, 0);
// BigInteger.Zero, BigInteger constructed from a Double
VerifyComparison(BigInteger.Zero, (BigInteger)0d, 0);
// BigInteger.Zero, BigInteger constructed from a Decimal
VerifyComparison(BigInteger.Zero, (BigInteger)0, 0);
// BigInteger.Zero, BigInteger constructed with Addition
byteArray = GetRandomByteArray(random);
isNegative = 0 == random.Next(0, 2);
VerifyComparison(BigInteger.Zero, false, new BigInteger(byteArray) + (-1 * new BigInteger(byteArray)), isNegative, 0);
// BigInteger.Zero, BigInteger constructed with Subtraction
byteArray = GetRandomByteArray(random);
isNegative = 0 == random.Next(0, 2);
VerifyComparison(BigInteger.Zero, false, new BigInteger(byteArray) - new BigInteger(byteArray), isNegative, 0);
// BigInteger.Zero, BigInteger constructed with Multiplication
byteArray = GetRandomByteArray(random);
isNegative = 0 == random.Next(0, 2);
VerifyComparison(BigInteger.Zero, false, 0 * new BigInteger(byteArray), isNegative, 0);
// BigInteger.Zero, BigInteger constructed with Division
do
{
byteArray = GetRandomByteArray(random);
}
while (MyBigIntImp.IsZero(byteArray));
isNegative = 0 == random.Next(0, 2);
VerifyComparison(BigInteger.Zero, false, 0 / new BigInteger(byteArray), isNegative, 0);
// BigInteger.One, BigInteger constructed with a byte[]
VerifyComparison(BigInteger.One, false, new BigInteger(new byte[] { 1, 0, 0, 0, 0, 0, 0, 0 }), false, 0);
// BigInteger.One, BigInteger constructed from an Int64
VerifyComparison(BigInteger.One, 1L, 0);
// BigInteger.One, BigInteger constructed from a Double
VerifyComparison(BigInteger.One, (BigInteger)1d, 0);
// BigInteger.One, BigInteger constructed from a Decimal
VerifyComparison(BigInteger.One, (BigInteger)1, 0);
// BigInteger.One, BigInteger constructed with Addition
byteArray = GetRandomByteArray(random);
isNegative = 0 == random.Next(0, 2);
VerifyComparison(BigInteger.One, false, (((BigInteger)(-1)) * new BigInteger(byteArray)) + (new BigInteger(byteArray)) + 1, false, 0);
// BigInteger.One, BigInteger constructed with Subtraction
byteArray = GetRandomByteArray(random);
isNegative = 0 == random.Next(0, 2);
BigInteger b = new BigInteger(byteArray);
if (b > (BigInteger)0)
{
VerifyComparison(BigInteger.One, false, (b + 1) - (b), false, 0);
}
else
{
b = -1L * b;
VerifyComparison(BigInteger.One, false, (b + 1) - (b), false, 0);
b = -1L * b;
}
// BigInteger.One, BigInteger constructed with Multiplication
byteArray = GetRandomByteArray(random);
isNegative = 0 == random.Next(0, 2);
VerifyComparison(BigInteger.One, (BigInteger)1 * (BigInteger)1, 0);
// BigInteger.One, BigInteger constructed with Division
do
{
byteArray = GetRandomByteArray(random);
}
while (MyBigIntImp.IsZero(byteArray));
BigInteger b1 = new BigInteger(byteArray);
VerifyComparison(BigInteger.One, false, b1 / b1, false, 0);
}
private static void RunNegativeTests(Random random)
{
// BigInteger.Zero, 0
Assert.Equal(false, BigInteger.Zero.Equals((Object)0));
// BigInteger.Zero, null
Assert.Equal(false, BigInteger.Zero.Equals((Object)null));
// BigInteger.Zero, string
Assert.Equal(false, BigInteger.Zero.Equals((Object)"0"));
}
public static void IComparable_Invalid(string paramName)
{
IComparable comparable = new BigInteger();
Assert.Equal(1, comparable.CompareTo(null));
AssertExtensions.Throws<ArgumentException>(paramName, () => comparable.CompareTo(0)); // Obj is not a BigInteger
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Netcoreapp | TargetFrameworkMonikers.Uap | TargetFrameworkMonikers.UapAot)] // Missing Exception.ParamName fixed in .NETCore
public static void IComparable_Invalid_net46()
{
IComparable_Invalid(null);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public static void IComparable_Invalid_netcore()
{
IComparable_Invalid("obj");
}
private static void VerifyComparison(BigInteger x, BigInteger y, int expectedResult)
{
bool expectedEquals = 0 == expectedResult;
bool expectedLessThan = expectedResult < 0;
bool expectedGreaterThan = expectedResult > 0;
Assert.Equal(expectedEquals, x == y);
Assert.Equal(expectedEquals, y == x);
Assert.Equal(!expectedEquals, x != y);
Assert.Equal(!expectedEquals, y != x);
Assert.Equal(expectedEquals, x.Equals(y));
Assert.Equal(expectedEquals, y.Equals(x));
Assert.Equal(expectedEquals, x.Equals((Object)y));
Assert.Equal(expectedEquals, y.Equals((Object)x));
VerifyCompareResult(expectedResult, x.CompareTo(y), "x.CompareTo(y)");
VerifyCompareResult(-expectedResult, y.CompareTo(x), "y.CompareTo(x)");
IComparable comparableX = x;
IComparable comparableY = y;
VerifyCompareResult(expectedResult, comparableX.CompareTo(y), "comparableX.CompareTo(y)");
VerifyCompareResult(-expectedResult, comparableY.CompareTo(x), "comparableY.CompareTo(x)");
VerifyCompareResult(expectedResult, BigInteger.Compare(x, y), "Compare(x,y)");
VerifyCompareResult(-expectedResult, BigInteger.Compare(y, x), "Compare(y,x)");
if (expectedEquals)
{
Assert.Equal(x.GetHashCode(), y.GetHashCode());
Assert.Equal(x.ToString(), y.ToString());
}
Assert.Equal(x.GetHashCode(), x.GetHashCode());
Assert.Equal(y.GetHashCode(), y.GetHashCode());
Assert.Equal(expectedLessThan, x < y);
Assert.Equal(expectedGreaterThan, y < x);
Assert.Equal(expectedGreaterThan, x > y);
Assert.Equal(expectedLessThan, y > x);
Assert.Equal(expectedLessThan || expectedEquals, x <= y);
Assert.Equal(expectedGreaterThan || expectedEquals, y <= x);
Assert.Equal(expectedGreaterThan || expectedEquals, x >= y);
Assert.Equal(expectedLessThan || expectedEquals, y >= x);
}
private static void VerifyComparison(BigInteger x, Int32 y, int expectedResult)
{
bool expectedEquals = 0 == expectedResult;
bool expectedLessThan = expectedResult < 0;
bool expectedGreaterThan = expectedResult > 0;
Assert.Equal(expectedEquals, x == y);
Assert.Equal(expectedEquals, y == x);
Assert.Equal(!expectedEquals, x != y);
Assert.Equal(!expectedEquals, y != x);
Assert.Equal(expectedEquals, x.Equals(y));
VerifyCompareResult(expectedResult, x.CompareTo(y), "x.CompareTo(y)");
if (expectedEquals)
{
Assert.Equal(x.GetHashCode(), ((BigInteger)y).GetHashCode());
Assert.Equal(x.ToString(), ((BigInteger)y).ToString());
}
Assert.Equal(x.GetHashCode(), x.GetHashCode());
Assert.Equal(((BigInteger)y).GetHashCode(), ((BigInteger)y).GetHashCode());
Assert.Equal(expectedLessThan, x < y);
Assert.Equal(expectedGreaterThan, y < x);
Assert.Equal(expectedGreaterThan, x > y);
Assert.Equal(expectedLessThan, y > x);
Assert.Equal(expectedLessThan || expectedEquals, x <= y);
Assert.Equal(expectedGreaterThan || expectedEquals, y <= x);
Assert.Equal(expectedGreaterThan || expectedEquals, x >= y);
Assert.Equal(expectedLessThan || expectedEquals, y >= x);
}
private static void VerifyComparison(BigInteger x, UInt32 y, int expectedResult)
{
bool expectedEquals = 0 == expectedResult;
bool expectedLessThan = expectedResult < 0;
bool expectedGreaterThan = expectedResult > 0;
Assert.Equal(expectedEquals, x == y);
Assert.Equal(expectedEquals, y == x);
Assert.Equal(!expectedEquals, x != y);
Assert.Equal(!expectedEquals, y != x);
Assert.Equal(expectedEquals, x.Equals(y));
VerifyCompareResult(expectedResult, x.CompareTo(y), "x.CompareTo(y)");
if (expectedEquals)
{
Assert.Equal(x.GetHashCode(), ((BigInteger)y).GetHashCode());
Assert.Equal(x.ToString(), ((BigInteger)y).ToString());
}
Assert.Equal(x.GetHashCode(), x.GetHashCode());
Assert.Equal(((BigInteger)y).GetHashCode(), ((BigInteger)y).GetHashCode());
Assert.Equal(expectedLessThan, x < y);
Assert.Equal(expectedGreaterThan, y < x);
Assert.Equal(expectedGreaterThan, x > y);
Assert.Equal(expectedLessThan, y > x);
Assert.Equal(expectedLessThan || expectedEquals, x <= y);
Assert.Equal(expectedGreaterThan || expectedEquals, y <= x);
Assert.Equal(expectedGreaterThan || expectedEquals, x >= y);
Assert.Equal(expectedLessThan || expectedEquals, y >= x);
}
private static void VerifyComparison(BigInteger x, Int64 y, int expectedResult)
{
bool expectedEquals = 0 == expectedResult;
bool expectedLessThan = expectedResult < 0;
bool expectedGreaterThan = expectedResult > 0;
Assert.Equal(expectedEquals, x == y);
Assert.Equal(expectedEquals, y == x);
Assert.Equal(!expectedEquals, x != y);
Assert.Equal(!expectedEquals, y != x);
Assert.Equal(expectedEquals, x.Equals(y));
VerifyCompareResult(expectedResult, x.CompareTo(y), "x.CompareTo(y)");
if (expectedEquals)
{
Assert.Equal(x.GetHashCode(), ((BigInteger)y).GetHashCode());
Assert.Equal(x.ToString(), ((BigInteger)y).ToString());
}
Assert.Equal(x.GetHashCode(), x.GetHashCode());
Assert.Equal(((BigInteger)y).GetHashCode(), ((BigInteger)y).GetHashCode());
Assert.Equal(expectedLessThan, x < y);
Assert.Equal(expectedGreaterThan, y < x);
Assert.Equal(expectedGreaterThan, x > y);
Assert.Equal(expectedLessThan, y > x);
Assert.Equal(expectedLessThan || expectedEquals, x <= y);
Assert.Equal(expectedGreaterThan || expectedEquals, y <= x);
Assert.Equal(expectedGreaterThan || expectedEquals, x >= y);
Assert.Equal(expectedLessThan || expectedEquals, y >= x);
}
private static void VerifyComparison(BigInteger x, UInt64 y, int expectedResult)
{
bool expectedEquals = 0 == expectedResult;
bool expectedLessThan = expectedResult < 0;
bool expectedGreaterThan = expectedResult > 0;
Assert.Equal(expectedEquals, x == y);
Assert.Equal(expectedEquals, y == x);
Assert.Equal(!expectedEquals, x != y);
Assert.Equal(!expectedEquals, y != x);
Assert.Equal(expectedEquals, x.Equals(y));
VerifyCompareResult(expectedResult, x.CompareTo(y), "x.CompareTo(y)");
if (expectedEquals)
{
Assert.Equal(x.GetHashCode(), ((BigInteger)y).GetHashCode());
Assert.Equal(x.ToString(), ((BigInteger)y).ToString());
}
else
{
Assert.NotEqual(x.GetHashCode(), ((BigInteger)y).GetHashCode());
Assert.NotEqual(x.ToString(), ((BigInteger)y).ToString());
}
Assert.Equal(x.GetHashCode(), x.GetHashCode());
Assert.Equal(((BigInteger)y).GetHashCode(), ((BigInteger)y).GetHashCode());
Assert.Equal(expectedLessThan, x < y);
Assert.Equal(expectedGreaterThan, y < x);
Assert.Equal(expectedGreaterThan, x > y);
Assert.Equal(expectedLessThan, y > x);
Assert.Equal(expectedLessThan || expectedEquals, x <= y);
Assert.Equal(expectedGreaterThan || expectedEquals, y <= x);
Assert.Equal(expectedGreaterThan || expectedEquals, x >= y);
Assert.Equal(expectedLessThan || expectedEquals, y >= x);
}
private static void VerifyComparison(BigInteger x, bool IsXNegative, BigInteger y, bool IsYNegative, int expectedResult)
{
bool expectedEquals = 0 == expectedResult;
bool expectedLessThan = expectedResult < 0;
bool expectedGreaterThan = expectedResult > 0;
if (IsXNegative == true)
{
x = x * -1;
}
if (IsYNegative == true)
{
y = y * -1;
}
Assert.Equal(expectedEquals, x == y);
Assert.Equal(expectedEquals, y == x);
Assert.Equal(!expectedEquals, x != y);
Assert.Equal(!expectedEquals, y != x);
Assert.Equal(expectedEquals, x.Equals(y));
Assert.Equal(expectedEquals, y.Equals(x));
Assert.Equal(expectedEquals, x.Equals((Object)y));
Assert.Equal(expectedEquals, y.Equals((Object)x));
VerifyCompareResult(expectedResult, x.CompareTo(y), "x.CompareTo(y)");
VerifyCompareResult(-expectedResult, y.CompareTo(x), "y.CompareTo(x)");
if (expectedEquals)
{
Assert.Equal(x.GetHashCode(), y.GetHashCode());
Assert.Equal(x.ToString(), y.ToString());
}
else
{
Assert.NotEqual(x.GetHashCode(), y.GetHashCode());
Assert.NotEqual(x.ToString(), y.ToString());
}
Assert.Equal(x.GetHashCode(), x.GetHashCode());
Assert.Equal(y.GetHashCode(), y.GetHashCode());
Assert.Equal(expectedLessThan, x < y);
Assert.Equal(expectedGreaterThan, y < x);
Assert.Equal(expectedGreaterThan, x > y);
Assert.Equal(expectedLessThan, y > x);
Assert.Equal(expectedLessThan || expectedEquals, x <= y);
Assert.Equal(expectedGreaterThan || expectedEquals, y <= x);
Assert.Equal(expectedGreaterThan || expectedEquals, x >= y);
Assert.Equal(expectedLessThan || expectedEquals, y >= x);
}
private static void VerifyCompareResult(int expected, int actual, string message)
{
if (0 == expected)
{
Assert.Equal(expected, actual);
}
else if (0 > expected)
{
Assert.InRange(actual, int.MinValue, -1);
}
else if (0 < expected)
{
Assert.InRange(actual, 1, int.MaxValue);
}
}
private static int GetRandomInputForComparison(Random random, out BigInteger bigInteger1, out BigInteger bigInteger2)
{
byte[] byteArray1, byteArray2;
bool sameSize = 0 == random.Next(0, 2);
if (sameSize)
{
int size = random.Next(0, 1024);
byteArray1 = GetRandomByteArray(random, size);
byteArray2 = GetRandomByteArray(random, size);
}
else
{
byteArray1 = GetRandomByteArray(random);
byteArray2 = GetRandomByteArray(random);
}
bigInteger1 = new BigInteger(byteArray1);
bigInteger2 = new BigInteger(byteArray2);
if (bigInteger1 > 0 && bigInteger2 > 0)
{
if (byteArray1.Length < byteArray2.Length)
{
for (int i = byteArray2.Length - 1; byteArray1.Length <= i; --i)
{
if (0 != byteArray2[i])
{
return -1;
}
}
}
else if (byteArray1.Length > byteArray2.Length)
{
for (int i = byteArray1.Length - 1; byteArray2.Length <= i; --i)
{
if (0 != byteArray1[i])
{
return 1;
}
}
}
}
else if ((bigInteger1 < 0 && bigInteger2 > 0) || (bigInteger1 == 0 && bigInteger2 > 0) || (bigInteger1 < 0 && bigInteger2 == 0))
{
return -1;
}
else if ((bigInteger1 > 0 && bigInteger2 < 0) || (bigInteger1 == 0 && bigInteger2 < 0) || (bigInteger1 > 0 && bigInteger2 == 0))
{
return 1;
}
else if (bigInteger1 != 0 && bigInteger2 != 0)
{
if (byteArray1.Length < byteArray2.Length)
{
for (int i = byteArray2.Length - 1; byteArray1.Length <= i; --i)
{
if (0xFF != byteArray2[i])
{
return 1;
}
}
}
else if (byteArray1.Length > byteArray2.Length)
{
for (int i = byteArray1.Length - 1; byteArray2.Length <= i; --i)
{
if (0xFF != byteArray1[i])
{
return -1;
}
}
}
}
for (int i = Math.Min(byteArray1.Length, byteArray2.Length) - 1; 0 <= i; --i)
{
if (byteArray1[i] > byteArray2[i])
{
return 1;
}
else if (byteArray1[i] < byteArray2[i])
{
return -1;
}
}
return 0;
}
private static byte[] GetRandomByteArray(Random random)
{
return GetRandomByteArray(random, random.Next(0, 1024));
}
private static byte[] GetRandomByteArray(Random random, int size)
{
return MyBigIntImp.GetRandomByteArray(random, size);
}
}
}
| |
using System;
using System.Linq;
using Signum.Entities.Basics;
using System.Linq.Expressions;
using Signum.Utilities;
using Signum.Entities.DynamicQuery;
using System.ComponentModel;
using System.Reflection;
using Signum.Entities.UserAssets;
using Signum.Entities.Templating;
using System.Xml.Linq;
using Signum.Entities.UserQueries;
using Signum.Entities;
namespace Signum.Entities.Mailing
{
[Serializable, EntityKind(EntityKind.Main, EntityData.Master)]
public class EmailTemplateEntity : Entity, IUserAssetEntity
{
public EmailTemplateEntity()
{
RebindEvents();
}
[UniqueIndex]
public Guid Guid { get; set; } = Guid.NewGuid();
public EmailTemplateEntity(object queryName) : this()
{
this.queryName = queryName;
}
[Ignore]
internal object queryName;
[UniqueIndex]
[StringLengthValidator(Min = 3, Max = 100)]
public string Name { get; set; }
public bool EditableMessage { get; set; } = true;
public bool DisableAuthorization { get; set; }
public QueryEntity Query { get; set; }
public EmailModelEntity? Model { get; set; }
public EmailTemplateFromEmbedded? From { get; set; }
[NoRepeatValidator]
public MList<EmailTemplateRecipientEmbedded> Recipients { get; set; } = new MList<EmailTemplateRecipientEmbedded>();
public bool GroupResults { get; set; }
[PreserveOrder]
public MList<QueryFilterEmbedded> Filters { get; set; } = new MList<QueryFilterEmbedded>();
[PreserveOrder]
public MList<QueryOrderEmbedded> Orders { get; set; } = new MList<QueryOrderEmbedded>();
[PreserveOrder]
[NoRepeatValidator, ImplementedBy(typeof(ImageAttachmentEntity)), NotifyChildProperty]
public MList<IAttachmentGeneratorEntity> Attachments { get; set; } = new MList<IAttachmentGeneratorEntity>();
public Lite<EmailMasterTemplateEntity>? MasterTemplate { get; set; }
public bool IsBodyHtml { get; set; } = true;
[NotifyCollectionChanged, NotifyChildProperty]
public MList<EmailTemplateMessageEmbedded> Messages { get; set; } = new MList<EmailTemplateMessageEmbedded>();
[NotifyChildProperty]
public TemplateApplicableEval? Applicable { get; set; }
protected override string? PropertyValidation(System.Reflection.PropertyInfo pi)
{
if (pi.Name == nameof(Messages))
{
if (Messages == null || !Messages.Any())
return EmailTemplateMessage.ThereAreNoMessagesForTheTemplate.NiceToString();
if (Messages.GroupCount(m => m.CultureInfo).Any(c => c.Value > 1))
return EmailTemplateMessage.TheresMoreThanOneMessageForTheSameLanguage.NiceToString();
}
return base.PropertyValidation(pi);
}
[AutoExpressionField]
public override string ToString() => As.Expression(() => Name);
internal void ParseData(QueryDescription description)
{
var canAggregate = this.GroupResults ? SubTokensOptions.CanAggregate : 0;
foreach (var r in Recipients.Where(r => r.Token != null))
r.Token!.ParseData(this, description, SubTokensOptions.CanElement);
if (From != null && From.Token != null)
From.Token.ParseData(this, description, SubTokensOptions.CanElement);
foreach (var f in Filters)
f.ParseData(this, description, SubTokensOptions.CanAnyAll | SubTokensOptions.CanElement | canAggregate);
foreach (var o in Orders)
o.ParseData(this, description, SubTokensOptions.CanElement | canAggregate);
}
public bool IsApplicable(Entity? entity)
{
if (Applicable == null)
return true;
try
{
return Applicable.Algorithm!.ApplicableUntyped(entity);
}
catch (Exception e)
{
throw new ApplicationException($"Error evaluating Applicable for EmailTemplate '{Name}' with entity '{entity}': " + e.Message, e);
}
}
public XElement ToXml(IToXmlContext ctx)
{
if(this.Attachments != null && this.Attachments.Count() > 0)
{
throw new NotImplementedException("Attachments are not yet exportable");
}
return new XElement("EmailTemplate",
new XAttribute("Name", Name),
new XAttribute("Guid", Guid),
new XAttribute("DisableAuthorization", DisableAuthorization),
new XAttribute("Query", Query.Key),
new XAttribute("EditableMessage", EditableMessage),
Model == null ? null! /*FIX all null! -> null*/ : new XAttribute("Model", Model.FullClassName),
MasterTemplate == null ? null! : new XAttribute("MasterTemplate", ctx.Include(MasterTemplate)),
new XAttribute("GroupResults", GroupResults),
Filters.IsNullOrEmpty() ? null! : new XElement("Filters", Filters.Select(f => f.ToXml(ctx)).ToList()),
Orders.IsNullOrEmpty() ? null! : new XElement("Orders", Orders.Select(o => o.ToXml(ctx)).ToList()),
new XAttribute("IsBodyHtml", IsBodyHtml),
From == null ? null! : new XElement("From",
From.DisplayName != null ? new XAttribute("DisplayName", From.DisplayName) : null!,
From.EmailAddress != null ? new XAttribute("EmailAddress", From.EmailAddress) : null!,
From.Token != null ? new XAttribute("Token", From.Token.Token.FullKey()) : null!,
new XAttribute("WhenMany", From.WhenMany),
new XAttribute("WhenNone", From.WhenNone)
),
new XElement("Recipients", Recipients.Select(rec =>
new XElement("Recipient",
rec.DisplayName.HasText()? new XAttribute("DisplayName", rec.DisplayName) : null!,
rec.EmailAddress.HasText()? new XAttribute("EmailAddress", rec.EmailAddress) : null!,
new XAttribute("Kind", rec.Kind),
rec.Token != null ? new XAttribute("Token", rec.Token?.Token.FullKey()!) : null!,
new XAttribute("WhenMany", rec.WhenMany),
new XAttribute("WhenNone", rec.WhenNone)
)
)),
new XElement("Messages", Messages.Select(x =>
new XElement("Message",
new XAttribute("CultureInfo", x.CultureInfo.Name),
new XAttribute("Subject", x.Subject),
new XCData(x.Text)
))),
this.Applicable?.Let(app => new XElement("Applicable", new XCData(app.Script)))!
);
}
public void FromXml(XElement element, IFromXmlContext ctx)
{
Guid = Guid.Parse(element.Attribute("Guid")!.Value);
Name = element.Attribute("Name")!.Value;
DisableAuthorization = element.Attribute("DisableAuthorization")?.Let(a => bool.Parse(a.Value)) ?? false;
Query = ctx.GetQuery(element.Attribute("Query")!.Value);
EditableMessage = bool.Parse(element.Attribute("EditableMessage")!.Value);
Model = element.Attribute("Model")?.Let(at => ctx.GetEmailModel(at.Value));
MasterTemplate = element.Attribute("MasterTemplate")?.Let(a=>(Lite<EmailMasterTemplateEntity>)ctx.GetEntity(Guid.Parse(a.Value)).ToLite());
GroupResults = bool.Parse(element.Attribute("GroupResults")!.Value);
Filters.Synchronize(element.Element("Filters")?.Elements().ToList(), (f, x) => f.FromXml(x, ctx));
Orders.Synchronize(element.Element("Orders")?.Elements().ToList(), (o, x) => o.FromXml(x, ctx));
IsBodyHtml = bool.Parse(element.Attribute("IsBodyHtml")!.Value);
From = element.Element("From")?.Let(from => new EmailTemplateFromEmbedded
{
DisplayName = from.Attribute("DisplayName")?.Value,
EmailAddress = from.Attribute("EmailAddress")?.Value,
Token = from.Attribute("Token")?.Let(t => new QueryTokenEmbedded(t.Value)),
WhenMany = from.Attribute("WhenMany")?.Value.ToEnum<WhenManyFromBehaviour>() ?? WhenManyFromBehaviour.FistResult,
WhenNone = from.Attribute("WhenNone")?.Value.ToEnum<WhenNoneFromBehaviour>() ?? WhenNoneFromBehaviour.NoMessage,
});
Recipients = element.Element("Recipients")!.Elements("Recipient").Select(rep => new EmailTemplateRecipientEmbedded
{
DisplayName = rep.Attribute("DisplayName")?.Value,
EmailAddress = rep.Attribute("EmailAddress")?.Value,
Kind = rep.Attribute("Kind")!.Value.ToEnum<EmailRecipientKind>(),
Token = rep.Attribute("Token")?.Let(a => new QueryTokenEmbedded(a.Value)),
WhenMany = rep.Attribute("WhenMany")?.Value?.ToEnum<WhenManyRecipiensBehaviour>() ?? WhenManyRecipiensBehaviour.KeepOneMessageWithManyRecipients,
WhenNone = rep.Attribute("WhenNone")?.Value?.ToEnum<WhenNoneRecipientsBehaviour>() ?? WhenNoneRecipientsBehaviour.ThrowException,
}).ToMList();
Messages = element.Element("Messages")!.Elements("Message").Select(elem => new EmailTemplateMessageEmbedded(ctx.GetCultureInfoEntity(elem.Attribute("CultureInfo")!.Value))
{
Subject = elem.Attribute("Subject")!.Value,
Text = elem.Value
}).ToMList();
Applicable = element.Element("Applicable")?.Let(app => new TemplateApplicableEval { Script = app.Value});
ParseData(ctx.GetQueryDescription(Query));
}
}
[Serializable]
public abstract class EmailTemplateAddressEmbedded : EmbeddedEntity
{
public string? EmailAddress { get; set; }
public string? DisplayName { get; set; }
public QueryTokenEmbedded? Token { get; set; }
public override string ToString()
{
return "{0} <{1}>".FormatWith(DisplayName, EmailAddress);
}
protected override string? PropertyValidation(PropertyInfo pi)
{
if (pi.Name == nameof(Token))
{
if (Token == null && EmailAddress.IsNullOrEmpty())
return EmailTemplateMessage.TokenOrEmailAddressMustBeSet.NiceToString();
if (Token != null && !EmailAddress.IsNullOrEmpty())
return EmailTemplateMessage.TokenAndEmailAddressCanNotBeSetAtTheSameTime.NiceToString();
if (Token != null && Token.Token.Type != typeof(EmailOwnerData))
return EmailTemplateMessage.TokenMustBeA0.NiceToString(typeof(EmailOwnerData).NiceName());
}
return null;
}
}
[Serializable]
public class EmailTemplateRecipientEmbedded : EmailTemplateAddressEmbedded
{
public EmailRecipientKind Kind { get; set; }
public WhenNoneRecipientsBehaviour WhenNone { get; set; }
public WhenManyRecipiensBehaviour WhenMany { get; set; }
public override string ToString()
{
return "{0} {1} <{2}>".FormatWith(Kind.NiceToString(), DisplayName, EmailAddress);
}
}
public enum WhenNoneRecipientsBehaviour
{
ThrowException,
NoMessage,
NoRecipients
}
public enum WhenManyRecipiensBehaviour
{
SplitMessages,
KeepOneMessageWithManyRecipients,
}
[Serializable]
public class EmailTemplateFromEmbedded : EmailTemplateAddressEmbedded
{
public WhenNoneFromBehaviour WhenNone { get; set; }
public WhenManyFromBehaviour WhenMany { get; set; }
public Guid? AzureUserId { get; set; }
}
public enum WhenNoneFromBehaviour
{
ThrowException,
NoMessage,
DefaultFrom
}
public enum WhenManyFromBehaviour
{
SplitMessages,
FistResult,
}
[Serializable]
public class EmailTemplateMessageEmbedded : EmbeddedEntity
{
private EmailTemplateMessageEmbedded() { }
public EmailTemplateMessageEmbedded(CultureInfoEntity culture)
{
this.CultureInfo = culture;
}
public CultureInfoEntity CultureInfo { get; set; }
[DbType(Size = int.MaxValue)]
string text;
[StringLengthValidator(MultiLine=true)]
public string Text
{
get { return text; }
set
{
if (Set(ref text, value))
TextParsedNode = null;
}
}
[Ignore]
internal object? TextParsedNode;
string subject;
[StringLengthValidator(Min = 3, Max = 200)]
public string Subject
{
get { return subject; }
set
{
if (Set(ref subject, value))
SubjectParsedNode = null;
}
}
[Ignore]
internal object? SubjectParsedNode;
public override string ToString()
{
return CultureInfo?.ToString() ?? EmailTemplateMessage.NewCulture.NiceToString();
}
}
public interface IAttachmentGeneratorEntity : IEntity
{
}
[AutoInit]
public static class EmailTemplateOperation
{
public static ConstructSymbol<EmailTemplateEntity>.From<EmailModelEntity> CreateEmailTemplateFromModel;
public static ConstructSymbol<EmailTemplateEntity>.Simple Create;
public static ExecuteSymbol<EmailTemplateEntity> Save;
public static DeleteSymbol<EmailTemplateEntity> Delete;
}
public enum EmailTemplateMessage
{
[Description("End date must be higher than start date")]
EndDateMustBeHigherThanStartDate,
[Description("There are no messages for the template")]
ThereAreNoMessagesForTheTemplate,
[Description("There must be a message for {0}")]
ThereMustBeAMessageFor0,
[Description("There's more than one message for the same language")]
TheresMoreThanOneMessageForTheSameLanguage,
[Description("The text must contain {0} indicating replacement point")]
TheTextMustContain0IndicatingReplacementPoint,
[Description("Impossible to access {0} because the template has no {1}")]
ImpossibleToAccess0BecauseTheTemplateHAsNo1,
NewCulture,
TokenOrEmailAddressMustBeSet,
TokenAndEmailAddressCanNotBeSetAtTheSameTime,
[Description("Token must be a {0}")]
TokenMustBeA0,
ShowPreview,
HidePreview
}
public enum EmailTemplateViewMessage
{
[Description("Insert message content")]
InsertMessageContent,
[Description("Insert")]
Insert,
[Description("Language")]
Language
}
[InTypeScript(true)]
public enum EmailTemplateVisibleOn
{
Single = 1,
Multiple = 2,
Query = 4
}
}
| |
//
// IOChannel.cs
//
// Author:
// Larry Ewing <[email protected]>
//
// Copyright (C) 2006 Novell, Inc.
// Copyright (C) 2006 Larry Ewing
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
using System.Runtime.InteropServices;
namespace FSpot.Imaging
{
[Flags]
public enum IOFlags
{
Append = 1,
Nonblock = 1 << 1,
Readable = 1 << 2,
Writable = 1 << 3,
Seekable = 1 << 4
}
public enum IOStatus
{
Error,
Normal,
Eof,
Again
}
public enum IOCondition
{
// FIXME these are system dependent and I'm hardcoding them because I don't
// want to write glue today. If you are debugging image loading and get
// to this point and find that that your problem is my fault, well... we all
// have bad days.
In = 1,
Out = 4,
Priority = 2,
Error = 8,
HungUp = 16,
Invalid = 32
}
public class DataReadEventArgs : EventArgs
{
public bool Continue;
public IOCondition Condition { get; private set; }
public DataReadEventArgs (IOCondition condition)
{
Condition = condition;
Continue = true;
}
}
public class IOChannel : Stream
{
HandleRef handle;
private delegate bool IOFunc (IntPtr sourceChannel, IOCondition cond, IntPtr data);
[DllImport("libglib-2.0-0.dll")]
static extern IOFlags g_io_channel_get_flags (HandleRef channel);
public override bool CanRead {
get {
IOFlags flags = g_io_channel_get_flags (handle);
return (flags & IOFlags.Readable) == IOFlags.Readable;
}
}
public override bool CanSeek {
get {
#if NOTDONE
IOFlags flags = g_io_channel_get_flags (handle);
return (flags & IOFlags.Seekable) == IOFlags.Seekable;
#else
return false;
#endif
}
}
public override bool CanWrite {
get {
IOFlags flags = g_io_channel_get_flags (handle);
return (flags & IOFlags.Writable) == IOFlags.Writable;
}
}
public override long Length {
get {
throw new NotSupportedException ("IOChannel doesn't support seeking");
}
}
public override long Position {
get {
throw new NotSupportedException ("IOChannel doesn't support seeking");
}
set {
throw new NotSupportedException ("IOChannel doesn't support seeking");
}
}
[DllImport("libglib-2.0-0.dll")]
static extern IntPtr g_io_channel_unix_new (int fd);
[DllImport("libglib-2.0-0.dll")]
static extern IOStatus g_io_channel_set_encoding (HandleRef handle, string encoding, out IntPtr error);
public IOChannel (int fd)
{
IntPtr raw = g_io_channel_unix_new (fd);
handle = new HandleRef (this, raw);
IntPtr error;
g_io_channel_set_encoding (handle, null, out error);
if (error != IntPtr.Zero)
throw new GLib.GException (error);
}
[DllImport("libglib-2.0-0.dll")]
static extern IOStatus g_io_channel_flush (HandleRef channel, out IntPtr error);
public override void Flush ()
{
IOStatus status;
IntPtr error;
status = g_io_channel_flush (handle, out error);
if (status != IOStatus.Normal && status != IOStatus.Eof)
Hyena.Log.DebugFormat ("IOChannel status = {0}", status);
if (error != IntPtr.Zero)
throw new GLib.GException (error);
}
[DllImport("libglib-2.0-0.dll")]
static extern unsafe IOStatus g_io_channel_write_chars (HandleRef channel, byte *data, int count, out int bytesWritten, out IntPtr error);
public override void Write (byte [] buffer, int offset, int count)
{
IOStatus status = IOStatus.Again;
IntPtr error;
int written;
if (buffer == null)
throw new ArgumentNullException ();
unsafe {
while (status == IOStatus.Again && count > 0) {
fixed (byte *data = &buffer [offset]) {
status = g_io_channel_write_chars (handle, data, count, out written, out error);
}
if (error != IntPtr.Zero)
throw new GLib.GException (error);
offset += written;
count -= written;
}
}
}
[DllImport("libglib-2.0-0.dll")]
static unsafe extern IOStatus g_io_channel_read_chars (HandleRef channel, byte *data, int count, out int bytesRead, out IntPtr error);
public override int Read (byte [] buffer, int offset, int count)
{
int read;
IOStatus status;
IntPtr error;
unsafe {
fixed (byte *data = &buffer[offset]) {
status = g_io_channel_read_chars (handle, data, count, out read, out error);
}
}
if (status != IOStatus.Normal && status != IOStatus.Eof)
Hyena.Log.DebugFormat ("IOChannel status = {0}", status);
if (error != IntPtr.Zero)
throw new GLib.GException (error);
return read;
}
[DllImport("libglib-2.0-0.dll")]
static extern uint g_io_add_watch (HandleRef handle, IOCondition cond, IOFunc func, IntPtr data);
uint AddWatch (IOCondition ioCondition, IOFunc ioFunc)
{
return g_io_add_watch (handle, ioCondition, ioFunc, IntPtr.Zero);
}
// FIXME this should hold more than one source in a table
// but I am lazy
uint data_ready_source;
EventHandler<DataReadEventArgs> data_ready;
IOFunc func;
public event EventHandler<DataReadEventArgs> DataReady {
add {
data_ready += value;
func = new IOFunc (DataReadyHandler);
data_ready_source = AddWatch (IOCondition.In, func);
}
remove {
GLib.Source.Remove (data_ready_source);
data_ready_source = 0;
data_ready -= value;
}
}
bool DataReadyHandler (IntPtr channel, IOCondition condition, IntPtr data)
{
var args = new DataReadEventArgs (condition);
if (data_ready != null)
data_ready (this, args);
return args.Continue;
}
public override void SetLength (long value)
{
throw new NotSupportedException ();
}
enum SeekType {
Current,
Set,
End
}
public override long Seek (long offset, SeekOrigin origin)
{
throw new NotSupportedException ();
}
[DllImport("libglib-2.0-0.dll")]
static extern IOStatus g_io_channel_shutdown (HandleRef handle, bool flush, out IntPtr error);
[DllImport("libglib-2.0-0.dll")]
static extern void g_io_channel_unref (HandleRef handle);
public override void Close ()
{
IntPtr error;
if (data_ready_source != 0)
GLib.Source.Remove (data_ready_source);
data_ready_source = 0;
g_io_channel_shutdown (handle, false, out error);
base.Close ();
if (error != IntPtr.Zero)
throw new GLib.GException (error);
}
~IOChannel ()
{
if (data_ready_source != 0)
GLib.Source.Remove (data_ready_source);
data_ready_source = 0;
g_io_channel_unref (handle);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using CallbackReceiver.Areas.HelpPage.ModelDescriptions;
using CallbackReceiver.Areas.HelpPage.Models;
namespace CallbackReceiver.Areas.HelpPage
{
/// <summary />
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
namespace QuickDevelop.Migrations
{
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure.Annotations;
using System.Data.Entity.Migrations;
public partial class AbpZero_Initial : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.AbpAuditLogs",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
UserId = c.Long(),
ServiceName = c.String(maxLength: 256),
MethodName = c.String(maxLength: 256),
Parameters = c.String(maxLength: 1024),
ExecutionTime = c.DateTime(nullable: false),
ExecutionDuration = c.Int(nullable: false),
ClientIpAddress = c.String(maxLength: 64),
ClientName = c.String(maxLength: 128),
BrowserInfo = c.String(maxLength: 256),
Exception = c.String(maxLength: 2000),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_AuditLog_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.AbpPermissions",
c => new
{
Id = c.Long(nullable: false, identity: true),
Name = c.String(nullable: false, maxLength: 128),
IsGranted = c.Boolean(nullable: false),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
RoleId = c.Int(),
UserId = c.Long(),
Discriminator = c.String(nullable: false, maxLength: 128),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true)
.ForeignKey("dbo.AbpRoles", t => t.RoleId, cascadeDelete: true)
.Index(t => t.RoleId)
.Index(t => t.UserId);
CreateTable(
"dbo.AbpRoles",
c => new
{
Id = c.Int(nullable: false, identity: true),
TenantId = c.Int(),
Name = c.String(nullable: false, maxLength: 32),
DisplayName = c.String(nullable: false, maxLength: 64),
IsStatic = c.Boolean(nullable: false),
IsDefault = c.Boolean(nullable: false),
IsDeleted = c.Boolean(nullable: false),
DeleterUserId = c.Long(),
DeletionTime = c.DateTime(),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_Role_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_Role_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.CreatorUserId)
.ForeignKey("dbo.AbpUsers", t => t.DeleterUserId)
.ForeignKey("dbo.AbpUsers", t => t.LastModifierUserId)
.ForeignKey("dbo.AbpTenants", t => t.TenantId)
.Index(t => t.TenantId)
.Index(t => t.DeleterUserId)
.Index(t => t.LastModifierUserId)
.Index(t => t.CreatorUserId);
CreateTable(
"dbo.AbpUsers",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
AuthenticationSource = c.String(maxLength: 64),
Name = c.String(nullable: false, maxLength: 32),
Surname = c.String(nullable: false, maxLength: 32),
UserName = c.String(nullable: false, maxLength: 32),
Password = c.String(nullable: false, maxLength: 128),
EmailAddress = c.String(nullable: false, maxLength: 256),
IsEmailConfirmed = c.Boolean(nullable: false),
EmailConfirmationCode = c.String(maxLength: 128),
PasswordResetCode = c.String(maxLength: 128),
LastLoginTime = c.DateTime(),
IsActive = c.Boolean(nullable: false),
IsDeleted = c.Boolean(nullable: false),
DeleterUserId = c.Long(),
DeletionTime = c.DateTime(),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_User_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_User_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.CreatorUserId)
.ForeignKey("dbo.AbpUsers", t => t.DeleterUserId)
.ForeignKey("dbo.AbpUsers", t => t.LastModifierUserId)
.ForeignKey("dbo.AbpTenants", t => t.TenantId)
.Index(t => t.TenantId)
.Index(t => t.DeleterUserId)
.Index(t => t.LastModifierUserId)
.Index(t => t.CreatorUserId);
CreateTable(
"dbo.AbpUserLogins",
c => new
{
Id = c.Long(nullable: false, identity: true),
UserId = c.Long(nullable: false),
LoginProvider = c.String(nullable: false, maxLength: 128),
ProviderKey = c.String(nullable: false, maxLength: 256),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true)
.Index(t => t.UserId);
CreateTable(
"dbo.AbpUserRoles",
c => new
{
Id = c.Long(nullable: false, identity: true),
UserId = c.Long(nullable: false),
RoleId = c.Int(nullable: false),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true)
.Index(t => t.UserId);
CreateTable(
"dbo.AbpSettings",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
UserId = c.Long(),
Name = c.String(nullable: false, maxLength: 256),
Value = c.String(maxLength: 2000),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.UserId)
.ForeignKey("dbo.AbpTenants", t => t.TenantId)
.Index(t => t.TenantId)
.Index(t => t.UserId);
CreateTable(
"dbo.AbpTenants",
c => new
{
Id = c.Int(nullable: false, identity: true),
TenancyName = c.String(nullable: false, maxLength: 64),
Name = c.String(nullable: false, maxLength: 128),
IsActive = c.Boolean(nullable: false),
IsDeleted = c.Boolean(nullable: false),
DeleterUserId = c.Long(),
DeletionTime = c.DateTime(),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_Tenant_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.CreatorUserId)
.ForeignKey("dbo.AbpUsers", t => t.DeleterUserId)
.ForeignKey("dbo.AbpUsers", t => t.LastModifierUserId)
.Index(t => t.DeleterUserId)
.Index(t => t.LastModifierUserId)
.Index(t => t.CreatorUserId);
}
public override void Down()
{
DropForeignKey("dbo.AbpRoles", "TenantId", "dbo.AbpTenants");
DropForeignKey("dbo.AbpPermissions", "RoleId", "dbo.AbpRoles");
DropForeignKey("dbo.AbpRoles", "LastModifierUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpRoles", "DeleterUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpRoles", "CreatorUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpUsers", "TenantId", "dbo.AbpTenants");
DropForeignKey("dbo.AbpSettings", "TenantId", "dbo.AbpTenants");
DropForeignKey("dbo.AbpTenants", "LastModifierUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpTenants", "DeleterUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpTenants", "CreatorUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpSettings", "UserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpUserRoles", "UserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpPermissions", "UserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpUserLogins", "UserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpUsers", "LastModifierUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpUsers", "DeleterUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpUsers", "CreatorUserId", "dbo.AbpUsers");
DropIndex("dbo.AbpTenants", new[] { "CreatorUserId" });
DropIndex("dbo.AbpTenants", new[] { "LastModifierUserId" });
DropIndex("dbo.AbpTenants", new[] { "DeleterUserId" });
DropIndex("dbo.AbpSettings", new[] { "UserId" });
DropIndex("dbo.AbpSettings", new[] { "TenantId" });
DropIndex("dbo.AbpUserRoles", new[] { "UserId" });
DropIndex("dbo.AbpUserLogins", new[] { "UserId" });
DropIndex("dbo.AbpUsers", new[] { "CreatorUserId" });
DropIndex("dbo.AbpUsers", new[] { "LastModifierUserId" });
DropIndex("dbo.AbpUsers", new[] { "DeleterUserId" });
DropIndex("dbo.AbpUsers", new[] { "TenantId" });
DropIndex("dbo.AbpRoles", new[] { "CreatorUserId" });
DropIndex("dbo.AbpRoles", new[] { "LastModifierUserId" });
DropIndex("dbo.AbpRoles", new[] { "DeleterUserId" });
DropIndex("dbo.AbpRoles", new[] { "TenantId" });
DropIndex("dbo.AbpPermissions", new[] { "UserId" });
DropIndex("dbo.AbpPermissions", new[] { "RoleId" });
DropTable("dbo.AbpTenants",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_Tenant_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpSettings");
DropTable("dbo.AbpUserRoles");
DropTable("dbo.AbpUserLogins");
DropTable("dbo.AbpUsers",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_User_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_User_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpRoles",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_Role_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_Role_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpPermissions");
DropTable("dbo.AbpAuditLogs",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_AuditLog_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System.IO;
using System.Collections.Generic;
// Support anim uvs here as well
[CanEditMultipleObjects, CustomEditor(typeof(MegaPointCache))]
public class MegaPointCacheEditor : MegaModifierEditor
{
static string lastpath = " ";
public delegate bool ParseBinCallbackType(BinaryReader br, string id);
public delegate void ParseClassCallbackType(string classname, BinaryReader br);
MegaModifiers mods;
List<MegaPCVert> Verts = new List<MegaPCVert>();
// Mapping values
float tolerance = 0.0001f;
float scl = 1.0f;
bool flipyz = false;
bool negx = false;
bool negz = false; // 8 cases now
string Read(BinaryReader br, int count)
{
byte[] buf = br.ReadBytes(count);
return System.Text.Encoding.ASCII.GetString(buf, 0, buf.Length);
}
struct MCCFrame
{
public Vector3[] points;
}
// Maya format
void LoadMCC()
{
//MegaPointCache am = (MegaPointCache)target;
//mods = am.gameObject.GetComponent<MegaModifiers>();
string filename = EditorUtility.OpenFilePanel("Maya Cache File", lastpath, "mc");
if ( filename == null || filename.Length < 1 )
return;
LoadMCC(filename);
}
#if false
public void LoadMCC(string filename)
{
MegaPointCache am = (MegaPointCache)target;
mods = am.gameObject.GetComponent<MegaModifiers>();
if ( mods == null )
{
Debug.LogWarning("You need to add a Mega Modify Object component first!");
return;
}
lastpath = filename;
FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read, System.IO.FileShare.Read);
BinaryReader br = new BinaryReader(fs);
string id = Read(br, 4);
if ( id != "FOR4" )
{
Debug.Log("wrong file");
return;
}
int offset = MegaParse.ReadMotInt(br);
br.ReadBytes(offset);
List<MCCFrame> frames = new List<MCCFrame>();
while ( true )
{
string btag = Read(br, 4);
if ( btag == "" )
break;
if ( btag != "FOR4" )
{
Debug.Log("File format error");
return;
}
int blocksize = MegaParse.ReadMotInt(br);
int bytesread = 0;
btag = Read(br, 4);
if ( btag != "MYCH" )
{
Debug.Log("File format error");
return;
}
bytesread += 4;
btag = Read(br, 4);
if ( btag != "TIME" )
{
Debug.Log("File format error");
return;
}
bytesread += 4;
br.ReadBytes(4);
bytesread += 4;
int time = MegaParse.ReadMotInt(br);
bytesread += 4;
am.maxtime = (float)time / 6000.0f;
while ( bytesread < blocksize )
{
btag = Read(br, 4);
if ( btag != "CHNM" )
{
Debug.Log("chm error");
return;
}
bytesread += 4;
int chnmsize = MegaParse.ReadMotInt(br);
bytesread += 4;
int mask = 3;
int chnmsizetoread = (chnmsize + mask) & (~mask);
//byte[] channelname = br.ReadBytes(chnmsize);
br.ReadBytes(chnmsize);
int paddingsize = chnmsizetoread - chnmsize;
if ( paddingsize > 0 )
br.ReadBytes(paddingsize);
bytesread += chnmsizetoread;
btag = Read(br, 4);
if ( btag != "SIZE" )
{
Debug.Log("Size error");
return;
}
bytesread += 4;
br.ReadBytes(4);
bytesread += 4;
int arraylength = MegaParse.ReadMotInt(br);
bytesread += 4;
MCCFrame frame = new MCCFrame();
frame.points = new Vector3[arraylength];
string dataformattag = Read(br, 4);
int bufferlength = MegaParse.ReadMotInt(br);
bytesread += 8;
if ( dataformattag == "FVCA" )
{
if ( bufferlength != arraylength * 3 * 4 )
{
Debug.Log("buffer len error");
return;
}
for ( int i = 0; i < arraylength; i++ )
{
frame.points[i].x = MegaParse.ReadMotFloat(br);
frame.points[i].y = MegaParse.ReadMotFloat(br);
frame.points[i].z = MegaParse.ReadMotFloat(br);
}
bytesread += arraylength * 3 * 4;
}
else
{
if ( dataformattag == "DVCA" )
{
if ( bufferlength != arraylength * 3 * 8 )
{
Debug.Log("buffer len error");
return;
}
for ( int i = 0; i < arraylength; i++ )
{
frame.points[i].x = (float)MegaParse.ReadMotDouble(br);
frame.points[i].y = (float)MegaParse.ReadMotDouble(br);
frame.points[i].z = (float)MegaParse.ReadMotDouble(br);
}
bytesread += arraylength * 3 * 8;
}
else
{
Debug.Log("Format Error");
return;
}
}
frames.Add(frame);
}
}
// Build table
am.Verts = new MegaPCVert[frames[0].points.Length];
for ( int i = 0; i < am.Verts.Length; i++ )
{
am.Verts[i] = new MegaPCVert();
am.Verts[i].points = new Vector3[frames.Count];
for ( int p = 0; p < am.Verts[i].points.Length; p++ )
am.Verts[i].points[p] = frames[p].points[i];
}
BuildData(mods, am, filename);
br.Close();
}
#else
public void LoadMCC(string filename)
{
MegaPointCache am = (MegaPointCache)target;
oldverts = am.Verts;
mods = am.gameObject.GetComponent<MegaModifiers>();
if ( mods == null )
{
Debug.LogWarning("You need to add a Mega Modify Object component first!");
return;
}
lastpath = filename;
FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read, System.IO.FileShare.Read);
BinaryReader br = new BinaryReader(fs);
string id = Read(br, 4);
if ( id != "FOR4" )
{
Debug.Log("wrong file");
return;
}
int offset = MegaParse.ReadMotInt(br);
br.ReadBytes(offset);
List<MCCFrame> frames = new List<MCCFrame>();
int buflen = 0;
//int clen = 0;
while ( true )
{
string btag = Read(br, 4);
if ( btag == "" )
break;
if ( btag != "FOR4" )
{
Debug.Log("File format error");
return;
}
int blocksize = MegaParse.ReadMotInt(br);
int bytesread = 0;
btag = Read(br, 4);
if ( btag != "MYCH" )
{
Debug.Log("File format error");
return;
}
bytesread += 4;
btag = Read(br, 4);
if ( btag != "TIME" )
{
Debug.Log("File format error");
return;
}
bytesread += 4;
br.ReadBytes(4);
bytesread += 4;
int time = MegaParse.ReadMotInt(br);
bytesread += 4;
am.maxtime = (float)time / 6000.0f;
while ( bytesread < blocksize )
{
btag = Read(br, 4);
if ( btag != "CHNM" )
{
Debug.Log("chm error");
return;
}
bytesread += 4;
int chnmsize = MegaParse.ReadMotInt(br);
bytesread += 4;
int mask = 3;
int chnmsizetoread = (chnmsize + mask) & (~mask);
//byte[] channelname = br.ReadBytes(chnmsize);
br.ReadBytes(chnmsize);
int paddingsize = chnmsizetoread - chnmsize;
if ( paddingsize > 0 )
br.ReadBytes(paddingsize);
bytesread += chnmsizetoread;
btag = Read(br, 4);
if ( btag != "SIZE" )
{
Debug.Log("Size error");
return;
}
bytesread += 4;
br.ReadBytes(4);
bytesread += 4;
int arraylength = MegaParse.ReadMotInt(br);
bytesread += 4;
MCCFrame frame = new MCCFrame();
frame.points = new Vector3[arraylength];
string dataformattag = Read(br, 4);
int bufferlength = MegaParse.ReadMotInt(br);
//Debug.Log("buflen " + bufferlength);
if ( buflen == 0 )
{
buflen = bufferlength;
}
bytesread += 8;
if ( dataformattag == "FVCA" )
{
if ( bufferlength != arraylength * 3 * 4 )
{
Debug.Log("buffer len error");
return;
}
for ( int i = 0; i < arraylength; i++ )
{
frame.points[i].x = MegaParse.ReadMotFloat(br);
frame.points[i].y = MegaParse.ReadMotFloat(br);
frame.points[i].z = MegaParse.ReadMotFloat(br);
}
bytesread += arraylength * 3 * 4;
}
else
{
if ( dataformattag == "DVCA" )
{
if ( bufferlength != arraylength * 3 * 8 )
{
Debug.Log("buffer len error");
return;
}
for ( int i = 0; i < arraylength; i++ )
{
frame.points[i].x = (float)MegaParse.ReadMotDouble(br);
frame.points[i].y = (float)MegaParse.ReadMotDouble(br);
frame.points[i].z = (float)MegaParse.ReadMotDouble(br);
}
bytesread += arraylength * 3 * 8;
}
else
{
Debug.Log("Format Error");
return;
}
}
if ( buflen == bufferlength )
frames.Add(frame);
}
}
//Debug.Log("frames " + frames.Count);
// Build table
am.Verts = new MegaPCVert[frames[0].points.Length];
//Debug.Log("am.Verts " + am.Verts.Length);
for ( int i = 0; i < am.Verts.Length; i++ )
{
am.Verts[i] = new MegaPCVert();
am.Verts[i].points = new Vector3[frames.Count];
for ( int p = 0; p < am.Verts[i].points.Length; p++ )
{
//Debug.Log("i " + i + " p " + p);
am.Verts[i].points[p] = frames[p].points[i];
}
}
BuildData(mods, am, filename);
br.Close();
}
#endif
void LoadMDD()
{
//MegaPointCache am = (MegaPointCache)target;
//mods = am.gameObject.GetComponent<MegaModifiers>();
string filename = EditorUtility.OpenFilePanel("Motion Designer File", lastpath, "mdd");
if ( filename == null || filename.Length < 1 )
return;
LoadMDD(filename);
}
public void LoadMDD(string filename)
{
MegaPointCache am = (MegaPointCache)target;
oldverts = am.Verts;
mods = am.gameObject.GetComponent<MegaModifiers>();
if ( mods == null)
{
Debug.LogWarning("You need to add a Mega Modify Object component first!");
return;
}
lastpath = filename;
// Clear what we have
Verts.Clear();
FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read, System.IO.FileShare.Read);
BinaryReader br = new BinaryReader(fs);
int numSamples = MegaParse.ReadMotInt(br);
int numPoints = MegaParse.ReadMotInt(br);
float t = 0.0f;
for ( int i = 0; i < numSamples; i++ )
t = MegaParse.ReadMotFloat(br);
am.maxtime = t;
am.Verts = new MegaPCVert[numPoints];
for ( int i = 0; i < am.Verts.Length; i++ )
{
am.Verts[i] = new MegaPCVert();
am.Verts[i].points = new Vector3[numSamples];
}
for ( int i = 0; i < numSamples; i++ )
{
for ( int v = 0; v < numPoints; v++ )
{
am.Verts[v].points[i].x = MegaParse.ReadMotFloat(br);
am.Verts[v].points[i].y = MegaParse.ReadMotFloat(br);
am.Verts[v].points[i].z = MegaParse.ReadMotFloat(br);
}
}
BuildData(mods, am, filename);
br.Close();
}
public bool DoAdjustFirst = false;
public bool uselastframe = false;
public int mapframe = 0;
MegaPCVert[] oldverts;
void BuildData(MegaModifiers mods, MegaPointCache am, string filename)
{
bool domapping = true;
if ( am.havemapping )
domapping = EditorUtility.DisplayDialog("Point Cache Mapping", "Replace Existing Mapping?", "Yes", "No");
if ( !domapping )
{
if ( DoAdjustFirst )
AdjustVertsSimple(mods, am);
}
else
{
if ( DoAdjustFirst )
AdjustVerts(mods, am);
}
// Build vector3[] of base verts
Vector3[] baseverts = new Vector3[am.Verts.Length];
int findex = 0;
if ( uselastframe )
{
findex = am.Verts[0].points.Length - 1;
}
for ( int i = 0; i < am.Verts.Length; i++ )
baseverts[i] = am.Verts[i].points[findex];
#if false
for ( int i = 0; i < 32; i++ )
{
Debug.Log("vert " + mods.verts[i].ToString("0.000"));
}
for ( int i = 0; i < 32; i++ )
{
Debug.Log("pc " + baseverts[i].ToString("0.000"));
}
#endif
if ( domapping )
{
if ( !TryMapping1(baseverts, mods.verts) )
{
EditorUtility.DisplayDialog("Mapping Failed!", "Mapping of " + System.IO.Path.GetFileNameWithoutExtension(filename) + " failed!", "OK");
EditorUtility.ClearProgressBar();
am.havemapping = false;
return;
}
am.negx = negx;
am.negz = negz;
am.flipyz = flipyz;
am.scl = scl;
}
else
{
negx = am.negx;
negz = am.negz;
flipyz = am.flipyz;
scl = am.scl;
}
am.havemapping = true;
// Remap vertices
for ( int i = 0; i < am.Verts.Length; i++ )
{
for ( int v = 0; v < am.Verts[i].points.Length; v++ )
{
if ( negx )
am.Verts[i].points[v].x = -am.Verts[i].points[v].x;
if ( flipyz )
{
float z = am.Verts[i].points[v].z;
am.Verts[i].points[v].z = am.Verts[i].points[v].y;
am.Verts[i].points[v].y = z;
}
if ( negz )
am.Verts[i].points[v].z = -am.Verts[i].points[v].z;
am.Verts[i].points[v] = am.Verts[i].points[v] * scl;
}
}
if ( domapping )
{
for ( int i = 0; i < am.Verts.Length; i++ )
{
am.Verts[i].indices = FindVerts(am.Verts[i].points[findex]);
if ( am.Verts[i].indices.Length == 0 )
{
EditorUtility.DisplayDialog("Final Mapping Failed!", "Mapping of " + System.IO.Path.GetFileNameWithoutExtension(filename) + " failed!", "OK");
EditorUtility.ClearProgressBar();
return;
}
}
}
else
{
for ( int i = 0; i < am.Verts.Length; i++ )
{
am.Verts[i].indices = oldverts[i].indices;
}
}
oldverts = null;
}
public void LoadFile(string filename)
{
string ext = System.IO.Path.GetExtension(filename);
ext = ext.ToLower();
switch ( ext )
{
case ".pc2":
LoadPC2(filename);
break;
case ".mdd":
LoadMDD(filename);
break;
case ".mc":
LoadMCC(filename);
break;
}
}
void LoadPC2()
{
//MegaPointCache am = (MegaPointCache)target;
//mods = am.gameObject.GetComponent<MegaModifiers>();
string filename = EditorUtility.OpenFilePanel("Point Cache File", lastpath, "pc2");
if ( filename == null || filename.Length < 1 )
return;
LoadPC2(filename);
}
public void LoadPC2(string filename)
{
MegaPointCache am = (MegaPointCache)target;
oldverts = am.Verts;
mods = am.gameObject.GetComponent<MegaModifiers>();
if ( mods == null )
{
Debug.LogWarning("You need to add a Mega Modify Object component first!");
return;
}
lastpath = filename;
// Clear what we have
Verts.Clear();
FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read, System.IO.FileShare.Read);
long len = fs.Length;
BinaryReader br = new BinaryReader(fs);
string sig = MegaParse.ReadStr(br);
if ( sig != "POINTCACHE2" )
{
EditorUtility.DisplayDialog("PC2 Importer", "The selected file does not appear to be a valid PC2 File", "Ok");
br.Close();
return;
}
int fileVersion = br.ReadInt32();
if ( fileVersion != 1 )
{
br.Close();
return;
}
int numPoints = br.ReadInt32();
br.ReadSingle();
br.ReadSingle();
int numSamples = br.ReadInt32();
long csamples = (len - 24) / (numPoints * 12);
numSamples = (int)csamples;
am.Verts = new MegaPCVert[numPoints];
for ( int i = 0; i < am.Verts.Length; i++ )
{
am.Verts[i] = new MegaPCVert();
am.Verts[i].points = new Vector3[numSamples];
}
for ( int i = 0; i < numSamples; i++ )
{
for ( int v = 0; v < numPoints; v++ )
am.Verts[v].points[i] = MegaParse.ReadP3(br);
}
BuildData(mods, am, filename);
br.Close();
}
// Utils methods
int[] FindVerts(Vector3 p)
{
List<int> indices = new List<int>();
for ( int i = 0; i < mods.verts.Length; i++ )
{
//float dist = Vector3.Distance(p, mods.verts[i]);
float dist = Vector3.SqrMagnitude(p - mods.verts[i]);
if ( dist < tolerance ) //0.0001f ) //mods.verts[i].Equals(p) )
indices.Add(i);
}
return indices.ToArray();
}
Vector3 Extents(Vector3[] verts, out Vector3 min, out Vector3 max)
{
Vector3 extent = Vector3.zero;
min = Vector3.zero;
max = Vector3.zero;
if ( verts != null && verts.Length > 0 )
{
min = verts[0];
max = verts[0];
for ( int i = 1; i < verts.Length; i++ )
{
if ( verts[i].x < min.x ) min.x = verts[i].x;
if ( verts[i].y < min.y ) min.y = verts[i].y;
if ( verts[i].z < min.z ) min.z = verts[i].z;
if ( verts[i].x > max.x ) max.x = verts[i].x;
if ( verts[i].y > max.y ) max.y = verts[i].y;
if ( verts[i].z > max.z ) max.z = verts[i].z;
}
extent = max - min;
}
return extent;
}
Vector3 Extents(MegaPCVert[] verts, out Vector3 min, out Vector3 max)
{
Vector3 extent = Vector3.zero;
min = Vector3.zero;
max = Vector3.zero;
if ( verts != null && verts.Length > 0 )
{
min = verts[0].points[0];
max = verts[0].points[0];
for ( int i = 1; i < verts.Length; i++ )
{
Vector3 p = verts[i].points[0];
if ( p.x < min.x ) min.x = p.x;
if ( p.y < min.y ) min.y = p.y;
if ( p.z < min.z ) min.z = p.z;
if ( p.x > max.x ) max.x = p.x;
if ( p.y > max.y ) max.y = p.y;
if ( p.z > max.z ) max.z = p.z;
}
extent = max - min;
}
return extent;
}
bool showadvanced = false;
public override void OnInspectorGUI()
{
MegaPointCache am = (MegaPointCache)target;
DoAdjustFirst = EditorGUILayout.Toggle("Mapping Adjust", DoAdjustFirst);
uselastframe = EditorGUILayout.Toggle("Use Last Frame", uselastframe);
EditorGUILayout.BeginHorizontal();
if ( GUILayout.Button("Import PC2") )
{
LoadPC2();
EditorUtility.SetDirty(target);
}
if ( GUILayout.Button("Import MDD") )
{
LoadMDD();
EditorUtility.SetDirty(target);
}
if ( GUILayout.Button("Import MC") )
{
LoadMCC();
EditorUtility.SetDirty(target);
}
EditorGUILayout.EndHorizontal();
// Basic mod stuff
showmodparams = EditorGUILayout.Foldout(showmodparams, "Modifier Common Params");
if ( showmodparams )
CommonModParamsBasic(am);
// Advanced
showadvanced = EditorGUILayout.Foldout(showadvanced, "Advanced Params");
if ( showadvanced )
{
tolerance = EditorGUILayout.FloatField("Map Tolerance", tolerance * 100.0f) / 100.0f;
if ( am.Verts != null && am.Verts.Length > 0 ) //[0] != null )
{
am.showmapping = EditorGUILayout.BeginToggleGroup("Show Mapping", am.showmapping);
am.mapStart = EditorGUILayout.IntSlider("StartVert", am.mapStart, 0, am.Verts.Length);
am.mapEnd = EditorGUILayout.IntSlider("endVert", am.mapEnd, 0, am.Verts.Length);
am.mappingSize = EditorGUILayout.Slider("Size", am.mappingSize, 0.0005f, 10.01f);
EditorGUILayout.EndToggleGroup();
}
//morph.tolerance = EditorGUILayout.Slider("Tolerance", morph.tolerance, 0.0f, 0.01f);
}
am.time = EditorGUILayout.FloatField("Time", am.time);
am.maxtime = EditorGUILayout.FloatField("Loop Time", am.maxtime);
am.animated = EditorGUILayout.Toggle("Animated", am.animated);
am.framedelay = EditorGUILayout.Toggle("Frame Delay", am.framedelay);
am.speed = EditorGUILayout.FloatField("Speed", am.speed);
am.LoopMode = (MegaRepeatMode)EditorGUILayout.EnumPopup("Loop Mode", am.LoopMode);
am.interpMethod = (MegaInterpMethod)EditorGUILayout.EnumPopup("Interp Method", am.interpMethod);
am.blendMode = (MegaBlendAnimMode)EditorGUILayout.EnumPopup("Blend Mode", am.blendMode);
if ( am.blendMode == MegaBlendAnimMode.Additive )
am.weight = EditorGUILayout.FloatField("Weight", am.weight);
if ( am.Verts != null && am.Verts.Length > 0 )
{
int mem = am.Verts.Length * am.Verts[0].points.Length * 12;
EditorGUILayout.LabelField("Memory: ", (mem / 1024) + "KB");
}
if ( GUI.changed )
EditorUtility.SetDirty(target);
}
// From here down could move to util class
int FindVert(Vector3 vert, Vector3[] tverts, float tolerance, float scl, bool flipyz, bool negx, bool negz, int vn)
{
int find = 0;
if ( negx )
vert.x = -vert.x;
if ( flipyz )
{
float z = vert.z;
vert.z = vert.y;
vert.y = z;
}
if ( negz )
vert.z = -vert.z;
vert /= scl;
float closest = Vector3.SqrMagnitude(tverts[0] - vert);
for ( int i = 0; i < tverts.Length; i++ )
{
float dif = Vector3.SqrMagnitude(tverts[i] - vert);
if ( dif < closest )
{
closest = dif;
find = i;
}
}
if ( closest > tolerance ) //0.0001f ) // not exact
{
return -1;
}
return find; //0;
}
bool DoMapping(Vector3[] verts, Vector3[] tverts, float scale, bool flipyz, bool negx, bool negz)
{
int count = 400;
for ( int i = 0; i < verts.Length; i++ )
{
float a = (float)i / (float)verts.Length;
count--;
if ( count < 0 )
{
//Debug.Log("map " + i + " vert " + verts[i].ToString("0.00000"));
EditorUtility.DisplayProgressBar("Mapping", "Mapping vertex " + i, a);
count = 400;
}
int mapping = FindVert(verts[i], tverts, tolerance, scale, flipyz, negx, negz, i);
if ( mapping == -1 )
{
// Failed
EditorUtility.ClearProgressBar();
return false;
}
}
EditorUtility.ClearProgressBar();
return true;
}
// Out of this we need scl, negx, negz and flipyz
bool TryMapping1(Vector3[] tverts, Vector3[] verts)
{
//for ( int i = 0; i < 8; i++ )
// Debug.Log("cache vert " + tverts[i].ToString("0.00000"));
//for ( int i = 0; i < 8; i++ )
// Debug.Log("mesh vert " + verts[i].ToString("0.00000"));
// Get extents for mod verts and for imported meshes, if not the same then scale
Vector3 min1,max1;
Vector3 min2,max2;
Vector3 ex1 = Extents(verts, out min1, out max1);
Vector3 ex2 = Extents(tverts, out min2, out max2);
//Debug.Log("mesh extents " + ex1.ToString("0.00000"));
//Debug.Log("cache extents " + ex2.ToString("0.00000"));
//Debug.Log("mesh min " + min1.ToString("0.00000"));
//Debug.Log("cache min " + min2.ToString("0.00000"));
//Debug.Log("mesh max " + max1.ToString("0.00000"));
//Debug.Log("cache max " + max2.ToString("0.00000"));
int largest1 = MegaUtils.LargestComponent(ex1);
int largest2 = MegaUtils.LargestComponent(ex2);
//Debug.Log(largest1 + " " + largest2);
scl = ex1[largest1] / ex2[largest2];
//Debug.Log("scl " + scl.ToString("0.0000"));
//Vector3 offset = verts[0] - (tverts[0] * scl);
//Debug.Log("Offset " + offset.ToString("0.00000"));
// need min max on all axis so we can produce an offset to add
int map = 0;
for ( map = 0; map < 8; map++ )
{
flipyz = ((map & 4) != 0);
negx = ((map & 2) != 0);
negz = ((map & 1) != 0);
bool mapped = DoMapping(verts, tverts, scl, flipyz, negx, negz);
if ( mapped )
break;
}
if ( map == 8 ) // We couldnt find any mapping
return false;
//Debug.Log("scl " + scl + " negx " + negx + " negz " + negz + " flipyz " + flipyz);
return true;
}
void AdjustVertsSimple(MegaModifiers mods, MegaPointCache am)
{
if ( am.Verts != null )
{
Vector3[] baseverts = new Vector3[am.Verts.Length];
for ( int i = 0; i < am.Verts.Length; i++ )
baseverts[i] = am.Verts[i].points[0];
for ( int i = 0; i < am.Verts.Length; i++ )
{
for ( int j = 0; j < am.Verts[i].points.Length; j++ )
{
Vector3 p = am.Verts[i].points[j] * am.adjustscl;
am.Verts[i].points[j] = p - am.adjustoff;
}
}
}
}
void AdjustVerts(MegaModifiers mods, MegaPointCache am)
{
if ( am.Verts != null )
{
Vector3[] baseverts = new Vector3[am.Verts.Length];
for ( int i = 0; i < am.Verts.Length; i++ )
baseverts[i] = am.Verts[i].points[0];
Vector3 min1,max1;
Vector3 min2,max2;
Vector3 ex1 = Extents(mods.verts, out min1, out max1);
Vector3 ex2 = Extents(baseverts, out min2, out max2);
//Debug.Log("mesh extents " + ex1.ToString("0.00000"));
//Debug.Log("cache extents " + ex2.ToString("0.00000"));
//Debug.Log("mesh min " + min1.ToString("0.00000"));
//Debug.Log("cache min " + min2.ToString("0.00000"));
//Debug.Log("mesh max " + max1.ToString("0.00000"));
//Debug.Log("cache max " + max2.ToString("0.00000"));
int largest1 = MegaUtils.LargestComponent(ex1);
int largest2 = MegaUtils.LargestComponent(ex2);
//Debug.Log(largest1 + " " + largest2);
am.adjustscl = ex1[largest1] / ex2[largest2];
//Debug.Log("scl " + scl1.ToString("0.0000"));
//off = verts[0] - (tverts[0] * scl);
am.adjustoff = (min2 * am.adjustscl) - min1;
//Debug.Log("scl " + am.adjustscl);
//Debug.Log("off " + am.adjustoff);
for ( int i = 0; i < am.Verts.Length; i++ )
{
for ( int j = 0; j < am.Verts[i].points.Length; j++ )
{
Vector3 p = am.Verts[i].points[j] * am.adjustscl;
am.Verts[i].points[j] = p - am.adjustoff;
}
}
}
}
MegaModifyObject mo = null;
//public void OnSceneGUI()
public override void DrawSceneGUI()
{
MegaPointCache mod = (MegaPointCache)target;
if ( mod.showmapping )
{
if ( mod.Verts != null && mod.Verts[0] != null )
{
float vsize = mod.mappingSize;
float vsize1 = vsize * 0.75f;
Matrix4x4 tm = mod.gameObject.transform.localToWorldMatrix;
Handles.matrix = tm; //Matrix4x4.identity;
Handles.color = Color.green;
if ( mo == null )
mo = mod.gameObject.GetComponent<MegaModifyObject>();
if ( mo )
{
for ( int i = 0; i < mo.verts.Length; i++ )
{
Vector3 p = mo.verts[i];
MegaHandles.DotCap(i, p, Quaternion.identity, vsize);
}
}
if ( mod.mapEnd >= mod.Verts.Length )
mod.mapEnd = mod.Verts.Length - 1;
if ( mod.mapStart > mod.mapEnd )
mod.mapStart = mod.mapEnd;
Handles.color = Color.white; //red;
int findex = 0;
if ( uselastframe )
{
findex = mod.Verts[0].points.Length - 1;
}
for ( int i = mod.mapStart; i < mod.mapEnd; i++ )
{
Vector3 p = mod.Verts[i].points[findex];
MegaHandles.DotCap(i, p, Quaternion.identity, vsize1);
}
Handles.matrix = Matrix4x4.identity;
}
}
}
}
| |
/*
WindowStateManager - Remembers window size, location and state across changes in resolution, and allows serialization to XML.
Copyright (c) 2005 Benjamin Hollis
(The 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.
*/
using System;
using System.Windows.Forms;
using Microsoft.Win32;
using System.Drawing;
using System.Collections;
using System.Xml.Serialization;
using System.Diagnostics;
using System.IO;
namespace Brh.Forms
{
/// <summary>
/// Remembers window size, location and state across changes in resolution, and allows serialization to XML.
/// </summary>
[XmlRoot("WindowState")]
public class WindowStateManager
{
public WindowStateManager()
{
_stateByResolution = new Hashtable();
}
/// <summary>
/// Use this to set the parent form, which will have its state saved.
/// </summary>
[XmlIgnore]
public Form Parent
{
//Note: setting another parent after this will be bad
set
{
_parent = value;
// subscribe to parent form's events
_parent.Closing += new System.ComponentModel.CancelEventHandler(OnClosing);
_parent.Resize += new System.EventHandler(OnResize);
_parent.Move += new System.EventHandler(OnMove);
_parent.Load += new System.EventHandler(OnLoad);
SystemEvents.DisplaySettingsChanged += new EventHandler(OnDisplaySettingsChanged);
// get initial width and height in case form is never resized
System.Drawing.Size screenSize = Screen.FromRectangle(new Rectangle(_parent.Location, _parent.Size)).Bounds.Size;
_thisState = new WindowSizeLocation(_parent.Size, _parent.Location, screenSize);
if(_stateByResolution.ContainsKey(_thisState.ScreenSize))
{
_parent.StartPosition = FormStartPosition.Manual;
//This seems to be setting the window location too early!
_loadedWindowState = _windowState;
_thisState = (WindowSizeLocation)_stateByResolution[_thisState.ScreenSize];
SetWindowState();
}
_stateByResolution[_thisState.ScreenSize] = _thisState;
}
get
{
return _parent;
}
}
/// <summary>
/// The table of sizes for each resolution. As far as I can tell this needs to be public to be persisted in XML. Bummer.
/// </summary>
public WindowSizeLocation[] Resolutions
{
get
{
WindowSizeLocation[] output = new WindowSizeLocation[_stateByResolution.Count];
int i=0;
foreach(WindowSizeLocation wsl in _stateByResolution.Values)
{
output[i] = wsl;
++i;
}
return output;
}
set
{
foreach(WindowSizeLocation wsl in value)
{
_stateByResolution[wsl.ScreenSize] = wsl;
}
}
}
/// <summary>
/// Whether or not the form should save the "Minimized" state.
/// </summary>
public bool AllowSaveMinimized
{
get {return _allowSaveMinimized;}
set {_allowSaveMinimized = value;}
}
/// <summary>
/// The current state of the window (Minimized, Normal, Maximized)
/// </summary>
public FormWindowState WindowState
{
get
{
return _windowState;
}
set
{
_windowState = value;
}
}
private void SetWindowState()
{
settingState = true;
Application.DoEvents();
_parent.Location = _thisState.Location;
_parent.Size = _thisState.Size;
_parent.WindowState = _windowState;
settingState = false;
}
private void OnResize(object sender, System.EventArgs e)
{
// save width and height
if(!settingState && _parent.WindowState == FormWindowState.Normal)
{
_thisState.Size = _parent.Size;
Debug.Assert(_thisState.Size == ((WindowSizeLocation)_stateByResolution[_thisState.ScreenSize]).Size);
}
}
private void OnMove(object sender, System.EventArgs e)
{
if(!settingState)
{
System.Drawing.Size screenSize = Screen.FromRectangle(new Rectangle(_parent.Location, _parent.Size)).Bounds.Size;
if(screenSize == _thisState.ScreenSize)
{
//Debug.WriteLine("Moved");
// save position
if(_parent.WindowState == FormWindowState.Normal)
{
_thisState.Location = _parent.Location;
Debug.Assert(_thisState.Location == ((WindowSizeLocation)_stateByResolution[_thisState.ScreenSize]).Location);
}
// save state
if(!(_parent.WindowState == FormWindowState.Minimized && !_allowSaveMinimized))
_windowState = _parent.WindowState;
}
}
}
private void OnClosing(object sender, System.ComponentModel.CancelEventArgs e)
{
}
private void OnLoad(object sender, System.EventArgs e)
{
_parent.WindowState = _loadedWindowState;
}
private void OnDisplaySettingsChanged(object sender, EventArgs e)
{
System.Drawing.Size screenSize = Screen.FromRectangle(new Rectangle(_parent.Location, _parent.Size)).Bounds.Size;
Debug.WriteLine("DisplaySettingsChanged: " + screenSize.ToString());
if(_stateByResolution.ContainsKey(screenSize))
{
Debug.WriteLine("Back in familiar territory.");
_thisState = (WindowSizeLocation)_stateByResolution[screenSize];
}
else
{
Debug.WriteLine("This is a new frontier.");
WindowSizeLocation newState = new WindowSizeLocation(_parent.Size, _parent.Location, screenSize);
if(_parent.WindowState != FormWindowState.Normal)
{
newState.Location = _thisState.Location;
newState.Size = _thisState.Size;
}
_thisState = newState;
_stateByResolution[_thisState.ScreenSize] = _thisState;
}
//If the form is offscreen, move it back on.
Rectangle windowRect = new Rectangle(_thisState.Location, _thisState.Size);
Rectangle workingArea = Screen.FromRectangle(windowRect).WorkingArea;
if(!workingArea.IntersectsWith(windowRect))
{
Point newLoc = new Point(_thisState.Location.X, _thisState.Location.Y);
if(_thisState.Location.X < workingArea.X)
newLoc.X = workingArea.X;
else if(_thisState.Location.X > workingArea.Right)
newLoc.X = workingArea.Right - _thisState.Size.Width;
if(_thisState.Location.Y < workingArea.Y)
newLoc.Y = workingArea.Y;
else if(_thisState.Location.Y > workingArea.Bottom)
newLoc.Y = workingArea.Bottom - _thisState.Size.Height;
_thisState.Location = newLoc;
}
SetWindowState();
}
public void Save(string filename)
{
XmlSerializer s = new XmlSerializer( typeof( WindowStateManager ) );
TextWriter w = new StreamWriter( filename );
s.Serialize( w, this );
w.Close();
}
public static WindowStateManager Load(string filename)
{
WindowStateManager output;
if(File.Exists(filename))
{
TextReader r = null;
try
{
XmlSerializer s = new XmlSerializer( typeof( WindowStateManager ) );
r = new StreamReader( filename );
output = (WindowStateManager)s.Deserialize( r );
r.Close();
}
catch(InvalidOperationException)
{
if(r != null)
r.Close();
File.Delete(filename);
output = new WindowStateManager();
}
}
else
{
output = new WindowStateManager();
}
return output;
}
private Form _parent;
private FormWindowState _windowState;
private FormWindowState _loadedWindowState;
private bool _allowSaveMinimized = false;
private bool _dockToScreenEdges = true;
private int _dockDistance = 5;//px
private Hashtable/*<WindowSizeLocation>*/ _stateByResolution;
private WindowSizeLocation _thisState;
bool settingState = false;
[XmlRoot("Resolution")]
public class WindowSizeLocation
{
public WindowSizeLocation()
{
}
public WindowSizeLocation(System.Drawing.Size windowSize, System.Drawing.Point windowPos, System.Drawing.Size screenSize)
{
_windowSize = windowSize;
_windowPos = windowPos;
_screenSize = screenSize;
}
public System.Drawing.Size Size
{
get { return _windowSize; }
set { _windowSize = value; }
}
public System.Drawing.Point Location
{
get { return _windowPos; }
set { _windowPos = value; }
}
public System.Drawing.Size ScreenSize
{
get { return _screenSize; }
set { _screenSize = value; }
}
private System.Drawing.Size _windowSize;
private System.Drawing.Point _windowPos;
private System.Drawing.Size _screenSize;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
namespace Pacman.GameLogic
{
[Serializable()]
public class Map : ICloneable
{
public const int Width = 28;
public const int Height = 31;
public const int NodeTopDistance = 5;
public const int NodeLeftDistance = 3;
public const int NodeDistance = 8;
public readonly int PixelWidth;
public readonly int PixelHeight;
public static readonly Color BackColor = Color.FromArgb(0,0,0);
[NonSerialized()]
private Image image;
public int PillsLeft = 0;
//public readonly Maze Maze;
private static Node[,] BackupNodes = new Node[Width,Height];
public List<Node> PillNodes = new List<Node>();
public List<Node> PowerPillNodes = new List<Node>();
public Node[,] Nodes = new Node[Width, Height];
// Generate the new map use for holding the weightings
public Node.NodeType[,] NodeData = new Node.NodeType[Width, Height];
public bool[] Tunnels = new bool[Height];
public Map(Bitmap map) {
//this.Maze = maze;
image = map;
PixelWidth = image.Width;
PixelHeight = image.Height;
analyzeMap(map);
analyzeNodes();
analyzeShortestPath();
foreach( Node n in Nodes ) {
BackupNodes[n.X, n.Y] = n.Clone();
}
}
public void Reset(){
PillsLeft = PillNodes.Count;
foreach( Node n in PillNodes ) {
n.Type = BackupNodes[n.X,n.Y].Type;
}
/*analyzeMap((Bitmap)image);
analyzeNodes();
analyzeShortestPath();*/
}
public Node GetNodeDirection(int x, int y, Direction pDirection)
{
int _tempX = x, _tempY = y;
// Based on the direction that is provided, return the node that is required.
switch (pDirection)
{
case Direction.Left:
_tempX--;
break;
case Direction.Right:
_tempX++;
break;
case Direction.Up:
_tempY--;
break;
case Direction.Down:
_tempY++;
break;
}
if (_tempX < Map.Width && _tempX >= 0 &&
_tempY < Map.Height && _tempY >= 0)
{
return Nodes[_tempX, _tempY];
}
return null;
}
public Node GetNode(int x, int y) {
int xPos = (int)Math.Floor((x - NodeLeftDistance) / (float)NodeDistance);
if( xPos < 0 ) xPos = 0; if( xPos >= Width ) xPos = Width - 1;
int yPos = (int)Math.Floor((y - NodeTopDistance) / (float)NodeDistance);
return Nodes[xPos, yPos];
}
public Node GetNodeNonWall(int x, int y) {
Node n = GetNode(x, y);
if( n.Type == Node.NodeType.Wall ) {
if( n.Up.Type != Node.NodeType.Wall ) return n.Up;
if( n.Down.Type != Node.NodeType.Wall ) return n.Down;
if( n.Left.Type != Node.NodeType.Wall ) return n.Left;
if( n.Right.Type != Node.NodeType.Wall ) return n.Right;
}
return n;
}
public List<Node> GetRoute(Node start, Node end) {
return GetRoute(start.X, start.Y, end.X, end.Y);
}
public List<Node> GetRoute(int startX, int startY, int endX, int endY) {
Node.PathInfo pathInfo = Nodes[startX, startY].ShortestPath[endX, endY];
if( pathInfo == null ) {
//Console.WriteLine("No path from " + startX + "," + startY + " to " + endX + "," + endY);
return null;
}
List<Node> path = new List<Node>();
Node curNode = Nodes[startX,startY];
while( !(curNode.X == endX && curNode.Y == endY) ) {
curNode = curNode.GetNode(curNode.ShortestPath[endX, endY].Direction);
path.Add(curNode);
}
return path;
}
private void analyzeShortestPath() {
foreach( Node n in Nodes ) {
if( n.Type == Node.NodeType.Wall )
continue;
//if( !(n.X == 13 && n.Y == 23) ) // test only pac position
// continue;
LinkedList<LinkedListNode<Node>> openList = new LinkedList<LinkedListNode<Node>>();
LinkedListNode<LinkedListNode<Node>> startNode = new LinkedListNode<LinkedListNode<Node>>(new LinkedListNode<Node>(n));
n.ShortestPath[n.X, n.Y] = new Node.PathInfo(Direction.None, 0);
shortestPathAddNode(startNode.Value, startNode.Value.Value.Up, Direction.Up, openList);
shortestPathAddNode(startNode.Value, startNode.Value.Value.Down, Direction.Down, openList);
shortestPathAddNode(startNode.Value, startNode.Value.Value.Left, Direction.Left, openList);
shortestPathAddNode(startNode.Value, startNode.Value.Value.Right, Direction.Right, openList);
while( openList.Count > 0 ) {
shortestPathProcessNode(n, openList.First, openList);
}
foreach( Node nClean in Nodes ) {
nClean.ShortestPath[nClean.X, nClean.Y] = null;
}
}
}
private void shortestPathProcessNode(Node curNode, LinkedListNode<LinkedListNode<Node>> n, LinkedList<LinkedListNode<Node>> openList) {
openList.Remove(n);
Node removeNode = n.Value.Value;
curNode.ShortestPath[removeNode.X, removeNode.Y] = removeNode.ShortestPath[removeNode.X, removeNode.Y];
Direction fromDir = removeNode.ShortestPath[removeNode.X, removeNode.Y].Direction;
shortestPathAddNode(n.Value, n.Value.Value.Up, fromDir, openList);
shortestPathAddNode(n.Value, n.Value.Value.Down, fromDir, openList);
shortestPathAddNode(n.Value, n.Value.Value.Left, fromDir, openList);
shortestPathAddNode(n.Value, n.Value.Value.Right, fromDir, openList);
}
private void shortestPathAddNode(LinkedListNode<Node> n, Node nDir, Direction dir, LinkedList<LinkedListNode<Node>> openList) {
if( nDir.Type == Node.NodeType.Wall || nDir.ShortestPath[nDir.X,nDir.Y] != null )
return;
nDir.ShortestPath[nDir.X, nDir.Y] = new Node.PathInfo(dir, n.Value.ShortestPath[n.Value.X, n.Value.Y].Distance + 1);
bool added = false;
foreach( LinkedListNode<Node> existingNode in openList ) {
if( existingNode.Value.ShortestPath[existingNode.Value.X, existingNode.Value.Y].Distance >
nDir.ShortestPath[nDir.X, nDir.Y].Distance ) {
openList.AddBefore(new LinkedListNode<LinkedListNode<Node>>(existingNode), new LinkedListNode<LinkedListNode<Node>>(new LinkedListNode<Node>(nDir)));
added = true;
break;
}
}
if( !added ) {
openList.AddLast(new LinkedListNode<Node>(nDir));
}
}
public void analyzeNodes() {
for( int x = 0; x < Width; x++ ) {
for( int y = 0; y < Height; y++ ) {
// up
if( y == 0 ) {
Nodes[x, y].Up = Nodes[x, Height - 1];
} else {
Nodes[x, y].Up = Nodes[x, y - 1];
}
// down
if( y == Height - 1 ) {
Nodes[x, y].Down = Nodes[x, 0];
} else {
Nodes[x, y].Down = Nodes[x, y + 1];
}
// left
if( x == 0 ) {
Nodes[x, y].Left = Nodes[Width - 1, y];
// tunnels
if( Nodes[x, y].Walkable ) {
Tunnels[y] = true;
} else {
Tunnels[y] = false;
}
} else {
Nodes[x, y].Left = Nodes[x - 1, y];
}
// right
if( x == Width - 1 ) {
Nodes[x, y].Right = Nodes[0, y];
} else {
Nodes[x, y].Right = Nodes[x + 1, y];
}
}
}
// close center
Nodes[13, 12].Type = Node.NodeType.Wall;
Nodes[14, 12].Type = Node.NodeType.Wall;
// set possible directions
for( int x = 0; x < Width; x++ ) {
for( int y = 0; y < Height; y++ ) {
Nodes[x, y].PossibleDirections = new List<Node>();
if( Nodes[x, y].Up.Walkable ) {
Nodes[x, y].PossibleDirections.Add(Nodes[x, y].Up);
}
if( Nodes[x, y].Down.Walkable ) {
Nodes[x, y].PossibleDirections.Add(Nodes[x, y].Down);
}
if( Nodes[x, y].Left.Walkable ) {
Nodes[x, y].PossibleDirections.Add(Nodes[x, y].Left);
}
if( Nodes[x, y].Right.Walkable ) {
Nodes[x, y].PossibleDirections.Add(Nodes[x, y].Right);
}
// set ghost possible
Nodes[x, y].GhostPossibles.Add(new List<Node>(4));
foreach( Node n in Nodes[x, y].PossibleDirections ) {
if( n != Nodes[x, y].Down ) {
Nodes[x, y].GhostPossibles[0].Add(n);
}
}
Nodes[x, y].GhostPossibles.Add(new List<Node>(4));
foreach( Node n in Nodes[x, y].PossibleDirections ) {
if( n != Nodes[x, y].Up ) {
Nodes[x, y].GhostPossibles[1].Add(n);
}
}
Nodes[x, y].GhostPossibles.Add(new List<Node>(4));
foreach( Node n in Nodes[x, y].PossibleDirections ) {
if( n != Nodes[x, y].Right ) {
Nodes[x, y].GhostPossibles[2].Add(n);
}
}
Nodes[x, y].GhostPossibles.Add(new List<Node>(4));
foreach( Node n in Nodes[x, y].PossibleDirections ) {
if( n != Nodes[x, y].Left ) {
Nodes[x, y].GhostPossibles[3].Add(n);
}
}
}
}
}
private void analyzeMap(Bitmap map){
for( int x = 0; x < Width; x++ ) {
for( int y = 0; y < Height; y++ ) {
if( gamePosition(map, x, y) ) {
if( getPositionColor(map, x, y, 0, 0) == BackColor ) {
Nodes[x, y] = new Node(x, y, Node.NodeType.None);
} else if( getPositionColor(map, x, y, -1, -1) == BackColor ) {
Nodes[x, y] = new Node(x, y, Node.NodeType.Pill);
PillNodes.Add(Nodes[x, y]);
PillsLeft++;
} else {
Nodes[x, y] = new Node(x, y, Node.NodeType.PowerPill);
PillNodes.Add(Nodes[x, y]);
PowerPillNodes.Add(Nodes[x, y]);
PillsLeft++;
}
} else {
Nodes[x, y] = new Node(x, y, Node.NodeType.Wall);
}
}
}
}
private bool gamePosition(Bitmap map, int x, int y) {
if( getPositionColor(map, x, y, -3, -3) != BackColor )
return false;
if( getPositionColor(map, x, y, -3, +4) != BackColor )
return false;
if( getPositionColor(map, x, y, +4, -3) != BackColor )
return false;
if( getPositionColor(map, x, y, +4, +4) != BackColor )
return false;
return true;
}
private Color getPositionColor(Bitmap map, int x, int y, int xOffset, int yOffset) {
return map.GetPixel(NodeLeftDistance + x * NodeDistance + xOffset, NodeTopDistance + y * NodeDistance + yOffset);
}
public void Draw(Graphics g) {
g.DrawImageUnscaled(image, new Point(0, 0));
foreach( Node node in Nodes ) {
node.Draw(g);
}
}
public object Clone()
{
// Clone the values that we require
// and regenerate all the reference values.
Map _newmap = (Map)this.MemberwiseClone();
_newmap.PillNodes = new List<Node>();
_newmap.PillNodes.Clear();
_newmap.PowerPillNodes = new List<Node>();
_newmap.PowerPillNodes.Clear();
_newmap.Nodes = new Node[Nodes.GetLength(0),
Nodes.GetLength(1)];
// Loop through the nodes and copy them appropriately
for (int x = 0; x < Nodes.GetLength(0); x++)
{
for (int y = 0; y < Nodes.GetLength(1); y++)
{
_newmap.Nodes[x, y] = Nodes[x, y].Clone();
if (_newmap.Nodes[x, y].Type == Node.NodeType.PowerPill ||
_newmap.Nodes[x, y].Type == Node.NodeType.Pill)
{
// Add the node
_newmap.PillNodes.Add(_newmap.Nodes[x, y]);
}
if(_newmap.Nodes[x,y].Type == Node.NodeType.PowerPill)
{
_newmap.PowerPillNodes.Add(_newmap.Nodes[x, y]);
}
}
}
// Copy over the node data.
_newmap.NodeData = new Node.NodeType[Width, Height];
foreach (var n in Nodes)
{
_newmap.NodeData[n.X, n.Y] = n.Type;
}
//_newmap.analyzeNodes();
return _newmap;
}
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Converters;
namespace Twilio.Rest.Taskrouter.V1.Workspace
{
/// <summary>
/// FetchActivityOptions
/// </summary>
public class FetchActivityOptions : IOptions<ActivityResource>
{
/// <summary>
/// The SID of the Workspace with the Activity resources to fetch
/// </summary>
public string PathWorkspaceSid { get; }
/// <summary>
/// The SID of the resource to fetch
/// </summary>
public string PathSid { get; }
/// <summary>
/// Construct a new FetchActivityOptions
/// </summary>
/// <param name="pathWorkspaceSid"> The SID of the Workspace with the Activity resources to fetch </param>
/// <param name="pathSid"> The SID of the resource to fetch </param>
public FetchActivityOptions(string pathWorkspaceSid, string pathSid)
{
PathWorkspaceSid = pathWorkspaceSid;
PathSid = pathSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
return p;
}
}
/// <summary>
/// UpdateActivityOptions
/// </summary>
public class UpdateActivityOptions : IOptions<ActivityResource>
{
/// <summary>
/// The SID of the Workspace with the Activity resources to update
/// </summary>
public string PathWorkspaceSid { get; }
/// <summary>
/// The SID of the Activity resource to update
/// </summary>
public string PathSid { get; }
/// <summary>
/// A string to describe the Activity resource
/// </summary>
public string FriendlyName { get; set; }
/// <summary>
/// Construct a new UpdateActivityOptions
/// </summary>
/// <param name="pathWorkspaceSid"> The SID of the Workspace with the Activity resources to update </param>
/// <param name="pathSid"> The SID of the Activity resource to update </param>
public UpdateActivityOptions(string pathWorkspaceSid, string pathSid)
{
PathWorkspaceSid = pathWorkspaceSid;
PathSid = pathSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (FriendlyName != null)
{
p.Add(new KeyValuePair<string, string>("FriendlyName", FriendlyName));
}
return p;
}
}
/// <summary>
/// DeleteActivityOptions
/// </summary>
public class DeleteActivityOptions : IOptions<ActivityResource>
{
/// <summary>
/// The SID of the Workspace with the Activity resources to delete
/// </summary>
public string PathWorkspaceSid { get; }
/// <summary>
/// The SID of the Activity resource to delete
/// </summary>
public string PathSid { get; }
/// <summary>
/// Construct a new DeleteActivityOptions
/// </summary>
/// <param name="pathWorkspaceSid"> The SID of the Workspace with the Activity resources to delete </param>
/// <param name="pathSid"> The SID of the Activity resource to delete </param>
public DeleteActivityOptions(string pathWorkspaceSid, string pathSid)
{
PathWorkspaceSid = pathWorkspaceSid;
PathSid = pathSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
return p;
}
}
/// <summary>
/// ReadActivityOptions
/// </summary>
public class ReadActivityOptions : ReadOptions<ActivityResource>
{
/// <summary>
/// The SID of the Workspace with the Activity resources to read
/// </summary>
public string PathWorkspaceSid { get; }
/// <summary>
/// The friendly_name of the Activity resources to read
/// </summary>
public string FriendlyName { get; set; }
/// <summary>
/// Whether to return activities that are available or unavailable
/// </summary>
public string Available { get; set; }
/// <summary>
/// Construct a new ReadActivityOptions
/// </summary>
/// <param name="pathWorkspaceSid"> The SID of the Workspace with the Activity resources to read </param>
public ReadActivityOptions(string pathWorkspaceSid)
{
PathWorkspaceSid = pathWorkspaceSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public override List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (FriendlyName != null)
{
p.Add(new KeyValuePair<string, string>("FriendlyName", FriendlyName));
}
if (Available != null)
{
p.Add(new KeyValuePair<string, string>("Available", Available));
}
if (PageSize != null)
{
p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString()));
}
return p;
}
}
/// <summary>
/// CreateActivityOptions
/// </summary>
public class CreateActivityOptions : IOptions<ActivityResource>
{
/// <summary>
/// The SID of the Workspace that the new Activity belongs to
/// </summary>
public string PathWorkspaceSid { get; }
/// <summary>
/// A string to describe the Activity resource
/// </summary>
public string FriendlyName { get; }
/// <summary>
/// Whether the Worker should be eligible to receive a Task when it occupies the Activity
/// </summary>
public bool? Available { get; set; }
/// <summary>
/// Construct a new CreateActivityOptions
/// </summary>
/// <param name="pathWorkspaceSid"> The SID of the Workspace that the new Activity belongs to </param>
/// <param name="friendlyName"> A string to describe the Activity resource </param>
public CreateActivityOptions(string pathWorkspaceSid, string friendlyName)
{
PathWorkspaceSid = pathWorkspaceSid;
FriendlyName = friendlyName;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (FriendlyName != null)
{
p.Add(new KeyValuePair<string, string>("FriendlyName", FriendlyName));
}
if (Available != null)
{
p.Add(new KeyValuePair<string, string>("Available", Available.Value.ToString().ToLower()));
}
return p;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
**
**
** Purpose: Encapsulate access to a public/private key pair
** used to sign strong name assemblies.
**
**
===========================================================*/
namespace System.Reflection
{
using System;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security;
using System.Security.Permissions;
using System.Runtime.Versioning;
using Microsoft.Win32;
using System.Diagnostics.Contracts;
#if !FEATURE_CORECLR
using Microsoft.Runtime.Hosting;
#endif
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class StrongNameKeyPair : IDeserializationCallback, ISerializable
{
private bool _keyPairExported;
private byte[] _keyPairArray;
private String _keyPairContainer;
private byte[] _publicKey;
#if !FEATURE_CORECLR
// Build key pair from file.
[System.Security.SecuritySafeCritical] // auto-generated
#pragma warning disable 618
[SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.UnmanagedCode)]
#pragma warning restore 618
public StrongNameKeyPair(FileStream keyPairFile)
{
if (keyPairFile == null)
throw new ArgumentNullException("keyPairFile");
Contract.EndContractBlock();
int length = (int)keyPairFile.Length;
_keyPairArray = new byte[length];
keyPairFile.Read(_keyPairArray, 0, length);
_keyPairExported = true;
}
#endif// FEATURE_CORECLR
// Build key pair from byte array in memory.
[System.Security.SecuritySafeCritical] // auto-generated
#pragma warning disable 618
[SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.UnmanagedCode)]
#pragma warning restore 618
public StrongNameKeyPair(byte[] keyPairArray)
{
if (keyPairArray == null)
throw new ArgumentNullException("keyPairArray");
Contract.EndContractBlock();
_keyPairArray = new byte[keyPairArray.Length];
Array.Copy(keyPairArray, _keyPairArray, keyPairArray.Length);
_keyPairExported = true;
}
[System.Security.SecuritySafeCritical] // auto-generated
#pragma warning disable 618
[SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.UnmanagedCode)]
#pragma warning restore 618
protected StrongNameKeyPair (SerializationInfo info, StreamingContext context) {
_keyPairExported = (bool) info.GetValue("_keyPairExported", typeof(bool));
_keyPairArray = (byte[]) info.GetValue("_keyPairArray", typeof(byte[]));
_keyPairContainer = (string) info.GetValue("_keyPairContainer", typeof(string));
_publicKey = (byte[]) info.GetValue("_publicKey", typeof(byte[]));
}
#if! FEATURE_CORECLR
// Reference key pair in named key container.
[System.Security.SecuritySafeCritical] // auto-generated
#pragma warning disable 618
[SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.UnmanagedCode)]
#pragma warning restore 618
public StrongNameKeyPair(String keyPairContainer)
{
if (keyPairContainer == null)
throw new ArgumentNullException("keyPairContainer");
Contract.EndContractBlock();
_keyPairContainer = keyPairContainer;
_keyPairExported = false;
}
// Get the public portion of the key pair.
public byte[] PublicKey
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
if (_publicKey == null)
{
_publicKey = ComputePublicKey();
}
byte[] publicKey = new byte[_publicKey.Length];
Array.Copy(_publicKey, publicKey, _publicKey.Length);
return publicKey;
}
}
[System.Security.SecurityCritical] // auto-generated
private unsafe byte[] ComputePublicKey()
{
byte[] publicKey = null;
// Make sure pbPublicKey is not leaked with async exceptions
RuntimeHelpers.PrepareConstrainedRegions();
try {
}
finally
{
IntPtr pbPublicKey = IntPtr.Zero;
int cbPublicKey = 0;
try
{
bool result;
if (_keyPairExported)
{
result = StrongNameHelpers.StrongNameGetPublicKey(null, _keyPairArray, _keyPairArray.Length,
out pbPublicKey, out cbPublicKey);
}
else
{
result = StrongNameHelpers.StrongNameGetPublicKey(_keyPairContainer, null, 0,
out pbPublicKey, out cbPublicKey);
}
if (!result)
throw new ArgumentException(Environment.GetResourceString("Argument_StrongNameGetPublicKey"));
publicKey = new byte[cbPublicKey];
Buffer.Memcpy(publicKey, 0, (byte*)(pbPublicKey.ToPointer()), 0, cbPublicKey);
}
finally
{
if (pbPublicKey != IntPtr.Zero)
StrongNameHelpers.StrongNameFreeBuffer(pbPublicKey);
}
}
return publicKey;
}
// Internal routine used to retrieve key pair info from unmanaged code.
private bool GetKeyPair(out Object arrayOrContainer)
{
arrayOrContainer = _keyPairExported ? (Object)_keyPairArray : (Object)_keyPairContainer;
return _keyPairExported;
}
#else
public StrongNameKeyPair(String keyPairContainer)
{
throw new PlatformNotSupportedException();
}
public byte[] PublicKey
{
get
{
throw new PlatformNotSupportedException();
}
}
#endif// FEATURE_CORECLR
/// <internalonly/>
[System.Security.SecurityCritical]
void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context) {
info.AddValue("_keyPairExported", _keyPairExported);
info.AddValue("_keyPairArray", _keyPairArray);
info.AddValue("_keyPairContainer", _keyPairContainer);
info.AddValue("_publicKey", _publicKey);
}
/// <internalonly/>
void IDeserializationCallback.OnDeserialization (Object sender) {}
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/, 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 Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using Aurora.Framework;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
namespace Aurora.Framework
{
public interface IGroupsServicesConnector
{
UUID CreateGroup(UUID RequestingAgentID, string name, string charter, bool showInList, UUID insigniaID,
int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish, UUID founderID);
void UpdateGroup(UUID RequestingAgentID, UUID groupID, string charter, bool showInList, UUID insigniaID,
int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish);
GroupRecord GetGroupRecord(UUID RequestingAgentID, UUID GroupID, string GroupName);
GroupProfileData GetGroupProfile(UUID RequestingAgentID, UUID GroupID);
List<DirGroupsReplyData> FindGroups(UUID RequestingAgentID, string search, int queryStart, uint queryFlags);
List<GroupMembersData> GetGroupMembers(UUID RequestingAgentID, UUID GroupID);
void AddGroupRole(UUID RequestingAgentID, UUID groupID, UUID roleID, string name, string description,
string title, ulong powers);
void UpdateGroupRole(UUID RequestingAgentID, UUID groupID, UUID roleID, string name, string description,
string title, ulong powers);
void RemoveGroupRole(UUID RequestingAgentID, UUID groupID, UUID roleID);
List<GroupRolesData> GetGroupRoles(UUID RequestingAgentID, UUID GroupID);
List<GroupRoleMembersData> GetGroupRoleMembers(UUID RequestingAgentID, UUID GroupID);
void AddAgentToGroup(UUID RequestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID);
bool RemoveAgentFromGroup(UUID RequestingAgentID, UUID AgentID, UUID GroupID);
void AddAgentToGroupInvite(UUID RequestingAgentID, UUID inviteID, UUID groupID, UUID roleID,
UUID agentIDFromAgentName, string FromAgentName);
GroupInviteInfo GetAgentToGroupInvite(UUID RequestingAgentID, UUID inviteID);
void RemoveAgentToGroupInvite(UUID RequestingAgentID, UUID inviteID);
void AddAgentToGroupRole(UUID RequestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID);
void RemoveAgentFromGroupRole(UUID RequestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID);
List<GroupRolesData> GetAgentGroupRoles(UUID RequestingAgentID, UUID AgentID, UUID GroupID);
string SetAgentActiveGroup(UUID RequestingAgentID, UUID AgentID, UUID GroupID);
GroupMembershipData GetAgentActiveMembership(UUID RequestingAgentID, UUID AgentID);
string SetAgentActiveGroupRole(UUID RequestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID);
void SetAgentGroupInfo(UUID RequestingAgentID, UUID AgentID, UUID GroupID, bool AcceptNotices,
bool ListInProfile);
GroupMembershipData GetAgentGroupMembership(UUID RequestingAgentID, UUID AgentID, UUID GroupID);
List<GroupMembershipData> GetAgentGroupMemberships(UUID RequestingAgentID, UUID AgentID);
void AddGroupNotice(UUID RequestingAgentID, UUID groupID, UUID noticeID, string fromName, string subject,
string message, UUID ItemID, int AssetType, string ItemName);
GroupNoticeInfo GetGroupNotice(UUID RequestingAgentID, UUID noticeID);
List<GroupNoticeData> GetGroupNotices(UUID RequestingAgentID, UUID GroupID);
List<GroupInviteInfo> GetGroupInvites(UUID requestingAgentID);
void AddGroupProposal(UUID agentID, GroupProposalInfo info);
bool CreateSession(ChatSession chatSession);
void AddMemberToGroup(ChatSessionMember chatSessionMember, UUID GroupID);
ChatSession GetSession(UUID sessionid);
ChatSessionMember FindMember(UUID sessionid, UUID Agent);
void RemoveSession(UUID sessionid);
List<GroupTitlesData> GetGroupTitles(UUID agentID, UUID groupID);
List<GroupProposalInfo> GetActiveProposals(UUID agentID, UUID groupID);
List<GroupProposalInfo> GetInactiveProposals(UUID agentID, UUID groupID);
void VoteOnActiveProposals(UUID agentID, UUID groupID, UUID proposalID, string vote);
}
/// <summary>
/// Internal class for chat sessions
/// </summary>
public class ChatSession
{
public List<ChatSessionMember> Members;
public string Name;
public UUID SessionID;
}
//Pulled from OpenMetaverse
// Summary:
// Struct representing a member of a group chat session and their settings
public class ChatSessionMember
{
// Summary:
// The OpenMetaverse.UUID of the Avatar
public UUID AvatarKey;
//
// Summary:
// True if user has voice chat enabled
public bool CanVoiceChat;
public bool HasBeenAdded;
//
// Summary:
// True of Avatar has moderator abilities
public bool IsModerator;
//
// Summary:
// True if a moderator has muted this avatars chat
public bool MuteText;
//
// Summary:
// True if a moderator has muted this avatars voice
public bool MuteVoice;
//
// Summary:
// True if they have been requested to join the session
}
public class GroupInviteInfo : IDataTransferable
{
public UUID AgentID = UUID.Zero;
public string FromAgentName = "";
public UUID GroupID = UUID.Zero;
public UUID InviteID = UUID.Zero;
public UUID RoleID = UUID.Zero;
public GroupInviteInfo()
{
}
public GroupInviteInfo(Dictionary<string, object> values)
{
FromKVP(values);
}
public override Dictionary<string, object> ToKVP()
{
Dictionary<string, object> values = new Dictionary<string, object>();
values["GroupID"] = GroupID;
values["RoleID"] = RoleID;
values["AgentID"] = AgentID;
values["InviteID"] = InviteID;
values["FromAgentName"] = FromAgentName;
return values;
}
public override void FromKVP(Dictionary<string, object> values)
{
GroupID = UUID.Parse(values["GroupID"].ToString());
RoleID = UUID.Parse(values["RoleID"].ToString());
AgentID = UUID.Parse(values["AgentID"].ToString());
InviteID = UUID.Parse(values["InviteID"].ToString());
FromAgentName = values["FromAgentName"].ToString();
}
public override OSDMap ToOSD()
{
OSDMap values = new OSDMap();
values["GroupID"] = GroupID;
values["RoleID"] = RoleID;
values["AgentID"] = AgentID;
values["InviteID"] = InviteID;
values["FromAgentName"] = FromAgentName;
return values;
}
public override void FromOSD(OSDMap values)
{
GroupID = values["GroupID"];
RoleID = values["RoleID"];
AgentID = values["AgentID"];
InviteID = values["InviteID"];
FromAgentName = values["FromAgentName"];
}
}
public class GroupNoticeInfo : IDataTransferable
{
public byte[] BinaryBucket = new byte[0];
public UUID GroupID = UUID.Zero;
public string Message = string.Empty;
public GroupNoticeData noticeData = new GroupNoticeData();
public GroupNoticeInfo()
{
}
public GroupNoticeInfo(Dictionary<string, object> values)
{
FromKVP(values);
}
public override void FromKVP(Dictionary<string, object> values)
{
noticeData = new GroupNoticeData(values["noticeData"] as Dictionary<string, object>);
GroupID = UUID.Parse(values["GroupID"].ToString());
Message = values["Message"].ToString();
BinaryBucket = Utils.HexStringToBytes(values["BinaryBucket"].ToString(), true);
}
public override Dictionary<string, object> ToKVP()
{
Dictionary<string, object> values = new Dictionary<string, object>();
values["noticeData"] = noticeData.ToKVP();
values["GroupID"] = GroupID;
values["Message"] = Message;
values["BinaryBucket"] = Utils.BytesToHexString(BinaryBucket, "BinaryBucket");
return values;
}
public override OSDMap ToOSD()
{
OSDMap values = new OSDMap();
values["noticeData"] = noticeData.ToOSD();
values["GroupID"] = GroupID;
values["Message"] = Message;
values["BinaryBucket"] = BinaryBucket;
return values;
}
public override void FromOSD(OSDMap values)
{
noticeData = new GroupNoticeData();
noticeData.FromOSD((OSDMap)values["noticeData"]);
GroupID = values["GroupID"];
Message = values["Message"];
BinaryBucket = values["BinaryBucket"];
}
}
public class GroupProposalInfo : IDataTransferable
{
public int Duration;
public UUID GroupID = UUID.Zero;
public float Majority;
public int Quorum;
public UUID Session = UUID.Zero;
public string Text = string.Empty;
public UUID BallotInitiator = UUID.Zero;
public DateTime Created = DateTime.Now;
public DateTime Ending = DateTime.Now;
public UUID VoteID = UUID.Random();
/// <summary>
/// Only set when a user is calling to find out proposal info, it is what said user voted
/// </summary>
public string VoteCast = "";
/// <summary>
/// The result of the proposal (success or failure)
/// </summary>
public bool Result = false;
/// <summary>
/// The number of votes cast (so far if the proposal is still open)
/// </summary>
public int NumVotes = 0;
/// <summary>
/// If this is false, the result of the proposal has not been calculated and should be when it is retrieved next
/// </summary>
public bool HasCalculatedResult = false;
public override void FromOSD(OSDMap map)
{
GroupID = map["GroupID"].AsUUID();
Duration = map["Duration"].AsInteger();
Majority = (float) map["Majority"].AsReal();
Text = map["Text"].AsString();
Quorum = map["Quorum"].AsInteger();
Session = map["Session"].AsUUID();
BallotInitiator = map["BallotInitiator"];
Created = map["Created"];
Ending = map["Ending"];
VoteID = map["VoteID"];
VoteCast = map["VoteCast"];
Result = map["Result"];
NumVotes = map["NumVotes"];
HasCalculatedResult = map["HasCalculatedResult"];
}
public override OSDMap ToOSD()
{
OSDMap map = new OSDMap();
map["GroupID"] = GroupID;
map["Duration"] = Duration;
map["Majority"] = Majority;
map["Text"] = Text;
map["Quorum"] = Quorum;
map["Session"] = Session;
map["BallotInitiator"] = BallotInitiator;
map["Created"] = Created;
map["Ending"] = Ending;
map["VoteID"] = VoteID;
map["VoteCast"] = VoteCast;
map["Result"] = Result;
map["NumVotes"] = NumVotes;
map["HasCalculatedResult"] = HasCalculatedResult;
return map;
}
public override void FromKVP(Dictionary<string, object> KVP)
{
FromOSD(Util.DictionaryToOSD(KVP));
}
public override Dictionary<string, object> ToKVP()
{
return Util.OSDToDictionary(ToOSD());
}
}
}
| |
using System;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace QarnotSDK {
/// <summary>
/// This class manages pools life cycle: submission, monitor, delete.
/// </summary>
public abstract partial class AQPool {
/// <summary>
/// Reference to the api connection.
/// </summary>
protected Connection _api;
/// <summary>
/// The pool resource uri.
/// </summary>
protected string _uri = null;
internal PoolApi _poolApi { get; set; }
/// <summary>
/// The inner Connection object.
/// </summary>
[InternalDataApiName(IsFilterable=false, IsSelectable=false)]
public virtual Connection Connection { get { return _api; } }
/// <summary>
/// The pool unique identifier. The Uuid is generated by the Api when the pool is submitted.
/// </summary>
[InternalDataApiName(Name="Uuid")]
public virtual Guid Uuid { get { return _poolApi.Uuid; } }
internal AQPool() { }
internal AQPool(Connection qapi, PoolApi poolApi) {
_api = qapi;
_uri = "pools/" + poolApi.Uuid.ToString();
_poolApi = poolApi;
}
internal virtual async Task<AQPool> InitializeAsync(Connection qapi, PoolApi poolApi) {
_api = qapi;
_uri = "pools/" + poolApi.Uuid.ToString();
_poolApi = poolApi;
return await Task.FromResult<AQPool>(this);
}
#region public methods
/// <summary>
/// Delete the pool.
/// </summary>
/// <param name="cancellationToken">Optional token to cancel the request.</param>
/// <returns></returns>
[Obsolete("use CloseAsync")]
public virtual async Task StopAsync(CancellationToken cancellationToken = default(CancellationToken)) {
if (_api.IsReadOnly) throw new Exception("Can't stop pools, this connection is configured in read-only mode");
using (var response = await _api._client.DeleteAsync(_uri, cancellationToken))
await Utils.LookForErrorAndThrowAsync(_api._client, response, cancellationToken);
}
/// <summary>
/// Close the pool.
/// </summary>
/// <param name="cancellationToken">Optional token to cancel the request.</param>
/// <returns></returns>
public virtual async Task CloseAsync(CancellationToken cancellationToken = default(CancellationToken)) {
if (_api.IsReadOnly) throw new Exception("Can't close pools, this connection is configured in read-only mode");
using (var response = await _api._client.PostAsync(_uri + "/close", null, cancellationToken))
await Utils.LookForErrorAndThrowAsync(_api._client, response, cancellationToken);
}
/// <summary>
/// Delete the pool. If the pool is running, the task is aborted and deleted.
/// </summary>
/// <param name="cancellationToken">Optional token to cancel the request.</param>
/// <param name="failIfDoesntExist">If set to false and the pool doesn't exist, no exception is thrown. Default is true.</param>
/// <param name="purgeResources">Boolean to trigger all resource storages deletion. Default is false.</param>
/// <returns></returns>
public abstract Task DeleteAsync(CancellationToken cancellationToken, bool failIfDoesntExist = false, bool purgeResources=false);
/// <summary>
/// Delete the pool. If the pool is running, the task is aborted and deleted.
/// </summary>
/// <param name="failIfDoesntExist">If set to false and the pool doesn't exist, no exception is thrown. Default is true.</param>
/// <param name="purgeResources">Boolean to trigger all resource storages deletion. Default is false.</param>
/// <returns></returns>
public virtual async Task DeleteAsync(bool failIfDoesntExist = false, bool purgeResources=false)
=> await DeleteAsync(default(CancellationToken), failIfDoesntExist, purgeResources);
#endregion
/// <summary>
/// Request made on a running pool to re-sync the resource buckets to the compute nodes.
/// 1 - Upload new files on your resource bucket,
/// 2 - Call this method,
/// 3 - The new files will appear on all the compute nodes in the $DOCKER_WORKDIR folder
/// Note: There is no way to know when the files are effectively transfered. This information is available on the compute node only.
/// Note: The update is additive only: files deleted from the bucket will NOT be deleted from the pool's resources directory.
/// </summary>
/// <param name="cancellationToken">Optional token to cancel the request.</param>
/// <returns></returns>
public async Task UpdateResourcesAsync(CancellationToken cancellationToken = default(CancellationToken))
{
if (_api.IsReadOnly)
{
throw new Exception("Can't update resources, this connection is configured in read-only mode");
}
var reqMsg = new HttpRequestMessage(new HttpMethod("PATCH"), _uri);
using (var response = await _api._client.SendAsync(reqMsg, cancellationToken))
{
await Utils.LookForErrorAndThrowAsync(_api._client, response, cancellationToken);
}
}
#region stdin/stdout
/// <summary>
/// Copies the full standard output to the given stream.
/// Note: the standard output will rotate if it's too large.
/// </summary>
/// <param name="destinationStream">The destination stream.</param>
/// <param name="cancellationToken">Optional token to cancel the request.</param>
/// <returns></returns>
public virtual async Task CopyStdoutToAsync(Stream destinationStream, CancellationToken cancellationToken = default(CancellationToken))
{
using (var response = await _api._client.GetAsync(_uri + "/stdout", cancellationToken))
{
await Utils.LookForErrorAndThrowAsync(_api._client, response, cancellationToken);
await response.Content.CopyToAsync(destinationStream);
}
}
/// <summary>
/// Copies the full standard error to the given stream.
/// Note: the standard error will rotate if it's too large.
/// </summary>
/// <param name="destinationStream">The destination stream.</param>
/// <param name="cancellationToken">Optional token to cancel the request.</param>
/// <returns></returns>
public virtual async Task CopyStderrToAsync(Stream destinationStream, CancellationToken cancellationToken = default(CancellationToken))
{
using (var response = await _api._client.GetAsync(_uri + "/stderr", cancellationToken))
{
await Utils.LookForErrorAndThrowAsync(_api._client, response, cancellationToken);
await response.Content.CopyToAsync(destinationStream);
}
}
/// <summary>
/// Copies the fresh new standard output since the last call to the given stream.
/// </summary>
/// <param name="destinationStream">The destination stream.</param>
/// <param name="cancellationToken">Optional token to cancel the request.</param>
/// <returns></returns>
public virtual async Task CopyFreshStdoutToAsync(Stream destinationStream, CancellationToken cancellationToken = default(CancellationToken))
{
if (_api.IsReadOnly) throw new Exception("Can't retrieve fresh standard output, this connection is configured in read-only mode");
using (var response = await _api._client.PostAsync(_uri + "/stdout", null, cancellationToken))
{
await Utils.LookForErrorAndThrowAsync(_api._client, response, cancellationToken);
await response.Content.CopyToAsync(destinationStream);
}
}
/// <summary>
/// Copies the fresh new standard error since the last call to the given stream.
/// </summary>
/// <param name="destinationStream">The destination stream.</param>
/// <param name="cancellationToken">Optional token to cancel the request.</param>
/// <returns></returns>
public virtual async Task CopyFreshStderrToAsync(Stream destinationStream, CancellationToken cancellationToken = default(CancellationToken))
{
if (_api.IsReadOnly) throw new Exception("Can't retrieve fresh standard error, this connection is configured in read-only mode");
using (var response = await _api._client.PostAsync(_uri + "/stderr", null, cancellationToken))
{
await Utils.LookForErrorAndThrowAsync(_api._client, response, cancellationToken);
await response.Content.CopyToAsync(destinationStream);
}
}
/// <summary>
/// Returns the full standard output.
/// Note: the standard output will rotate if it's too large.
/// </summary>
/// <param name="cancellationToken">Optional token to cancel the request.</param>
/// <returns>The pool standard output.</returns>
public virtual async Task<string> StdoutAsync(CancellationToken cancellationToken = default(CancellationToken))
{
using (MemoryStream ms = new MemoryStream())
{
await CopyStdoutToAsync(ms, cancellationToken);
ms.Position = 0;
using (var reader = new StreamReader(ms))
{
return await reader.ReadToEndAsync();
}
}
}
/// <summary>
/// Return the full standard error.
/// Note: the standard error will rotate if it's too large.
/// </summary>
/// <param name="cancellationToken">Optional token to cancel the request.</param>
/// <returns>The pool standard error.</returns>
public virtual async Task<string> StderrAsync(CancellationToken cancellationToken = default(CancellationToken))
{
using (MemoryStream ms = new MemoryStream())
{
await CopyStderrToAsync(ms, cancellationToken);
ms.Position = 0;
using (var reader = new StreamReader(ms))
{
return await reader.ReadToEndAsync();
}
}
}
/// <summary>
/// Returns the fresh new standard output since the last call.
/// </summary>
/// <param name="cancellationToken">Optional token to cancel the request.</param>
/// <returns>The pool fresh standard output.</returns>
public virtual async Task<string> FreshStdoutAsync(CancellationToken cancellationToken = default(CancellationToken))
{
using (MemoryStream ms = new MemoryStream())
{
await CopyFreshStdoutToAsync(ms, cancellationToken);
ms.Position = 0;
using (var reader = new StreamReader(ms))
{
return await reader.ReadToEndAsync();
}
}
}
/// <summary>
/// Returns the fresh new standard error since the last call.
/// </summary>
/// /// <param name="cancellationToken">Optional token to cancel the request.</param>
/// <returns>The pool fresh standard error.</returns>
public virtual async Task<string> FreshStderrAsync(CancellationToken cancellationToken = default(CancellationToken))
{
using (MemoryStream ms = new MemoryStream())
{
await CopyFreshStderrToAsync(ms, cancellationToken);
ms.Position = 0;
using (var reader = new StreamReader(ms))
{
return await reader.ReadToEndAsync();
}
}
}
#endregion
}
}
| |
// 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.
//
// This file was autogenerated by a tool.
// Do not modify it.
//
namespace Microsoft.Azure.Batch
{
using Models = Microsoft.Azure.Batch.Protocol.Models;
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// A file to be downloaded to a compute node from Azure Blob Storage, such as task executables and task input data files.
/// </summary>
public partial class ResourceFile : ITransportObjectProvider<Models.ResourceFile>, IPropertyMetadata
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="ResourceFile"/> class.
/// </summary>
/// <param name='httpUrl'>The URL of the file to download.</param>
/// <param name='fileMode'>The file permission mode attribute in octal format.</param>
/// <param name='filePath'>The location on the compute node to which to download the file(s), relative to the task's working directory.</param>
/// <param name='storageContainerUrl'>The URL of the blob container within Azure Blob Storage.</param>
/// <param name='autoStorageContainerName'>The storage container name in the auto storage account.</param>
/// <param name='blobPrefix'>The blob prefix to use when downloading blobs from an Azure Storage container. Only the blobs whose names begin
/// with the specified prefix will be downloaded.</param>
internal ResourceFile(
string httpUrl = default(string),
string fileMode = default(string),
string filePath = default(string),
string storageContainerUrl = default(string),
string autoStorageContainerName = default(string),
string blobPrefix = default(string))
{
this.HttpUrl = httpUrl;
this.FileMode = fileMode;
this.FilePath = filePath;
this.StorageContainerUrl = storageContainerUrl;
this.AutoStorageContainerName = autoStorageContainerName;
this.BlobPrefix = blobPrefix;
}
internal ResourceFile(Models.ResourceFile protocolObject)
{
this.AutoStorageContainerName = protocolObject.AutoStorageContainerName;
this.BlobPrefix = protocolObject.BlobPrefix;
this.FileMode = protocolObject.FileMode;
this.FilePath = protocolObject.FilePath;
this.HttpUrl = protocolObject.HttpUrl;
this.StorageContainerUrl = protocolObject.StorageContainerUrl;
}
#endregion Constructors
#region ResourceFile
/// <summary>
/// Gets the storage container name in the auto storage account.
/// </summary>
public string AutoStorageContainerName { get; }
/// <summary>
/// Gets the blob prefix to use when downloading blobs from an Azure Storage container. Only the blobs whose names
/// begin with the specified prefix will be downloaded.
/// </summary>
/// <remarks>
/// This property is valid only when <see cref="AutoStorageContainerName" /> or <see cref="StorageContainerUrl" />
/// is used. This prefix can be a partial filename or a subdirectory. If a prefix is not specified, all the files
/// in the container will be downloaded.
/// </remarks>
public string BlobPrefix { get; }
/// <summary>
/// Gets the file permission mode attribute in octal format.
/// </summary>
/// <remarks>
/// <para>This property is applicable only if the resource file is downloaded to a Linux node. This property will
/// be ignored if it is specified for a <see cref="ResourceFile"/> which will be downloaded to a Windows node. If
/// this property is not specified for a Linux node, then the default value is 0770.</para>
/// </remarks>
public string FileMode { get; }
/// <summary>
/// Gets the location on the compute node to which to download the file(s), relative to the task's working directory.
/// </summary>
/// <remarks>
/// If the <see cref="HttpUrl" /> property is specified, this is required and describes the path which the file will
/// be downloaded to, including the filename. Otherwise, if the <see cref="AutoStorageContainerName" /> or <see cref="StorageContainerUrl"
/// /> property is specified, this is optional and is the directory to download the files to. In the case where this
/// is used as a directory, any directory structure already associated with the input data will be retained in full
/// and appended to the specified <see cref="FilePath" /> directory. The specified relative path cannot break out
/// of the task's working directory (for example by using '..').
/// </remarks>
public string FilePath { get; }
/// <summary>
/// Gets the URL of the file to download.
/// </summary>
/// <remarks>
/// If the URL is Azure Blob Storage, it must be readable using anonymous access; that is, the Batch service does
/// not present any credentials when downloading the blob. There are two ways to get such a URL for a blob in Azure
/// storage: include a Shared Access Signature (SAS) granting read permissions on the blob, or set the ACL for the
/// blob or its container to allow public access.
/// </remarks>
public string HttpUrl { get; }
/// <summary>
/// Gets the URL of the blob container within Azure Blob Storage.
/// </summary>
/// <remarks>
/// This URL must be readable and listable using anonymous access; that is, the Batch service does not present any
/// credentials when downloading blobs from the container. There are two ways to get such a URL for a container in
/// Azure storage: include a Shared Access Signature (SAS) granting read permissions on the container, or set the
/// ACL for the container to allow public access.
/// </remarks>
public string StorageContainerUrl { get; }
#endregion // ResourceFile
#region IPropertyMetadata
bool IModifiable.HasBeenModified
{
//This class is compile time readonly so it cannot have been modified
get { return false; }
}
bool IReadOnly.IsReadOnly
{
get { return true; }
set
{
// This class is compile time readonly already
}
}
#endregion // IPropertyMetadata
#region Internal/private methods
/// <summary>
/// Return a protocol object of the requested type.
/// </summary>
/// <returns>The protocol object of the requested type.</returns>
Models.ResourceFile ITransportObjectProvider<Models.ResourceFile>.GetTransportObject()
{
Models.ResourceFile result = new Models.ResourceFile()
{
AutoStorageContainerName = this.AutoStorageContainerName,
BlobPrefix = this.BlobPrefix,
FileMode = this.FileMode,
FilePath = this.FilePath,
HttpUrl = this.HttpUrl,
StorageContainerUrl = this.StorageContainerUrl,
};
return result;
}
/// <summary>
/// Converts a collection of protocol layer objects to object layer collection objects.
/// </summary>
internal static IList<ResourceFile> ConvertFromProtocolCollection(IEnumerable<Models.ResourceFile> protoCollection)
{
ConcurrentChangeTrackedModifiableList<ResourceFile> converted = UtilitiesInternal.CollectionToThreadSafeCollectionIModifiable(
items: protoCollection,
objectCreationFunc: o => new ResourceFile(o));
return converted;
}
/// <summary>
/// Converts a collection of protocol layer objects to object layer collection objects, in a frozen state.
/// </summary>
internal static IList<ResourceFile> ConvertFromProtocolCollectionAndFreeze(IEnumerable<Models.ResourceFile> protoCollection)
{
ConcurrentChangeTrackedModifiableList<ResourceFile> converted = UtilitiesInternal.CollectionToThreadSafeCollectionIModifiable(
items: protoCollection,
objectCreationFunc: o => new ResourceFile(o).Freeze());
converted = UtilitiesInternal.CreateObjectWithNullCheck(converted, o => o.Freeze());
return converted;
}
/// <summary>
/// Converts a collection of protocol layer objects to object layer collection objects, with each object marked readonly
/// and returned as a readonly collection.
/// </summary>
internal static IReadOnlyList<ResourceFile> ConvertFromProtocolCollectionReadOnly(IEnumerable<Models.ResourceFile> protoCollection)
{
IReadOnlyList<ResourceFile> converted =
UtilitiesInternal.CreateObjectWithNullCheck(
UtilitiesInternal.CollectionToNonThreadSafeCollection(
items: protoCollection,
objectCreationFunc: o => new ResourceFile(o).Freeze()), o => o.AsReadOnly());
return converted;
}
#endregion // Internal/private methods
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Xml;
using System.Xml.Serialization;
using AgenaTrader.API;
using AgenaTrader.Custom;
using AgenaTrader.Plugins;
using AgenaTrader.Helper;
/// <summary>
/// Version: 1.3.2
/// -------------------------------------------------------------------------
/// Simon Pucher 2017
/// -------------------------------------------------------------------------
/// ****** Important ******
/// To compile this script without any error you also need access to the utility indicator to use global source code elements.
/// You will find this script on GitHub: https://raw.githubusercontent.com/simonpucher/AgenaTrader/master/Utilities/GlobalUtilities_Utility.cs
/// -------------------------------------------------------------------------
/// Namespace holds all indicators and is required. Do not change it.
/// </summary>
namespace AgenaTrader.UserCode
{
[Category("Script-Trading")]
[Description("Moving Averages Condition.")]
[IsEntryAttribute(true)]
[IsStopAttribute(false)]
[IsTargetAttribute(false)]
[OverrulePreviousStopPrice(false)]
public class Moving_Averages_Condition : UserScriptedCondition
{
#region Variables
private int _candles = 14;
private Stack<DateTime> lastsignals;
private Color _plot0color = Const.DefaultIndicatorColor;
private int _plot0width = Const.DefaultLineWidth;
private DashStyle _plot0dashstyle = Const.DefaultIndicatorDashStyle;
private Color _plot1color = Const.DefaultIndicatorColor_GreyedOut;
private int _plot1width = Const.DefaultLineWidth;
private DashStyle _plot1dashstyle = Const.DefaultIndicatorDashStyle;
private int _ma_long = 200;
private int _ma_medium = 100;
private int _ma_short = 50;
private Color _signalcolor = Color.Transparent;
#endregion
protected override void OnInit()
{
IsEntry = true;
IsStop = false;
IsTarget = false;
Add(new OutputDescriptor(new Pen(this.Plot0Color, this.Plot0Width), OutputSerieDrawStyle.Line, "Occurred"));
Add(new OutputDescriptor(new Pen(this.Plot0Color, this.Plot1Width), OutputSerieDrawStyle.Line, "Entry"));
IsOverlay = false;
CalculateOnClosedBar = true;
this.RequiredBarsCount = 200;
}
protected override void OnCalculate()
{
//Reset color
_signalcolor = Color.Transparent;
if (ProcessingBarIndex == 0)
{
lastsignals = new Stack<DateTime>();
}
bool therewasasignal = false;
//if (Low[0] < SMA(200)[0] && SMA(50)[0] >= SMA(100)[0] && SMA(100)[0] >= SMA(200)[0] && Close[0] > SuperTrend(SuperTrendMAType.HMA, SuperTrendMode.ATR, 14, 2.618, 14).UpTrend[0])
//if (Low[0] < SMA(200)[0] && SMA(50)[0] >= SMA(100)[0] && Close[0] > SuperTrend(SuperTrendMAType.HMA, SuperTrendMode.ATR, 14, 2.618, 14).UpTrend[0])
//if (Low[0] < SMA(200)[0] && SMA(50)[0] >= SMA(100)[0] && Close[0] > SuperTrend(SuperTrendMAType.SMA, SuperTrendMode.ATR, 50, 2.618, 50).UpTrend[0])
if (Low[0] < SMA(this.MA_Long)[0] && SMA(this.MA_Short)[0] >= SMA(this.MA_Medium)[0]
&& Close[0] > SuperTrend(SuperTrendMAType.SMA, SuperTrendMode.ATR, 200, 2.618, 200).UpTrend[0])
{
therewasasignal = true;
}
double thevalue = 0;
if (therewasasignal)
{
thevalue = 1;
_signalcolor = Color.LightGreen;
AddChartArrowUp("ArrowLong_Entry" + +Bars[0].Time.Ticks, this.IsAutoAdjustableScale, 0, Bars[0].Low, Color.Green);
lastsignals.Push(Time[0]);
}
else
{
if (lastsignals != null && lastsignals.Count > 0 && lastsignals.Peek() >= Time[this.Candles - 1])
{
AddChartArrowUp("ArrowLong_Echo_Entry" + +Bars[0].Time.Ticks, this.IsAutoAdjustableScale, 0, Bars[0].Low, Color.LightGreen);
thevalue = 0.5;
_signalcolor = Color.Green;
}
}
Occurred.Set(thevalue);
PlotColors[0][0] = this.Plot0Color;
OutputDescriptors[0].PenStyle = this.Dash0Style;
OutputDescriptors[0].Pen.Width = this.Plot0Width;
PlotColors[1][0] = this.Plot1Color;
OutputDescriptors[1].PenStyle = this.Dash1Style;
OutputDescriptors[1].Pen.Width = this.Plot1Width;
}
public override string ToString()
{
return "Moving Averages (C)";
}
public override string DisplayName
{
get
{
return "Moving Averages (C)";
}
}
public override Color? GetSignalColor()
{
return _signalcolor;
}
#region Properties
[Browsable(false)]
[XmlIgnore()]
public DataSeries Occurred
{
get { return Outputs[0]; }
}
[Browsable(false)]
[XmlIgnore()]
public DataSeries Entry
{
get { return Outputs[1]; }
}
public override IList<DataSeries> GetEntries()
{
return new[]{Entry};
}
/// <summary>
/// </summary>
[Description("The period of the long Moving Average.")]
[InputParameter]
[DisplayName("Period MA Long")]
public int MA_Long
{
get { return _ma_long; }
set { _ma_long = value; }
}
/// <summary>
/// </summary>
[Description("The period of the medium Moving Average.")]
[InputParameter]
[DisplayName("Period MA Medium")]
public int MA_Medium
{
get { return _ma_medium; }
set { _ma_medium = value; }
}
/// <summary>
/// </summary>
[Description("The period of the short Moving Average.")]
[InputParameter]
[DisplayName("Period MA Short")]
public int MA_Short
{
get { return _ma_short; }
set { _ma_short = value; }
}
/// <summary>
/// </summary>
[Description("The script show a signal if the gap was during the last x candles.")]
[InputParameter]
[DisplayName("Candles")]
public int Candles
{
get { return _candles; }
set { _candles = value; }
}
/// <summary>
/// </summary>
[Description("Select Color for the indicator.")]
[Category("Plots")]
[DisplayName("Color")]
public Color Plot0Color
{
get { return _plot0color; }
set { _plot0color = value; }
}
// Serialize Color object
[Browsable(false)]
public string Plot0ColorSerialize
{
get { return SerializableColor.ToString(_plot0color); }
set { _plot0color = SerializableColor.FromString(value); }
}
/// <summary>
/// </summary>
[Description("Line width for indicator.")]
[Category("Plots")]
[DisplayName("Line width")]
public int Plot0Width
{
get { return _plot0width; }
set { _plot0width = Math.Max(1, value); }
}
/// <summary>
/// </summary>
[Description("DashStyle for indicator.")]
[Category("Plots")]
[DisplayName("DashStyle")]
public DashStyle Dash0Style
{
get { return _plot0dashstyle; }
set { _plot0dashstyle = value; }
}
/// <summary>
/// </summary>
[Description("Select color for the indicator.")]
[Category("Plots")]
[DisplayName("Color")]
public Color Plot1Color
{
get { return _plot1color; }
set { _plot1color = value; }
}
// Serialize Color object
[Browsable(false)]
public string Plot1ColorSerialize
{
get { return SerializableColor.ToString(_plot1color); }
set { _plot1color = SerializableColor.FromString(value); }
}
/// <summary>
/// </summary>
[Description("Line width for indicator.")]
[Category("Plots")]
[DisplayName("Line width")]
public int Plot1Width
{
get { return _plot1width; }
set { _plot1width = Math.Max(1, value); }
}
/// <summary>
/// </summary>
[Description("DashStyle for indicator.")]
[Category("Plots")]
[DisplayName("DashStyle")]
public DashStyle Dash1Style
{
get { return _plot1dashstyle; }
set { _plot1dashstyle = value; }
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Threading;
using System.Collections.Generic;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.ScriptEngine.Shared;
using OpenSim.Region.ScriptEngine.Shared.Api;
using log4net;
using LSL_Float = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat;
using LSL_Integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger;
using LSL_Key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
using LSL_List = OpenSim.Region.ScriptEngine.Shared.LSL_Types.list;
using LSL_Rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion;
using LSL_String = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
using LSL_Vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3;
namespace OpenSim.Region.ScriptEngine.Yengine
{
/****************************************************\
* This file contains routines called by scripts. *
\****************************************************/
public class XMRLSL_Api: LSL_Api
{
public AsyncCommandManager acm;
private XMRInstance inst;
public void InitXMRLSLApi(XMRInstance i)
{
acm = AsyncCommands;
inst = i;
}
protected override void ScriptSleep(int ms)
{
ms = (int)(ms * m_ScriptDelayFactor);
if (ms < 10)
return;
inst.Sleep(ms);
}
public override void llSleep(double sec)
{
inst.Sleep((int)(sec * 1000.0));
}
public override void llDie()
{
inst.Die();
}
/**
* @brief Seat avatar on prim.
* @param owner = true: owner of prim script is running in
* false: avatar that has given ANIMATION permission on the prim
* @returns 0: successful
* -1: no permission to animate
* -2: no av granted perms
* -3: av not in region
*/
/* engines should not have own API
public int xmrSeatAvatar (bool owner)
{
// Get avatar to be seated and make sure they have given us ANIMATION permission
UUID avuuid;
if (owner) {
avuuid = inst.m_Part.OwnerID;
} else {
if ((m_item.PermsMask & ScriptBaseClass.PERMISSION_TRIGGER_ANIMATION) == 0) {
return -1;
}
avuuid = m_item.PermsGranter;
}
if (avuuid == UUID.Zero) {
return -2;
}
ScenePresence presence = World.GetScenePresence (avuuid);
if (presence == null) {
return -3;
}
// remoteClient = not used by ScenePresence.HandleAgentRequestSit()
// agentID = not used by ScenePresence.HandleAgentRequestSit()
// targetID = UUID of prim to sit on
// offset = offset of sitting position
presence.HandleAgentRequestSit (null, UUID.Zero, m_host.UUID, OpenMetaverse.Vector3.Zero);
return 0;
}
*/
/**
* @brief llTeleportAgent() is broken in that if you pass it a landmark,
* it still subjects the position to spawn points, as it always
* calls RequestTeleportLocation() with TeleportFlags.ViaLocation.
* See llTeleportAgent() and CheckAndAdjustTelehub().
*
* @param agent = what agent to teleport
* @param landmark = inventory name or UUID of a landmark object
* @param lookat = looking direction after teleport
*/
/* engines should not have own API
public void xmrTeleportAgent2Landmark (string agent, string landmark, LSL_Vector lookat)
{
// find out about agent to be teleported
UUID agentId;
if (!UUID.TryParse (agent, out agentId)) throw new ApplicationException ("bad agent uuid");
ScenePresence presence = World.GetScenePresence (agentId);
if (presence == null) throw new ApplicationException ("agent not present in scene");
if (presence.IsNPC) throw new ApplicationException ("agent is an NPC");
if (presence.IsGod) throw new ApplicationException ("agent is a god");
// prim must be owned by land owner or prim must be attached to agent
if (m_host.ParentGroup.AttachmentPoint == 0) {
if (m_host.OwnerID != World.LandChannel.GetLandObject (presence.AbsolutePosition).LandData.OwnerID) {
throw new ApplicationException ("prim not owned by land's owner");
}
} else {
if (m_host.OwnerID != presence.UUID) throw new ApplicationException ("prim not attached to agent");
}
// find landmark in inventory or by UUID
UUID assetID = ScriptUtils.GetAssetIdFromKeyOrItemName (m_host, landmark);
if (assetID == UUID.Zero) throw new ApplicationException ("no such landmark");
// read it in and make sure it is a landmark
AssetBase lma = World.AssetService.Get (assetID.ToString ());
if ((lma == null) || (lma.Type != (sbyte)AssetType.Landmark)) throw new ApplicationException ("not a landmark");
// parse the record
AssetLandmark lm = new AssetLandmark (lma);
// the regionhandle (based on region's world X,Y) might be out of date
// re-read the handle so we can pass it to RequestTeleportLocation()
var region = World.GridService.GetRegionByUUID (World.RegionInfo.ScopeID, lm.RegionID);
if (region == null) throw new ApplicationException ("no such region");
// finally ready to teleport
World.RequestTeleportLocation (presence.ControllingClient,
region.RegionHandle,
lm.Position,
lookat,
(uint)TeleportFlags.ViaLandmark);
}
*/
/**
* @brief Allow any member of group given by config SetParcelMusicURLGroup to set music URL.
* Code modelled after llSetParcelMusicURL().
* @param newurl = new URL to set (or "" to leave it alone)
* @returns previous URL string
*/
/* engines should not have own API
public string xmrSetParcelMusicURLGroup (string newurl)
{
string groupname = m_ScriptEngine.Config.GetString ("SetParcelMusicURLGroup", "");
if (groupname == "") throw new ApplicationException ("no SetParcelMusicURLGroup config param set");
IGroupsModule igm = World.RequestModuleInterface<IGroupsModule> ();
if (igm == null) throw new ApplicationException ("no GroupsModule loaded");
GroupRecord grouprec = igm.GetGroupRecord (groupname);
if (grouprec == null) throw new ApplicationException ("no such group " + groupname);
GroupMembershipData gmd = igm.GetMembershipData (grouprec.GroupID, m_host.OwnerID);
if (gmd == null) throw new ApplicationException ("not a member of group " + groupname);
ILandObject land = World.LandChannel.GetLandObject (m_host.AbsolutePosition);
if (land == null) throw new ApplicationException ("no land at " + m_host.AbsolutePosition.ToString ());
string oldurl = land.GetMusicUrl ();
if (oldurl == null) oldurl = "";
if ((newurl != null) && (newurl != "")) land.SetMusicUrl (newurl);
return oldurl;
}
*/
}
public partial class XMRInstance
{
/**
* @brief The script is calling llReset().
* We throw an exception to unwind the script out to its main
* causing all the finally's to execute and it will also set
* eventCode = None to indicate event handler has completed.
*/
public void ApiReset()
{
ClearQueueExceptLinkMessages();
throw new ScriptResetException();
}
/**
* @brief The script is calling one of the llDetected...(int number)
* functions. Return corresponding DetectParams pointer.
*/
public DetectParams GetDetectParams(int number)
{
DetectParams dp = null;
if((number >= 0) && (m_DetectParams != null) && (number < m_DetectParams.Length))
dp = m_DetectParams[number];
return dp;
}
/**
* @brief Script is calling llDie, so flag the run loop to delete script
* once we are off the microthread stack, and throw an exception
* to unwind the stack asap.
*/
public void Die()
{
// llDie doesn't work in attachments!
if(m_Part.ParentGroup.IsAttachment || m_DetachQuantum > 0)
return;
throw new ScriptDieException();
}
/**
* @brief Called by script to sleep for the given number of milliseconds.
*/
public void Sleep(int ms)
{
lock(m_QueueLock)
{
// Say how long to sleep.
m_SleepUntil = DateTime.UtcNow + TimeSpan.FromMilliseconds(ms);
// Don't wake on any events.
m_SleepEventMask1 = 0;
m_SleepEventMask2 = 0;
}
// The compiler follows all calls to llSleep() with a call to CheckRun().
// So tell CheckRun() to suspend the microthread.
suspendOnCheckRunTemp = true;
}
/**
* Block script execution until an event is queued or a timeout is reached.
* @param timeout = maximum number of seconds to wait
* @param returnMask = if event is queued that matches these mask bits,
* the script is woken, that event is dequeued and
* returned to the caller. The event handler is not
* executed.
* @param backgroundMask = if any of these events are queued while waiting,
* execute their event handlers. When any such event
* handler exits, continue waiting for events or the
* timeout.
* @returns empty list: no event was queued that matched returnMask and the timeout was reached
* or a background event handler changed state (eg, via 'state' statement)
* else: list giving parameters of the event:
* [0] = event code (integer)
* [1..n] = call parameters to the event, if any
* Notes:
* 1) Scrips should use XMREVENTMASKn_<eventname> symbols for the mask arguments,
* where n is 1 or 2 for mask1 or mask2 arguments.
* The list[0] return argument can be decoded by using XMREVENTCODE_<eventname> symbols.
* 2) If all masks are zero, the call ends up acting like llSleep.
* 3) If an event is enabled in both returnMask and backgroundMask, the returnMask bit
* action takes precedence, ie, the event is returned. This allows a simple specification
* of -1 for both backgroundMask arguments to indicate that all events not listed in
* the returnMask argumetns should be handled in the background.
* 4) Any events not listed in either returnMask or backgroundMask arguments will be
* queued for later processing (subject to normal queue limits).
* 5) Background event handlers execute as calls from within xmrEventDequeue, they do
* not execute as separate threads. Thus any background event handlers must return
* before the call to xmrEventDequeue will return.
* 6) If a background event handler changes state (eg, via 'state' statement), the state
* is immediately changed and the script-level xmrEventDequeue call does not return.
* 7) For returned events, the detect parameters are overwritten by the returned event.
* For background events, the detect parameters are saved and restored.
* 8) Scripts must contain dummy event handler definitions for any event types that may
* be returned by xmrEventDequeue, to let the runtime know that the script is capable
* of processing that event type. Otherwise, the event may not be queued to the script.
*/
private static LSL_List emptyList = new LSL_List(new object[0]);
public override LSL_List xmrEventDequeue(double timeout, int returnMask1, int returnMask2,
int backgroundMask1, int backgroundMask2)
{
DateTime sleepUntil = DateTime.UtcNow + TimeSpan.FromMilliseconds(timeout * 1000.0);
EventParams evt = null;
int callNo, evc2;
int evc1 = 0;
int mask1 = returnMask1 | backgroundMask1; // codes 00..31
int mask2 = returnMask2 | backgroundMask2; // codes 32..63
LinkedListNode<EventParams> lln = null;
object[] sv;
ScriptEventCode evc = ScriptEventCode.None;
callNo = -1;
try
{
if(callMode == CallMode_NORMAL)
goto findevent;
// Stack frame is being restored as saved via CheckRun...().
// Restore necessary values then jump to __call<n> label to resume processing.
sv = RestoreStackFrame("xmrEventDequeue", out callNo);
sleepUntil = DateTime.Parse((string)sv[0]);
returnMask1 = (int)sv[1];
returnMask2 = (int)sv[2];
mask1 = (int)sv[3];
mask2 = (int)sv[4];
switch(callNo)
{
case 0:
goto __call0;
case 1:
{
evc1 = (int)sv[5];
evc = (ScriptEventCode)(int)sv[6];
DetectParams[] detprms = ObjArrToDetPrms((object[])sv[7]);
object[] ehargs = (object[])sv[8];
evt = new EventParams(evc.ToString(), ehargs, detprms);
goto __call1;
}
}
throw new ScriptBadCallNoException(callNo);
// Find first event that matches either the return or background masks.
findevent:
Monitor.Enter(m_QueueLock);
for(lln = m_EventQueue.First; lln != null; lln = lln.Next)
{
evt = lln.Value;
evc = (ScriptEventCode)Enum.Parse(typeof(ScriptEventCode), evt.EventName);
evc1 = (int)evc;
evc2 = evc1 - 32;
if((((uint)evc1 < (uint)32) && (((mask1 >> evc1) & 1) != 0)) ||
(((uint)evc2 < (uint)32) && (((mask2 >> evc2) & 1) != 0)))
goto remfromq;
}
// Nothing found, sleep while one comes in.
m_SleepUntil = sleepUntil;
m_SleepEventMask1 = mask1;
m_SleepEventMask2 = mask2;
Monitor.Exit(m_QueueLock);
suspendOnCheckRunTemp = true;
callNo = 0;
__call0:
CheckRunQuick();
goto checktmo;
// Found one, remove it from queue.
remfromq:
m_EventQueue.Remove(lln);
if((uint)evc1 < (uint)m_EventCounts.Length)
m_EventCounts[evc1]--;
Monitor.Exit(m_QueueLock);
m_InstEHEvent++;
// See if returnable or background event.
if((((uint)evc1 < (uint)32) && (((returnMask1 >> evc1) & 1) != 0)) ||
(((uint)evc2 < (uint)32) && (((returnMask2 >> evc2) & 1) != 0)))
{
// Returnable event, return its parameters in a list.
// Also set the detect parameters to what the event has.
int plen = evt.Params.Length;
object[] plist = new object[plen + 1];
plist[0] = (LSL_Integer)evc1;
for(int i = 0; i < plen;)
{
object ob = evt.Params[i];
if(ob is int)
ob = (LSL_Integer)(int)ob;
else if(ob is double)
ob = (LSL_Float)(double)ob;
else if(ob is string)
ob = (LSL_String)(string)ob;
plist[++i] = ob;
}
m_DetectParams = evt.DetectParams;
return new LSL_List(plist);
}
// It is a background event, simply call its event handler,
// then check event queue again.
callNo = 1;
__call1:
ScriptEventHandler seh = m_ObjCode.scriptEventHandlerTable[stateCode, evc1];
if(seh == null)
goto checktmo;
DetectParams[] saveDetParams = this.m_DetectParams;
object[] saveEHArgs = this.ehArgs;
ScriptEventCode saveEventCode = this.eventCode;
this.m_DetectParams = evt.DetectParams;
this.ehArgs = evt.Params;
this.eventCode = evc;
try
{
seh(this);
}
finally
{
this.m_DetectParams = saveDetParams;
this.ehArgs = saveEHArgs;
this.eventCode = saveEventCode;
}
// Keep waiting until we find a returnable event or timeout.
checktmo:
if(DateTime.UtcNow < sleepUntil)
goto findevent;
// We timed out, return an empty list.
return emptyList;
}
finally
{
if(callMode != CallMode_NORMAL)
{
// Stack frame is being saved by CheckRun...().
// Save everything we need at the __call<n> labels so we can restore it
// when we need to.
sv = CaptureStackFrame("xmrEventDequeue", callNo, 9);
sv[0] = sleepUntil.ToString(); // needed at __call0,__call1
sv[1] = returnMask1; // needed at __call0,__call1
sv[2] = returnMask2; // needed at __call0,__call1
sv[3] = mask1; // needed at __call0,__call1
sv[4] = mask2; // needed at __call0,__call1
if(callNo == 1)
{
sv[5] = evc1; // needed at __call1
sv[6] = (int)evc; // needed at __call1
sv[7] = DetPrmsToObjArr(evt.DetectParams); // needed at __call1
sv[8] = evt.Params; // needed at __call1
}
}
}
}
/**
* @brief Enqueue an event
* @param ev = as returned by xmrEventDequeue saying which event type to queue
* and what argument list to pass to it. The llDetect...() parameters
* are as currently set for the script (use xmrEventLoadDets to set how
* you want them to be different).
*/
public override void xmrEventEnqueue(LSL_List ev)
{
object[] data = ev.Data;
ScriptEventCode evc = (ScriptEventCode)ListInt(data[0]);
int nargs = data.Length - 1;
object[] args = new object[nargs];
Array.Copy(data, 1, args, 0, nargs);
PostEvent(new EventParams(evc.ToString(), args, m_DetectParams));
}
/**
* @brief Save current detect params into a list
* @returns a list containing current detect param values
*/
private const int saveDPVer = 1;
public override LSL_List xmrEventSaveDets()
{
object[] obs = DetPrmsToObjArr(m_DetectParams);
return new LSL_List(obs);
}
private static object[] DetPrmsToObjArr(DetectParams[] dps)
{
int len = dps.Length;
object[] obs = new object[len * 16 + 1];
int j = 0;
obs[j++] = (LSL_Integer)saveDPVer;
for(int i = 0; i < len; i++)
{
DetectParams dp = dps[i];
obs[j++] = (LSL_String)dp.Key.ToString(); // UUID
obs[j++] = dp.OffsetPos; // vector
obs[j++] = (LSL_Integer)dp.LinkNum; // integer
obs[j++] = (LSL_String)dp.Group.ToString(); // UUID
obs[j++] = (LSL_String)dp.Name; // string
obs[j++] = (LSL_String)dp.Owner.ToString(); // UUID
obs[j++] = dp.Position; // vector
obs[j++] = dp.Rotation; // rotation
obs[j++] = (LSL_Integer)dp.Type; // integer
obs[j++] = dp.Velocity; // vector
obs[j++] = dp.TouchST; // vector
obs[j++] = dp.TouchNormal; // vector
obs[j++] = dp.TouchBinormal; // vector
obs[j++] = dp.TouchPos; // vector
obs[j++] = dp.TouchUV; // vector
obs[j++] = (LSL_Integer)dp.TouchFace; // integer
}
return obs;
}
/**
* @brief Load current detect params from a list
* @param dpList = as returned by xmrEventSaveDets()
*/
public override void xmrEventLoadDets(LSL_List dpList)
{
m_DetectParams = ObjArrToDetPrms(dpList.Data);
}
private static DetectParams[] ObjArrToDetPrms(object[] objs)
{
int j = 0;
if((objs.Length % 16 != 1) || (ListInt(objs[j++]) != saveDPVer))
throw new Exception("invalid detect param format");
int len = objs.Length / 16;
DetectParams[] dps = new DetectParams[len];
for(int i = 0; i < len; i++)
{
DetectParams dp = new DetectParams();
dp.Key = new UUID(ListStr(objs[j++]));
dp.OffsetPos = (LSL_Vector)objs[j++];
dp.LinkNum = ListInt(objs[j++]);
dp.Group = new UUID(ListStr(objs[j++]));
dp.Name = ListStr(objs[j++]);
dp.Owner = new UUID(ListStr(objs[j++]));
dp.Position = (LSL_Vector)objs[j++];
dp.Rotation = (LSL_Rotation)objs[j++];
dp.Type = ListInt(objs[j++]);
dp.Velocity = (LSL_Vector)objs[j++];
SurfaceTouchEventArgs stea = new SurfaceTouchEventArgs();
stea.STCoord = LSLVec2OMVec((LSL_Vector)objs[j++]);
stea.Normal = LSLVec2OMVec((LSL_Vector)objs[j++]);
stea.Binormal = LSLVec2OMVec((LSL_Vector)objs[j++]);
stea.Position = LSLVec2OMVec((LSL_Vector)objs[j++]);
stea.UVCoord = LSLVec2OMVec((LSL_Vector)objs[j++]);
stea.FaceIndex = ListInt(objs[j++]);
dp.SurfaceTouchArgs = stea;
dps[i] = dp;
}
return dps;
}
/**
* @brief The script is executing a 'state <newState>;' command.
* Tell outer layers to cancel any event triggers, like llListen(),
* then tell outer layers which events the new state has handlers for.
* We also clear the event queue as per http://wiki.secondlife.com/wiki/State
*/
public override void StateChange()
{
// Cancel any llListen()s etc.
// But llSetTimerEvent() should persist.
object[] timers = m_XMRLSLApi.acm.TimerPlugin.GetSerializationData(m_ItemID);
AsyncCommandManager.RemoveScript(m_Engine, m_LocalID, m_ItemID);
m_XMRLSLApi.acm.TimerPlugin.CreateFromData(m_LocalID, m_ItemID, UUID.Zero, timers);
// Tell whoever cares which event handlers the new state has.
m_Part.SetScriptEvents(m_ItemID, GetStateEventFlags(stateCode));
// Clear out any old events from the queue.
lock(m_QueueLock)
{
m_EventQueue.Clear();
for(int i = m_EventCounts.Length; --i >= 0;)
m_EventCounts[i] = 0;
}
}
}
/**
* @brief Thrown by things like llResetScript() to unconditionally
* unwind as script and reset it to the default state_entry
* handler. We don't want script-level try/catch to intercept
* these so scripts can't interfere with the behavior.
*/
public class ScriptResetException: Exception, IXMRUncatchable
{
}
/**
* @brief Thrown by things like llDie() to unconditionally unwind as
* script. We don't want script-level try/catch to intercept
* these so scripts can't interfere with the behavior.
*/
public class ScriptDieException: Exception, IXMRUncatchable
{
}
}
| |
/*
Copyright 2019 Esri
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.Windows.Forms;
using ESRI.ArcGIS.SystemUI;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS;
using Microsoft.Win32;
namespace ToolbarControlExtension
{
public class Form1 : System.Windows.Forms.Form
{
private System.ComponentModel.Container components = null;
public System.Windows.Forms.CheckBox chkExtension;
public System.Windows.Forms.Label Label3;
public System.Windows.Forms.Label Label1;
public System.Windows.Forms.Label Label2;
private ESRI.ArcGIS.Controls.AxToolbarControl axToolbarControl1;
private ESRI.ArcGIS.Controls.AxMapControl axMapControl1;
private ESRI.ArcGIS.Controls.AxLicenseControl axLicenseControl1;
private IExtensionManagerAdmin m_ExtensionManagerAdmin;
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
this.chkExtension = new System.Windows.Forms.CheckBox();
this.Label3 = new System.Windows.Forms.Label();
this.Label1 = new System.Windows.Forms.Label();
this.Label2 = new System.Windows.Forms.Label();
this.axToolbarControl1 = new ESRI.ArcGIS.Controls.AxToolbarControl();
this.axMapControl1 = new ESRI.ArcGIS.Controls.AxMapControl();
this.axLicenseControl1 = new ESRI.ArcGIS.Controls.AxLicenseControl();
((System.ComponentModel.ISupportInitialize)(this.axToolbarControl1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.axMapControl1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.axLicenseControl1)).BeginInit();
this.SuspendLayout();
//
// chkExtension
//
this.chkExtension.BackColor = System.Drawing.SystemColors.Control;
this.chkExtension.Cursor = System.Windows.Forms.Cursors.Default;
this.chkExtension.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.chkExtension.ForeColor = System.Drawing.SystemColors.ControlText;
this.chkExtension.Location = new System.Drawing.Point(592, 8);
this.chkExtension.Name = "chkExtension";
this.chkExtension.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.chkExtension.Size = new System.Drawing.Size(113, 25);
this.chkExtension.TabIndex = 6;
this.chkExtension.Text = "Enable Extension";
this.chkExtension.UseVisualStyleBackColor = false;
this.chkExtension.CheckedChanged += new System.EventHandler(this.chkExtension_CheckedChanged);
//
// Label3
//
this.Label3.BackColor = System.Drawing.SystemColors.Control;
this.Label3.Cursor = System.Windows.Forms.Cursors.Default;
this.Label3.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Label3.ForeColor = System.Drawing.SystemColors.ControlText;
this.Label3.Location = new System.Drawing.Point(592, 136);
this.Label3.Name = "Label3";
this.Label3.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Label3.Size = new System.Drawing.Size(137, 65);
this.Label3.TabIndex = 9;
this.Label3.Text = "Enable the extension and navigate around the data using the commands from the ext" +
"ension.";
//
// Label1
//
this.Label1.BackColor = System.Drawing.SystemColors.Control;
this.Label1.Cursor = System.Windows.Forms.Cursors.Default;
this.Label1.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Label1.ForeColor = System.Drawing.SystemColors.ControlText;
this.Label1.Location = new System.Drawing.Point(592, 88);
this.Label1.Name = "Label1";
this.Label1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Label1.Size = new System.Drawing.Size(137, 41);
this.Label1.TabIndex = 8;
this.Label1.Text = "Navigate around the data using the commands on the ToolbarControl.";
//
// Label2
//
this.Label2.BackColor = System.Drawing.SystemColors.Control;
this.Label2.Cursor = System.Windows.Forms.Cursors.Default;
this.Label2.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Label2.ForeColor = System.Drawing.SystemColors.ControlText;
this.Label2.Location = new System.Drawing.Point(592, 40);
this.Label2.Name = "Label2";
this.Label2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Label2.Size = new System.Drawing.Size(137, 40);
this.Label2.TabIndex = 7;
this.Label2.Text = "Browse to a map document to load into the MapControl.";
//
// axToolbarControl1
//
this.axToolbarControl1.Location = new System.Drawing.Point(8, 8);
this.axToolbarControl1.Name = "axToolbarControl1";
this.axToolbarControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axToolbarControl1.OcxState")));
this.axToolbarControl1.Size = new System.Drawing.Size(576, 28);
this.axToolbarControl1.TabIndex = 10;
//
// axMapControl1
//
this.axMapControl1.Location = new System.Drawing.Point(8, 40);
this.axMapControl1.Name = "axMapControl1";
this.axMapControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axMapControl1.OcxState")));
this.axMapControl1.Size = new System.Drawing.Size(576, 432);
this.axMapControl1.TabIndex = 11;
//
// axLicenseControl1
//
this.axLicenseControl1.Enabled = true;
this.axLicenseControl1.Location = new System.Drawing.Point(595, 204);
this.axLicenseControl1.Name = "axLicenseControl1";
this.axLicenseControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axLicenseControl1.OcxState")));
this.axLicenseControl1.Size = new System.Drawing.Size(32, 32);
this.axLicenseControl1.TabIndex = 12;
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(736, 478);
this.Controls.Add(this.axLicenseControl1);
this.Controls.Add(this.axMapControl1);
this.Controls.Add(this.axToolbarControl1);
this.Controls.Add(this.chkExtension);
this.Controls.Add(this.Label3);
this.Controls.Add(this.Label1);
this.Controls.Add(this.Label2);
this.Name = "Form1";
this.Text = "MenuTracking";
this.Load += new System.EventHandler(this.Form1_Load);
((System.ComponentModel.ISupportInitialize)(this.axToolbarControl1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.axMapControl1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.axLicenseControl1)).EndInit();
this.ResumeLayout(false);
}
#endregion
[STAThread]
static void Main()
{
if (!RuntimeManager.Bind(ProductCode.Engine))
{
if (!RuntimeManager.Bind(ProductCode.Desktop))
{
MessageBox.Show("Unable to bind to ArcGIS runtime. Application will be shut down.");
return;
}
}
Application.Run(new Form1());
}
private void Form1_Load(object sender, System.EventArgs e)
{
//Set buddy control
axToolbarControl1.SetBuddyControl(axMapControl1.Object);
//Add control command items to the ToolbarControl
axToolbarControl1.AddItem("esriControls.ControlsOpenDocCommand",-1,-1,false,0,esriCommandStyles.esriCommandStyleIconOnly);
axToolbarControl1.AddItem("esriControls.ControlsMapZoomInTool",-1,-1,true,0,esriCommandStyles.esriCommandStyleIconOnly);
axToolbarControl1.AddItem("esriControls.ControlsMapZoomOutTool",-1,-1,false,0,esriCommandStyles.esriCommandStyleIconOnly);
axToolbarControl1.AddItem("esriControls.ControlsMapPanTool",-1,-1,false,0,esriCommandStyles.esriCommandStyleIconOnly);
//Add extension command items to the ToolbarControl
axToolbarControl1.AddItem("ZoomFactorExtensionCSharp.SetZoomFactor",-1,-1,true,0,esriCommandStyles.esriCommandStyleIconAndText);
axToolbarControl1.AddItem("ZoomFactorExtensionCSharp.ZoomIn",-1,-1,true,0,esriCommandStyles.esriCommandStyleIconAndText);
axToolbarControl1.AddItem("ZoomFactorExtensionCSharp.ZoomOut",-1,-1,true,0,esriCommandStyles.esriCommandStyleIconAndText);
//Get the extension manager admin
m_ExtensionManagerAdmin = (IExtensionManagerAdmin) new ExtensionManagerClass();
//Add the extension to the extension manager
UID uID = new UIDClass();
uID.Value = "ZoomFactorExtensionCSharp.ZoomExtension";
object obj = new object();
m_ExtensionManagerAdmin.AddExtension(uID, ref obj);
}
private void chkExtension_CheckedChanged(object sender, System.EventArgs e)
{
//Get the extension manager
IExtensionManager extensionManager = (IExtensionManager) m_ExtensionManagerAdmin;
//Get the extension from the extension manager
IExtensionConfig extensionConfig = (IExtensionConfig) extensionManager.FindExtension("Zoom Factor Extension");
//Set the enabled state
if (chkExtension.CheckState == CheckState.Checked) extensionConfig.State = esriExtensionState.esriESEnabled;
else extensionConfig.State = esriExtensionState.esriESDisabled;
}
}
}
| |
using JetBrains.Annotations;
using JsonApiDotNetCore.AtomicOperations;
using JsonApiDotNetCore.Configuration;
using JsonApiDotNetCore.Errors;
using JsonApiDotNetCore.Middleware;
using JsonApiDotNetCore.Resources;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.Extensions.Logging;
namespace JsonApiDotNetCore.Controllers;
/// <summary>
/// Implements the foundational ASP.NET controller layer in the JsonApiDotNetCore architecture for handling atomic:operations requests. See
/// https://jsonapi.org/ext/atomic/ for details. Delegates work to <see cref="IOperationsProcessor" />.
/// </summary>
[PublicAPI]
public abstract class BaseJsonApiOperationsController : CoreJsonApiController
{
private readonly IJsonApiOptions _options;
private readonly IResourceGraph _resourceGraph;
private readonly IOperationsProcessor _processor;
private readonly IJsonApiRequest _request;
private readonly ITargetedFields _targetedFields;
private readonly TraceLogWriter<BaseJsonApiOperationsController> _traceWriter;
protected BaseJsonApiOperationsController(IJsonApiOptions options, IResourceGraph resourceGraph, ILoggerFactory loggerFactory,
IOperationsProcessor processor, IJsonApiRequest request, ITargetedFields targetedFields)
{
ArgumentGuard.NotNull(options, nameof(options));
ArgumentGuard.NotNull(resourceGraph, nameof(resourceGraph));
ArgumentGuard.NotNull(loggerFactory, nameof(loggerFactory));
ArgumentGuard.NotNull(processor, nameof(processor));
ArgumentGuard.NotNull(request, nameof(request));
ArgumentGuard.NotNull(targetedFields, nameof(targetedFields));
_options = options;
_resourceGraph = resourceGraph;
_processor = processor;
_request = request;
_targetedFields = targetedFields;
_traceWriter = new TraceLogWriter<BaseJsonApiOperationsController>(loggerFactory);
}
/// <summary>
/// Atomically processes a list of operations and returns a list of results. All changes are reverted if processing fails. If processing succeeds but
/// none of the operations returns any data, then HTTP 201 is returned instead of 200.
/// </summary>
/// <example>
/// The next example creates a new resource.
/// <code><![CDATA[
/// POST /operations HTTP/1.1
/// Content-Type: application/vnd.api+json;ext="https://jsonapi.org/ext/atomic"
///
/// {
/// "atomic:operations": [{
/// "op": "add",
/// "data": {
/// "type": "authors",
/// "attributes": {
/// "name": "John Doe"
/// }
/// }
/// }]
/// }
/// ]]></code>
/// </example>
/// <example>
/// The next example updates an existing resource.
/// <code><![CDATA[
/// POST /operations HTTP/1.1
/// Content-Type: application/vnd.api+json;ext="https://jsonapi.org/ext/atomic"
///
/// {
/// "atomic:operations": [{
/// "op": "update",
/// "data": {
/// "type": "authors",
/// "id": 1,
/// "attributes": {
/// "name": "Jane Doe"
/// }
/// }
/// }]
/// }
/// ]]></code>
/// </example>
/// <example>
/// The next example deletes an existing resource.
/// <code><![CDATA[
/// POST /operations HTTP/1.1
/// Content-Type: application/vnd.api+json;ext="https://jsonapi.org/ext/atomic"
///
/// {
/// "atomic:operations": [{
/// "op": "remove",
/// "ref": {
/// "type": "authors",
/// "id": 1
/// }
/// }]
/// }
/// ]]></code>
/// </example>
public virtual async Task<IActionResult> PostOperationsAsync([FromBody] IList<OperationContainer> operations, CancellationToken cancellationToken)
{
_traceWriter.LogMethodStart(new
{
operations
});
ArgumentGuard.NotNull(operations, nameof(operations));
if (_options.ValidateModelState)
{
ValidateModelState(operations);
}
IList<OperationContainer?> results = await _processor.ProcessAsync(operations, cancellationToken);
return results.Any(result => result != null) ? Ok(results) : NoContent();
}
protected virtual void ValidateModelState(IList<OperationContainer> operations)
{
// We must validate the resource inside each operation manually, because they are typed as IIdentifiable.
// Instead of validating IIdentifiable we need to validate the resource runtime-type.
using IDisposable _ = new RevertRequestStateOnDispose(_request, _targetedFields);
int operationIndex = 0;
var requestModelState = new List<(string key, ModelStateEntry? entry)>();
int maxErrorsRemaining = ModelState.MaxAllowedErrors;
foreach (OperationContainer operation in operations)
{
if (maxErrorsRemaining < 1)
{
break;
}
maxErrorsRemaining = ValidateOperation(operation, operationIndex, requestModelState, maxErrorsRemaining);
operationIndex++;
}
if (requestModelState.Any())
{
Dictionary<string, ModelStateEntry?> modelStateDictionary = requestModelState.ToDictionary(tuple => tuple.key, tuple => tuple.entry);
throw new InvalidModelStateException(modelStateDictionary, typeof(IList<OperationContainer>), _options.IncludeExceptionStackTraceInErrors,
_resourceGraph, (collectionType, index) => collectionType == typeof(IList<OperationContainer>) ? operations[index].Resource.GetType() : null);
}
}
private int ValidateOperation(OperationContainer operation, int operationIndex, List<(string key, ModelStateEntry? entry)> requestModelState,
int maxErrorsRemaining)
{
if (operation.Request.WriteOperation is WriteOperationKind.CreateResource or WriteOperationKind.UpdateResource)
{
_targetedFields.CopyFrom(operation.TargetedFields);
_request.CopyFrom(operation.Request);
var validationContext = new ActionContext
{
ModelState =
{
MaxAllowedErrors = maxErrorsRemaining
}
};
ObjectValidator.Validate(validationContext, null, string.Empty, operation.Resource);
if (!validationContext.ModelState.IsValid)
{
int errorsRemaining = maxErrorsRemaining;
foreach (string key in validationContext.ModelState.Keys)
{
ModelStateEntry entry = validationContext.ModelState[key]!;
if (entry.ValidationState == ModelValidationState.Invalid)
{
string operationKey = $"[{operationIndex}].{nameof(OperationContainer.Resource)}.{key}";
if (entry.Errors.Count > 0 && entry.Errors[0].Exception is TooManyModelErrorsException)
{
requestModelState.Insert(0, (operationKey, entry));
}
else
{
requestModelState.Add((operationKey, entry));
}
errorsRemaining -= entry.Errors.Count;
}
}
return errorsRemaining;
}
}
return maxErrorsRemaining;
}
}
| |
/*
This sample demonstrates how to map, fetch, and manipulate
a nested table of UDTs that has an inheritance hierarchy
(i.e. parent and child types). This sample can use managed
ODP.NET or ODP.NET Core.
Database schema setup scripts:
1. Connect to HR or another similar schema.
2. Run the following SQL scripts to create a person type,
a student type that inherits from person type, a nested
table of person types, and a table with a nested table column.
drop table odp_nt_sample_person_rel_tab;
drop type odp_nt_sample_person_coll_type;
drop type odp_nt_sample_student_type;
drop type odp_nt_sample_person_type;
create type odp_nt_sample_person_type as object
(name varchar2(30), address varchar2(60), age number(3)) NOT FINAL;
/
create type odp_nt_sample_student_type under odp_nt_sample_person_type
(dept_id number(2), major varchar2(20));
/
create type odp_nt_sample_person_coll_type as
table of odp_nt_sample_person_type;
/
create table odp_nt_sample_person_rel_tab
(col1 odp_nt_sample_person_coll_type) nested table col1 store as nt_s;
*/
using System;
using System.Data;
using System.Collections;
using Oracle.ManagedDataAccess.Client;
using Oracle.ManagedDataAccess.Types;
class NestedTableSample
{
static void Main(string[] args)
{
// Enter user id, password, and Oracle data source (i.e. net service name, EZ Connect, etc.)
string constr = "user id=<USER ID>;password=<PASSWORD>;data source=<DATA SOURCE>";
string sql1 = "insert into odp_nt_sample_person_rel_tab values(:param)";
string sql2 = "select col1 from odp_nt_sample_person_rel_tab";
// Create a new Person object
Person p1 = new Person();
p1.Name = "John";
p1.Address = "Address 1";
p1.Age = 20;
// Create a new Student object
Student s1 = new Student();
s1.Name = "Jim";
s1.Address = "Address 2";
s1.Age = 25;
s1.Major = "Physics";
// Create a second Student object
Student s2 = new Student();
s2.Name = "Alex";
s2.Address = "Address 3";
s2.Age = 21;
s2.Major = "Math";
// Create a new Person array
Person[] pa = new Person[] { p1, s1 };
OracleConnection con = null;
OracleCommand cmd = null;
OracleDataReader reader = null;
try
{
// Establish a connection to Oracle DB
con = new OracleConnection(constr);
con.Open();
cmd = new OracleCommand(sql1, con);
cmd.CommandText = sql1;
OracleParameter param = new OracleParameter();
param.OracleDbType = OracleDbType.Array;
param.Direction = ParameterDirection.Input;
// Note: The UdtTypeName is case-senstive
param.UdtTypeName = "ODP_NT_SAMPLE_PERSON_COLL_TYPE";
param.Value = pa;
cmd.Parameters.Add(param);
// Insert a nested table of (person, student) into the table column
cmd.ExecuteNonQuery();
// Modify some elements in Person array
pa[1].Address = "Modified Address";
pa[1].Age = pa[1].Age + 1;
// Add/Remove some elements by converting the Person[] to an ArrayList
ArrayList list = new ArrayList(pa);
// Remove the first element
list.RemoveAt(0);
// Add the second student
list.Add(s2);
pa = (Person[])list.ToArray(typeof(Person));
param.Value = pa;
// The array now has two students.
// Insert a nested table of (student, student) into the table column.
cmd.ExecuteNonQuery();
cmd.CommandText = sql2;
cmd.CommandType = CommandType.Text;
reader = cmd.ExecuteReader();
// Fetch each row
int rowCount = 1;
while (reader.Read())
{
// Fetch the array and print out each element.
// Observe that four new elements were inserted with this app.
Person[] p = (Person[])reader.GetValue(0);
for (int i = 0; i < p.Length; i++)
Console.WriteLine("Row {0}, Person[{1}]: {2} ", rowCount, i, p.GetValue(i));
rowCount++;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
// Clean up
if (reader != null)
reader.Dispose();
if (cmd != null)
cmd.Dispose();
if (con != null)
con.Dispose();
}
}
}
// Person Class
// An instance of a Person class represents an ODP_NT_SAMPLE_PERSON_TYPE object.
// A custom type must implement INullable and IOracleCustomType interfaces.
public class Person : INullable, IOracleCustomType
{
private bool m_bIsNull; // Whether the Person object is NULL
private string m_name; // "NAME" attribute
private OracleString m_address; // "ADDRESS" attribute
private int? m_age; // "AGE" attribute
// Implementation of INullable.IsNull
public virtual bool IsNull
{
get
{
return m_bIsNull;
}
}
// Person.Null is used to return a NULL Person object.
public static Person Null
{
get
{
Person p = new Person();
p.m_bIsNull = true;
return p;
}
}
// Specify the OracleObjectMappingAttribute to map "Name" to "NAME".
[OracleObjectMappingAttribute("NAME")]
// The mapping can also be specified using attribute index 0.
// [OracleObjectMappingAttribute(0)]
public string Name
{
get
{
return m_name;
}
set
{
m_name = value;
}
}
// Specify the OracleObjectMappingAttribute to map "Address" to "ADDRESS".
[OracleObjectMappingAttribute("ADDRESS")]
// The mapping can also be specified using attribute index 1.
// [OracleObjectMappingAttribute(1)]
public OracleString Address
{
get
{
return m_address;
}
set
{
m_address = value;
}
}
// Specify the OracleObjectMappingAttribute to map "Age" to "AGE".
[OracleObjectMappingAttribute("AGE")]
// The mapping can also be specified using attribute index 2.
// [OracleObjectMappingAttribute(2)]
public int? Age
{
get
{
return m_age;
}
set
{
m_age = value;
}
}
// Implementation of IOracleCustomType.FromCustomObject()
public virtual void FromCustomObject(OracleConnection con, object pUdt)
{
// Convert from the Custom Type to Oracle Object
// Set the "NAME" attribute.
// By default the "NAME" attribute will be set to NULL.
if (m_name != null)
{
OracleUdt.SetValue(con, pUdt, "NAME", m_name);
// The "NAME" attribute can also be accessed by specifying index 0.
// OracleUdt.SetValue(con, pUdt, 0, m_name);
}
// Set the "ADDRESS" attribute.
// By default the "ADDRESS" attribute will be set to NULL.
if (!m_address.IsNull)
{
OracleUdt.SetValue(con, pUdt, "ADDRESS", m_address);
// The "ADDRESS" attribute can also be accessed by specifying index 1.
// OracleUdt.SetValue(con, pUdt, 1, m_address);
}
// Set the "AGE" attribute.
// By default the "AGE" attribute will be set to NULL.
if (m_age != null)
{
OracleUdt.SetValue(con, pUdt, "AGE", m_age);
// The "AGE attribute can also be accessed by specifying index 2.
// OracleUdt.SetValue(con, pUdt, 2, m_age);
}
}
// Implementation of IOracleCustomType.ToCustomObject()
public virtual void ToCustomObject(OracleConnection con, object pUdt)
{
// Convert from the Oracle Object to a Custom Type
// Get the "NAME" attribute.
// If the "NAME" attribute is NULL, then null will be returned.
m_name = (string)OracleUdt.GetValue(con, pUdt, "NAME");
// The "NAME" attribute can also be accessed by specifying index 0.
// m_name = (string)OracleUdt.GetValue(con, pUdt, 0);
// Get the "ADDRESS" attribute.
// If the "ADDRESS" attribute is NULL, then OracleString.Null will be returned.
m_address = (OracleString)OracleUdt.GetValue(con, pUdt, "ADDRESS");
// The "ADDRESS" attribute can also be accessed by specifying index 1.
// m_address = (OracleString)OracleUdt.GetValue(con, pUdt, 1);
// Get the "AGE" attribute.
// If the "AGE" attribute is NULL, then null will be returned.
m_age = (int?)OracleUdt.GetValue(con, pUdt, "AGE");
// The "AGE" attribute can also be accessed by specifying index 2.
// m_age = (int?)OracleUdt.GetValue(con, pUdt, 2);
}
public override string ToString()
{
// Return a string representation of the custom object
if (m_bIsNull)
return "Person.Null";
else
{
string name = (m_name == null) ? "NULL" : m_name;
string address = (m_address.IsNull) ? "NULL" : m_address.Value;
string age = (m_age == null)? "NULL" : m_age.ToString();
return "Person(" + name + ", " + address + ", " + age + ")";
}
}
}
// PersonFactory Class
// An instance of the PersonFactory class is used to create Person objects.
[OracleCustomTypeMappingAttribute("ODP_NT_SAMPLE_PERSON_TYPE")]
public class PersonFactory : IOracleCustomTypeFactory
{
// Implementation of IOracleCustomTypeFactory.CreateObject()
public IOracleCustomType CreateObject()
{
// Return a new custom object
return new Person();
}
}
// Student Class
// A Student class instance represents an ODP_NT_SAMPLE_STUDENT_TYPE object.
// Note: We do not map the "DEPT_ID" attribute (attribute index 3) so it
// will always be NULL. A custom type must implement INullable and
// IOracleCustomType interfaces.
public class Student : Person, INullable, IOracleCustomType
{
private bool m_bIsNull; // Whether the Student object is NULL
private string m_major; // "MAJOR" attribute
// Implementation of INullable.IsNull
public override bool IsNull
{
get
{
return m_bIsNull;
}
}
// Student.Null is used to return a NULL Student object.
public new static Student Null
{
get
{
Student s = new Student();
s.m_bIsNull = true;
return s;
}
}
// Specify the OracleObjectMappingAttribute to map "Major" to "MAJOR".
[OracleObjectMappingAttribute("MAJOR")]
// The mapping can also be specified using attribute index 4.
// [OracleObjectMappingAttribute(4)]
public string Major
{
get
{
return m_major;
}
set
{
m_major = value;
}
}
// Implementation of IOracleCustomType.FromCustomObject()
public override void FromCustomObject(OracleConnection con, object pUdt)
{
// Convert from the Custom Type to Oracle Object.
// Invoke the base class conversion method.
base.FromCustomObject(con, pUdt);
// Set the "MAJOR" attribute.
// By default, the "MAJOR" attribute will be set to NULL.
if (m_major != null)
OracleUdt.SetValue(con, pUdt, "MAJOR", m_major);
// The "MAJOR" attribute can also be accessed by specifying index 4.
// OracleUdt.SetValue(con, pUdt, 4, m_major);
}
// Implementation of IOracleCustomType.ToCustomObject()
public override void ToCustomObject(OracleConnection con, object pUdt)
{
// Convert from the Oracle Object to a Custom Type.
// Invoke the base class conversion method.
base.ToCustomObject(con, pUdt);
// Get the "MAJOR" attribute.
// If the "MAJOR" attribute is NULL, then "null" will be returned.
m_major = (string)OracleUdt.GetValue(con, pUdt, "MAJOR");
// The "MAJOR" attribute can also be accessed by specifying index 4.
// m_major = (string)OracleUdt.GetValue(con, pUdt, 4);
}
public override string ToString()
{
// Return a string representation of the custom object
if (m_bIsNull)
{
return "Student.Null";
}
else
{
string name = (Name == null) ? "NULL" : Name;
string address = (Address.IsNull) ? "NULL" : Address.Value;
string age = (Age == null) ? "NULL" : Age.ToString();
string major = (m_major == null) ? "NULL" : m_major;
return "Student(" + name + ", " + address + ", " + age + ", " + major + ")";
}
}
}
// StudentFactory Class
// An instance of the StudentFactory class is used to create Student objects.
[OracleCustomTypeMappingAttribute("ODP_NT_SAMPLE_STUDENT_TYPE")]
public class StudentFactory : IOracleCustomTypeFactory
{
// Implementation of IOracleCustomTypeFactory.CreateObject()
public IOracleCustomType CreateObject()
{
// Return a new custom object
return new Student();
}
}
// PersonArrayFactory Class
// An instance of the PersonArrayFactory class is used to create Person array.
[OracleCustomTypeMappingAttribute("ODP_NT_SAMPLE_PERSON_COLL_TYPE")]
public class PersonArrayFactory : IOracleArrayTypeFactory
{
// IOracleArrayTypeFactory Inteface
public Array CreateArray(int numElems)
{
return new Person[numElems];
}
public Array CreateStatusArray(int numElems)
{
// An OracleUdtStatus[] is not required to store null status information.
return null;
}
}
/* Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. */
/******************************************************************************
*
* You may not use the identified files except in compliance with The MIT
* License (the "License.")
*
* You may obtain a copy of the License at
* https://github.com/oracle/Oracle.NET/blob/master/LICENSE
*
* 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.
*
*****************************************************************************/
| |
#region Using directives
using System;
using System.Collections.Generic;
using System.Management.Automation;
using System.Security.Principal;
using System.Management.Automation.SecurityAccountsManager;
using System.Management.Automation.SecurityAccountsManager.Extensions;
#endregion
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// The Get-LocalGroupMember cmdlet gets the members of a local group.
/// </summary>
[Cmdlet(VerbsCommon.Get, "LocalGroupMember",
DefaultParameterSetName = "Default",
HelpUri = "http://go.microsoft.com/fwlink/?LinkId=717988")]
[Alias("glgm")]
public class GetLocalGroupMemberCommand : Cmdlet
{
#region Instance Data
private Sam sam = null;
#endregion Instance Data
#region Parameter Properties
/// <summary>
/// The following is the definition of the input parameter "Group".
/// The security group from the local Security Accounts Manager.
/// </summary>
[Parameter(Mandatory = true,
Position = 0,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = "Group")]
[ValidateNotNull]
public Microsoft.PowerShell.Commands.LocalGroup Group
{
get { return this.group;}
set { this.group = value; }
}
private Microsoft.PowerShell.Commands.LocalGroup group;
/// <summary>
/// The following is the definition of the input parameter "Member".
/// Specifies the name of the user or group that is a member of this group. If
/// this parameter is not specified, all members of the specified group are
/// returned. This accepts a name, SID, or wildcard string.
/// </summary>
[Parameter(Position = 1)]
[ValidateNotNullOrEmpty]
public string Member
{
get { return this.member;}
set { this.member = value; }
}
private string member;
/// <summary>
/// The following is the definition of the input parameter "Name".
/// The security group from the local Security Accounts Manager.
/// </summary>
[Parameter(Mandatory = true,
Position = 0,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = "Default")]
[ValidateNotNullOrEmpty]
public string Name
{
get { return this.name;}
set { this.name = value; }
}
private string name;
/// <summary>
/// The following is the definition of the input parameter "SID".
/// The security group from the local Security Accounts Manager.
/// </summary>
[Parameter(Mandatory = true,
Position = 0,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = "SecurityIdentifier")]
[ValidateNotNullOrEmpty]
public System.Security.Principal.SecurityIdentifier SID
{
get { return this.sid;}
set { this.sid = value; }
}
private System.Security.Principal.SecurityIdentifier sid;
#endregion Parameter Properties
#region Cmdlet Overrides
/// <summary>
/// BeginProcessing method.
/// </summary>
protected override void BeginProcessing()
{
sam = new Sam();
}
/// <summary>
/// ProcessRecord method.
/// </summary>
protected override void ProcessRecord()
{
try
{
IEnumerable<LocalPrincipal> principals = null;
if (Group != null)
principals = ProcessGroup(Group);
else if (Name != null)
principals = ProcessName(Name);
else if (SID != null)
principals = ProcessSid(SID);
if (principals != null)
WriteObject(principals, true);
}
catch (Exception ex)
{
WriteError(ex.MakeErrorRecord());
}
}
/// <summary>
/// EndProcessing method.
/// </summary>
protected override void EndProcessing()
{
if (sam != null)
{
sam.Dispose();
sam = null;
}
}
#endregion Cmdlet Overrides
#region Private Methods
private IEnumerable<LocalPrincipal> ProcessesMembership(IEnumerable<LocalPrincipal> membership)
{
List<LocalPrincipal> rv;
// if no members are specified, return all of them
if (Member == null)
{
//return membership;
rv = new List<LocalPrincipal>(membership);
}
else
{
//var rv = new List<LocalPrincipal>();
rv = new List<LocalPrincipal>();
if (WildcardPattern.ContainsWildcardCharacters(Member))
{
var pattern = new WildcardPattern(Member, WildcardOptions.Compiled
| WildcardOptions.IgnoreCase);
foreach (var m in membership)
if (pattern.IsMatch(sam.StripMachineName(m.Name)))
rv.Add(m);
}
else
{
var sid = this.TrySid(Member);
if (sid != null)
{
foreach (var m in membership)
{
if (m.SID == sid)
{
rv.Add(m);
break;
}
}
}
else
{
foreach (var m in membership)
{
if (sam.StripMachineName(m.Name).Equals(Member, StringComparison.CurrentCultureIgnoreCase))
{
rv.Add(m);
break;
}
}
}
if (rv.Count == 0)
{
var ex = new PrincipalNotFoundException(member, member);
WriteError(ex.MakeErrorRecord());
}
}
}
// sort the resulting principals by mane
rv.Sort((p1, p2) => string.Compare(p1.Name, p2.Name, StringComparison.CurrentCultureIgnoreCase));
return rv;
}
private IEnumerable<LocalPrincipal> ProcessGroup(LocalGroup group)
{
return ProcessesMembership(sam.GetLocalGroupMembers(group));
}
private IEnumerable<LocalPrincipal> ProcessName(string name)
{
return ProcessGroup(sam.GetLocalGroup(name));
}
private IEnumerable<LocalPrincipal> ProcessSid(SecurityIdentifier groupSid)
{
return ProcessesMembership(sam.GetLocalGroupMembers(groupSid));
}
#endregion Private Methods
}//End Class
}//End namespace
| |
// 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.Xml;
using System.Collections.Generic;
using System.Globalization;
namespace System.Runtime.Serialization
{
public sealed class ExtensionDataObject
{
private IList<ExtensionDataMember> _members;
#if USE_REFEMIT
public ExtensionDataObject()
#else
internal ExtensionDataObject()
#endif
{
}
#if USE_REFEMIT
public IList<ExtensionDataMember> Members
#else
internal IList<ExtensionDataMember> Members
#endif
{
get { return _members; }
set { _members = value; }
}
}
#if USE_REFEMIT
public class ExtensionDataMember
#else
internal class ExtensionDataMember
#endif
{
private string _name;
private string _ns;
private IDataNode _value;
private int _memberIndex;
public string Name
{
get { return _name; }
set { _name = value; }
}
public string Namespace
{
get { return _ns; }
set { _ns = value; }
}
public IDataNode Value
{
get { return _value; }
set { _value = value; }
}
public int MemberIndex
{
get { return _memberIndex; }
set { _memberIndex = value; }
}
}
#if USE_REFEMIT
public interface IDataNode
#else
internal interface IDataNode
#endif
{
Type DataType { get; }
object Value { get; set; } // boxes for primitives
string DataContractName { get; set; }
string DataContractNamespace { get; set; }
string ClrTypeName { get; set; }
string ClrAssemblyName { get; set; }
string Id { get; set; }
bool PreservesReferences { get; }
// NOTE: consider moving below APIs to DataNode<T> if IDataNode API is made public
void GetData(ElementData element);
bool IsFinalValue { get; set; }
void Clear();
}
internal class DataNode<T> : IDataNode
{
protected Type dataType;
private T _value;
private string _dataContractName;
private string _dataContractNamespace;
private string _clrTypeName;
private string _clrAssemblyName;
private string _id = Globals.NewObjectId;
private bool _isFinalValue;
internal DataNode()
{
this.dataType = typeof(T);
_isFinalValue = true;
}
internal DataNode(T value)
: this()
{
_value = value;
}
public Type DataType
{
get { return dataType; }
}
public object Value
{
get { return _value; }
set { _value = (T)value; }
}
bool IDataNode.IsFinalValue
{
get { return _isFinalValue; }
set { _isFinalValue = value; }
}
public T GetValue()
{
return _value;
}
#if NotUsed
public void SetValue(T value)
{
this.value = value;
}
#endif
public string DataContractName
{
get { return _dataContractName; }
set { _dataContractName = value; }
}
public string DataContractNamespace
{
get { return _dataContractNamespace; }
set { _dataContractNamespace = value; }
}
public string ClrTypeName
{
get { return _clrTypeName; }
set { _clrTypeName = value; }
}
public string ClrAssemblyName
{
get { return _clrAssemblyName; }
set { _clrAssemblyName = value; }
}
public bool PreservesReferences
{
get { return (Id != Globals.NewObjectId); }
}
public string Id
{
get { return _id; }
set { _id = value; }
}
public virtual void GetData(ElementData element)
{
element.dataNode = this;
element.attributeCount = 0;
element.childElementIndex = 0;
if (DataContractName != null)
AddQualifiedNameAttribute(element, Globals.XsiPrefix, Globals.XsiTypeLocalName, Globals.SchemaInstanceNamespace, DataContractName, DataContractNamespace);
if (ClrTypeName != null)
element.AddAttribute(Globals.SerPrefix, Globals.SerializationNamespace, Globals.ClrTypeLocalName, ClrTypeName);
if (ClrAssemblyName != null)
element.AddAttribute(Globals.SerPrefix, Globals.SerializationNamespace, Globals.ClrAssemblyLocalName, ClrAssemblyName);
}
public virtual void Clear()
{
// dataContractName not cleared because it is used when re-serializing from unknown data
_clrTypeName = _clrAssemblyName = null;
}
internal void AddQualifiedNameAttribute(ElementData element, string elementPrefix, string elementName, string elementNs, string valueName, string valueNs)
{
string prefix = ExtensionDataReader.GetPrefix(valueNs);
element.AddAttribute(elementPrefix, elementNs, elementName, prefix + ":" + valueName);
bool prefixDeclaredOnElement = false;
if (element.attributes != null)
{
for (int i = 0; i < element.attributes.Length; i++)
{
AttributeData attribute = element.attributes[i];
if (attribute != null && attribute.prefix == Globals.XmlnsPrefix && attribute.localName == prefix)
{
prefixDeclaredOnElement = true;
break;
}
}
}
if (!prefixDeclaredOnElement)
element.AddAttribute(Globals.XmlnsPrefix, Globals.XmlnsNamespace, prefix, valueNs);
}
}
internal class ClassDataNode : DataNode<object>
{
private IList<ExtensionDataMember> _members;
internal ClassDataNode()
{
dataType = Globals.TypeOfClassDataNode;
}
internal IList<ExtensionDataMember> Members
{
get { return _members; }
set { _members = value; }
}
public override void Clear()
{
base.Clear();
_members = null;
}
}
internal class XmlDataNode : DataNode<object>
{
private IList<XmlAttribute> _xmlAttributes;
private IList<XmlNode> _xmlChildNodes;
private XmlDocument _ownerDocument;
internal XmlDataNode()
{
dataType = Globals.TypeOfXmlDataNode;
}
internal IList<XmlAttribute> XmlAttributes
{
get { return _xmlAttributes; }
set { _xmlAttributes = value; }
}
internal IList<XmlNode> XmlChildNodes
{
get { return _xmlChildNodes; }
set { _xmlChildNodes = value; }
}
internal XmlDocument OwnerDocument
{
get { return _ownerDocument; }
set { _ownerDocument = value; }
}
public override void Clear()
{
base.Clear();
_xmlAttributes = null;
_xmlChildNodes = null;
_ownerDocument = null;
}
}
internal class CollectionDataNode : DataNode<Array>
{
private IList<IDataNode> _items;
private string _itemName;
private string _itemNamespace;
private int _size = -1;
internal CollectionDataNode()
{
dataType = Globals.TypeOfCollectionDataNode;
}
internal IList<IDataNode> Items
{
get { return _items; }
set { _items = value; }
}
internal string ItemName
{
get { return _itemName; }
set { _itemName = value; }
}
internal string ItemNamespace
{
get { return _itemNamespace; }
set { _itemNamespace = value; }
}
internal int Size
{
get { return _size; }
set { _size = value; }
}
public override void GetData(ElementData element)
{
base.GetData(element);
element.AddAttribute(Globals.SerPrefix, Globals.SerializationNamespace, Globals.ArraySizeLocalName, Size.ToString(NumberFormatInfo.InvariantInfo));
}
public override void Clear()
{
base.Clear();
_items = null;
_size = -1;
}
}
internal class ISerializableDataNode : DataNode<object>
{
private string _factoryTypeName;
private string _factoryTypeNamespace;
private IList<ISerializableDataMember> _members;
internal ISerializableDataNode()
{
dataType = Globals.TypeOfISerializableDataNode;
}
internal string FactoryTypeName
{
get { return _factoryTypeName; }
set { _factoryTypeName = value; }
}
internal string FactoryTypeNamespace
{
get { return _factoryTypeNamespace; }
set { _factoryTypeNamespace = value; }
}
internal IList<ISerializableDataMember> Members
{
get { return _members; }
set { _members = value; }
}
public override void GetData(ElementData element)
{
base.GetData(element);
if (FactoryTypeName != null)
AddQualifiedNameAttribute(element, Globals.SerPrefix, Globals.ISerializableFactoryTypeLocalName, Globals.SerializationNamespace, FactoryTypeName, FactoryTypeNamespace);
}
public override void Clear()
{
base.Clear();
_members = null;
_factoryTypeName = _factoryTypeNamespace = null;
}
}
internal class ISerializableDataMember
{
private string _name;
private IDataNode _value;
internal string Name
{
get { return _name; }
set { _name = value; }
}
internal IDataNode Value
{
get { return _value; }
set { _value = value; }
}
}
}
| |
namespace ExpandingHeaderGroupsSplitters
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
this.menuStrip = new System.Windows.Forms.MenuStrip();
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.menuOffice2010 = new System.Windows.Forms.ToolStripMenuItem();
this.menuOffice2007 = new System.Windows.Forms.ToolStripMenuItem();
this.menuSparkle = new System.Windows.Forms.ToolStripMenuItem();
this.menuSystem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripContainer1 = new System.Windows.Forms.ToolStripContainer();
this.kryptonPanel1 = new ComponentFactory.Krypton.Toolkit.KryptonPanel();
this.kryptonSplitContainerHorizontal = new ComponentFactory.Krypton.Toolkit.KryptonSplitContainer();
this.kryptonHeaderGroupLeft = new ComponentFactory.Krypton.Toolkit.KryptonHeaderGroup();
this.buttonSpecLeftRight = new ComponentFactory.Krypton.Toolkit.ButtonSpecHeaderGroup();
this.textBoxLeft = new ComponentFactory.Krypton.Toolkit.KryptonTextBox();
this.kryptonSplitContainerVertical = new ComponentFactory.Krypton.Toolkit.KryptonSplitContainer();
this.kryptonHeaderGroupRightTop = new ComponentFactory.Krypton.Toolkit.KryptonHeaderGroup();
this.textBoxRightTop = new ComponentFactory.Krypton.Toolkit.KryptonTextBox();
this.kryptonHeaderGroupRightBottom = new ComponentFactory.Krypton.Toolkit.KryptonHeaderGroup();
this.buttonSpecUpDown = new ComponentFactory.Krypton.Toolkit.ButtonSpecHeaderGroup();
this.textBoxRightBottom = new ComponentFactory.Krypton.Toolkit.KryptonTextBox();
this.toolStrip = new System.Windows.Forms.ToolStrip();
this.toolOffice2010 = new System.Windows.Forms.ToolStripButton();
this.toolOffice2007 = new System.Windows.Forms.ToolStripButton();
this.toolSparkle = new System.Windows.Forms.ToolStripButton();
this.toolSystem = new System.Windows.Forms.ToolStripButton();
this.kryptonManager = new ComponentFactory.Krypton.Toolkit.KryptonManager(this.components);
this.statusStrip1 = new System.Windows.Forms.StatusStrip();
this.menuStrip.SuspendLayout();
this.toolStripContainer1.ContentPanel.SuspendLayout();
this.toolStripContainer1.TopToolStripPanel.SuspendLayout();
this.toolStripContainer1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.kryptonPanel1)).BeginInit();
this.kryptonPanel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.kryptonSplitContainerHorizontal)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.kryptonSplitContainerHorizontal.Panel1)).BeginInit();
this.kryptonSplitContainerHorizontal.Panel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.kryptonSplitContainerHorizontal.Panel2)).BeginInit();
this.kryptonSplitContainerHorizontal.Panel2.SuspendLayout();
this.kryptonSplitContainerHorizontal.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.kryptonHeaderGroupLeft)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.kryptonHeaderGroupLeft.Panel)).BeginInit();
this.kryptonHeaderGroupLeft.Panel.SuspendLayout();
this.kryptonHeaderGroupLeft.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.kryptonSplitContainerVertical)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.kryptonSplitContainerVertical.Panel1)).BeginInit();
this.kryptonSplitContainerVertical.Panel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.kryptonSplitContainerVertical.Panel2)).BeginInit();
this.kryptonSplitContainerVertical.Panel2.SuspendLayout();
this.kryptonSplitContainerVertical.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.kryptonHeaderGroupRightTop)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.kryptonHeaderGroupRightTop.Panel)).BeginInit();
this.kryptonHeaderGroupRightTop.Panel.SuspendLayout();
this.kryptonHeaderGroupRightTop.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.kryptonHeaderGroupRightBottom)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.kryptonHeaderGroupRightBottom.Panel)).BeginInit();
this.kryptonHeaderGroupRightBottom.Panel.SuspendLayout();
this.kryptonHeaderGroupRightBottom.SuspendLayout();
this.toolStrip.SuspendLayout();
this.SuspendLayout();
//
// menuStrip
//
this.menuStrip.Font = new System.Drawing.Font("Segoe UI", 9F);
this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem});
this.menuStrip.Location = new System.Drawing.Point(0, 0);
this.menuStrip.Name = "menuStrip";
this.menuStrip.Size = new System.Drawing.Size(460, 24);
this.menuStrip.TabIndex = 0;
this.menuStrip.Text = "menuStrip1";
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.menuOffice2010,
this.menuOffice2007,
this.menuSparkle,
this.menuSystem,
this.toolStripSeparator1,
this.exitToolStripMenuItem});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
this.fileToolStripMenuItem.Size = new System.Drawing.Size(37, 20);
this.fileToolStripMenuItem.Text = "File";
//
// menuOffice2010
//
this.menuOffice2010.Checked = true;
this.menuOffice2010.CheckState = System.Windows.Forms.CheckState.Checked;
this.menuOffice2010.Name = "menuOffice2010";
this.menuOffice2010.Size = new System.Drawing.Size(167, 22);
this.menuOffice2010.Text = "Office 2010 - Blue";
this.menuOffice2010.Click += new System.EventHandler(this.toolOffice2010_Click);
//
// menuOffice2007
//
this.menuOffice2007.Name = "menuOffice2007";
this.menuOffice2007.Size = new System.Drawing.Size(167, 22);
this.menuOffice2007.Text = "Office 2007 - Blue";
this.menuOffice2007.Click += new System.EventHandler(this.toolOffice2007_Click);
//
// menuSparkle
//
this.menuSparkle.Name = "menuSparkle";
this.menuSparkle.Size = new System.Drawing.Size(167, 22);
this.menuSparkle.Text = "Sparkle - Blue";
this.menuSparkle.Click += new System.EventHandler(this.toolSparkle_Click);
//
// menuSystem
//
this.menuSystem.Name = "menuSystem";
this.menuSystem.Size = new System.Drawing.Size(167, 22);
this.menuSystem.Text = "System";
this.menuSystem.Click += new System.EventHandler(this.toolSystem_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(164, 6);
//
// exitToolStripMenuItem
//
this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
this.exitToolStripMenuItem.Size = new System.Drawing.Size(167, 22);
this.exitToolStripMenuItem.Text = "Exit";
this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click);
//
// toolStripContainer1
//
//
// toolStripContainer1.ContentPanel
//
this.toolStripContainer1.ContentPanel.Controls.Add(this.kryptonPanel1);
this.toolStripContainer1.ContentPanel.Size = new System.Drawing.Size(460, 309);
this.toolStripContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
this.toolStripContainer1.Location = new System.Drawing.Point(0, 24);
this.toolStripContainer1.Name = "toolStripContainer1";
this.toolStripContainer1.Size = new System.Drawing.Size(460, 334);
this.toolStripContainer1.TabIndex = 2;
this.toolStripContainer1.Text = "toolStripContainer1";
//
// toolStripContainer1.TopToolStripPanel
//
this.toolStripContainer1.TopToolStripPanel.Controls.Add(this.toolStrip);
//
// kryptonPanel1
//
this.kryptonPanel1.Controls.Add(this.kryptonSplitContainerHorizontal);
this.kryptonPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.kryptonPanel1.Location = new System.Drawing.Point(0, 0);
this.kryptonPanel1.Name = "kryptonPanel1";
this.kryptonPanel1.Padding = new System.Windows.Forms.Padding(5);
this.kryptonPanel1.Size = new System.Drawing.Size(460, 309);
this.kryptonPanel1.TabIndex = 0;
//
// kryptonSplitContainerHorizontal
//
this.kryptonSplitContainerHorizontal.Cursor = System.Windows.Forms.Cursors.Default;
this.kryptonSplitContainerHorizontal.Dock = System.Windows.Forms.DockStyle.Fill;
this.kryptonSplitContainerHorizontal.Location = new System.Drawing.Point(5, 5);
this.kryptonSplitContainerHorizontal.Name = "kryptonSplitContainerHorizontal";
//
// kryptonSplitContainerHorizontal.Panel1
//
this.kryptonSplitContainerHorizontal.Panel1.Controls.Add(this.kryptonHeaderGroupLeft);
this.kryptonSplitContainerHorizontal.Panel1MinSize = 100;
//
// kryptonSplitContainerHorizontal.Panel2
//
this.kryptonSplitContainerHorizontal.Panel2.Controls.Add(this.kryptonSplitContainerVertical);
this.kryptonSplitContainerHorizontal.Panel2MinSize = 100;
this.kryptonSplitContainerHorizontal.Size = new System.Drawing.Size(450, 299);
this.kryptonSplitContainerHorizontal.SplitterDistance = 167;
this.kryptonSplitContainerHorizontal.TabIndex = 0;
//
// kryptonHeaderGroupLeft
//
this.kryptonHeaderGroupLeft.ButtonSpecs.AddRange(new ComponentFactory.Krypton.Toolkit.ButtonSpecHeaderGroup[] {
this.buttonSpecLeftRight});
this.kryptonHeaderGroupLeft.Dock = System.Windows.Forms.DockStyle.Fill;
this.kryptonHeaderGroupLeft.HeaderVisibleSecondary = false;
this.kryptonHeaderGroupLeft.Location = new System.Drawing.Point(0, 0);
this.kryptonHeaderGroupLeft.Name = "kryptonHeaderGroupLeft";
//
// kryptonHeaderGroupLeft.Panel
//
this.kryptonHeaderGroupLeft.Panel.Controls.Add(this.textBoxLeft);
this.kryptonHeaderGroupLeft.Panel.Padding = new System.Windows.Forms.Padding(5);
this.kryptonHeaderGroupLeft.Size = new System.Drawing.Size(167, 299);
this.kryptonHeaderGroupLeft.TabIndex = 0;
this.kryptonHeaderGroupLeft.ValuesPrimary.Heading = "Left";
this.kryptonHeaderGroupLeft.ValuesPrimary.Image = null;
//
// buttonSpecLeftRight
//
this.buttonSpecLeftRight.ColorMap = System.Drawing.Color.Black;
this.buttonSpecLeftRight.Type = ComponentFactory.Krypton.Toolkit.PaletteButtonSpecStyle.ArrowLeft;
this.buttonSpecLeftRight.UniqueName = "F83F8E4720614585F83F8E4720614585";
//
// textBoxLeft
//
this.textBoxLeft.BackColor = System.Drawing.Color.White;
this.textBoxLeft.Dock = System.Windows.Forms.DockStyle.Fill;
this.textBoxLeft.Location = new System.Drawing.Point(5, 5);
this.textBoxLeft.Multiline = true;
this.textBoxLeft.Name = "textBoxLeft";
this.textBoxLeft.ReadOnly = true;
this.textBoxLeft.Size = new System.Drawing.Size(155, 258);
this.textBoxLeft.StateCommon.Border.Draw = ComponentFactory.Krypton.Toolkit.InheritBool.False;
this.textBoxLeft.StateCommon.Border.DrawBorders = ((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders)((((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Top | ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Bottom)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Left)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Right)));
this.textBoxLeft.TabIndex = 0;
this.textBoxLeft.Text = resources.GetString("textBoxLeft.Text");
//
// kryptonSplitContainerVertical
//
this.kryptonSplitContainerVertical.Cursor = System.Windows.Forms.Cursors.Default;
this.kryptonSplitContainerVertical.Dock = System.Windows.Forms.DockStyle.Fill;
this.kryptonSplitContainerVertical.Location = new System.Drawing.Point(0, 0);
this.kryptonSplitContainerVertical.Name = "kryptonSplitContainerVertical";
this.kryptonSplitContainerVertical.Orientation = System.Windows.Forms.Orientation.Horizontal;
//
// kryptonSplitContainerVertical.Panel1
//
this.kryptonSplitContainerVertical.Panel1.Controls.Add(this.kryptonHeaderGroupRightTop);
this.kryptonSplitContainerVertical.Panel1MinSize = 100;
//
// kryptonSplitContainerVertical.Panel2
//
this.kryptonSplitContainerVertical.Panel2.Controls.Add(this.kryptonHeaderGroupRightBottom);
this.kryptonSplitContainerVertical.Panel2MinSize = 100;
this.kryptonSplitContainerVertical.Size = new System.Drawing.Size(278, 299);
this.kryptonSplitContainerVertical.SplitterDistance = 133;
this.kryptonSplitContainerVertical.TabIndex = 0;
//
// kryptonHeaderGroupRightTop
//
this.kryptonHeaderGroupRightTop.Dock = System.Windows.Forms.DockStyle.Fill;
this.kryptonHeaderGroupRightTop.HeaderVisibleSecondary = false;
this.kryptonHeaderGroupRightTop.Location = new System.Drawing.Point(0, 0);
this.kryptonHeaderGroupRightTop.Name = "kryptonHeaderGroupRightTop";
//
// kryptonHeaderGroupRightTop.Panel
//
this.kryptonHeaderGroupRightTop.Panel.Controls.Add(this.textBoxRightTop);
this.kryptonHeaderGroupRightTop.Panel.Padding = new System.Windows.Forms.Padding(5);
this.kryptonHeaderGroupRightTop.Size = new System.Drawing.Size(278, 133);
this.kryptonHeaderGroupRightTop.TabIndex = 0;
this.kryptonHeaderGroupRightTop.ValuesPrimary.Heading = "Right Top";
this.kryptonHeaderGroupRightTop.ValuesPrimary.Image = null;
//
// textBoxRightTop
//
this.textBoxRightTop.BackColor = System.Drawing.Color.White;
this.textBoxRightTop.Dock = System.Windows.Forms.DockStyle.Fill;
this.textBoxRightTop.Location = new System.Drawing.Point(5, 5);
this.textBoxRightTop.Multiline = true;
this.textBoxRightTop.Name = "textBoxRightTop";
this.textBoxRightTop.ReadOnly = true;
this.textBoxRightTop.Size = new System.Drawing.Size(266, 92);
this.textBoxRightTop.StateCommon.Border.Draw = ComponentFactory.Krypton.Toolkit.InheritBool.False;
this.textBoxRightTop.StateCommon.Border.DrawBorders = ((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders)((((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Top | ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Bottom)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Left)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Right)));
this.textBoxRightTop.TabIndex = 0;
this.textBoxRightTop.Text = "Use the arrow buttons on the headers to toggle the expanded/collapsed state.\r\n\r\nA" +
" step by step tutorial on building this kind of expanding/collapsing layout can " +
"be found in the help documentation.";
//
// kryptonHeaderGroupRightBottom
//
this.kryptonHeaderGroupRightBottom.ButtonSpecs.AddRange(new ComponentFactory.Krypton.Toolkit.ButtonSpecHeaderGroup[] {
this.buttonSpecUpDown});
this.kryptonHeaderGroupRightBottom.Dock = System.Windows.Forms.DockStyle.Fill;
this.kryptonHeaderGroupRightBottom.HeaderVisibleSecondary = false;
this.kryptonHeaderGroupRightBottom.Location = new System.Drawing.Point(0, 0);
this.kryptonHeaderGroupRightBottom.Name = "kryptonHeaderGroupRightBottom";
//
// kryptonHeaderGroupRightBottom.Panel
//
this.kryptonHeaderGroupRightBottom.Panel.Controls.Add(this.textBoxRightBottom);
this.kryptonHeaderGroupRightBottom.Panel.Padding = new System.Windows.Forms.Padding(5);
this.kryptonHeaderGroupRightBottom.Size = new System.Drawing.Size(278, 161);
this.kryptonHeaderGroupRightBottom.TabIndex = 0;
this.kryptonHeaderGroupRightBottom.ValuesPrimary.Heading = "Right Bottom";
this.kryptonHeaderGroupRightBottom.ValuesPrimary.Image = null;
//
// buttonSpecUpDown
//
this.buttonSpecUpDown.ColorMap = System.Drawing.Color.Black;
this.buttonSpecUpDown.Type = ComponentFactory.Krypton.Toolkit.PaletteButtonSpecStyle.ArrowDown;
this.buttonSpecUpDown.UniqueName = "0A33A54B77ED443B0A33A54B77ED443B";
//
// textBoxRightBottom
//
this.textBoxRightBottom.BackColor = System.Drawing.Color.White;
this.textBoxRightBottom.Dock = System.Windows.Forms.DockStyle.Fill;
this.textBoxRightBottom.Location = new System.Drawing.Point(5, 5);
this.textBoxRightBottom.Multiline = true;
this.textBoxRightBottom.Name = "textBoxRightBottom";
this.textBoxRightBottom.ReadOnly = true;
this.textBoxRightBottom.Size = new System.Drawing.Size(266, 120);
this.textBoxRightBottom.StateCommon.Border.Draw = ComponentFactory.Krypton.Toolkit.InheritBool.False;
this.textBoxRightBottom.StateCommon.Border.DrawBorders = ((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders)((((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Top | ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Bottom)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Left)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Right)));
this.textBoxRightBottom.TabIndex = 0;
this.textBoxRightBottom.Text = resources.GetString("textBoxRightBottom.Text");
//
// toolStrip
//
this.toolStrip.Dock = System.Windows.Forms.DockStyle.None;
this.toolStrip.Font = new System.Drawing.Font("Segoe UI", 9F);
this.toolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolOffice2010,
this.toolOffice2007,
this.toolSparkle,
this.toolSystem});
this.toolStrip.Location = new System.Drawing.Point(3, 0);
this.toolStrip.Name = "toolStrip";
this.toolStrip.Size = new System.Drawing.Size(180, 25);
this.toolStrip.TabIndex = 0;
//
// toolOffice2010
//
this.toolOffice2010.Checked = true;
this.toolOffice2010.CheckState = System.Windows.Forms.CheckState.Checked;
this.toolOffice2010.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.toolOffice2010.Image = ((System.Drawing.Image)(resources.GetObject("toolOffice2010.Image")));
this.toolOffice2010.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolOffice2010.Name = "toolOffice2010";
this.toolOffice2010.Size = new System.Drawing.Size(35, 22);
this.toolOffice2010.Text = "2010";
this.toolOffice2010.Click += new System.EventHandler(this.toolOffice2010_Click);
//
// toolOffice2007
//
this.toolOffice2007.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.toolOffice2007.Image = ((System.Drawing.Image)(resources.GetObject("toolOffice2007.Image")));
this.toolOffice2007.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolOffice2007.Name = "toolOffice2007";
this.toolOffice2007.Size = new System.Drawing.Size(35, 22);
this.toolOffice2007.Text = "2007";
this.toolOffice2007.Click += new System.EventHandler(this.toolOffice2007_Click);
//
// toolSparkle
//
this.toolSparkle.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.toolSparkle.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolSparkle.Name = "toolSparkle";
this.toolSparkle.Size = new System.Drawing.Size(49, 22);
this.toolSparkle.Text = "Sparkle";
this.toolSparkle.Click += new System.EventHandler(this.toolSparkle_Click);
//
// toolSystem
//
this.toolSystem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.toolSystem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolSystem.Name = "toolSystem";
this.toolSystem.Size = new System.Drawing.Size(49, 22);
this.toolSystem.Text = "System";
this.toolSystem.Click += new System.EventHandler(this.toolSystem_Click);
//
// statusStrip1
//
this.statusStrip1.Font = new System.Drawing.Font("Segoe UI", 9F);
this.statusStrip1.Location = new System.Drawing.Point(0, 358);
this.statusStrip1.Name = "statusStrip1";
this.statusStrip1.RenderMode = System.Windows.Forms.ToolStripRenderMode.ManagerRenderMode;
this.statusStrip1.Size = new System.Drawing.Size(460, 22);
this.statusStrip1.TabIndex = 3;
this.statusStrip1.Text = "statusStrip1";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(460, 380);
this.Controls.Add(this.toolStripContainer1);
this.Controls.Add(this.menuStrip);
this.Controls.Add(this.statusStrip1);
this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MainMenuStrip = this.menuStrip;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.MinimumSize = new System.Drawing.Size(300, 300);
this.Name = "Form1";
this.Text = "Expanding HeaderGroups (Splitters)";
this.Load += new System.EventHandler(this.Form1_Load);
this.menuStrip.ResumeLayout(false);
this.menuStrip.PerformLayout();
this.toolStripContainer1.ContentPanel.ResumeLayout(false);
this.toolStripContainer1.TopToolStripPanel.ResumeLayout(false);
this.toolStripContainer1.TopToolStripPanel.PerformLayout();
this.toolStripContainer1.ResumeLayout(false);
this.toolStripContainer1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.kryptonPanel1)).EndInit();
this.kryptonPanel1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.kryptonSplitContainerHorizontal.Panel1)).EndInit();
this.kryptonSplitContainerHorizontal.Panel1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.kryptonSplitContainerHorizontal.Panel2)).EndInit();
this.kryptonSplitContainerHorizontal.Panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.kryptonSplitContainerHorizontal)).EndInit();
this.kryptonSplitContainerHorizontal.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.kryptonHeaderGroupLeft.Panel)).EndInit();
this.kryptonHeaderGroupLeft.Panel.ResumeLayout(false);
this.kryptonHeaderGroupLeft.Panel.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.kryptonHeaderGroupLeft)).EndInit();
this.kryptonHeaderGroupLeft.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.kryptonSplitContainerVertical.Panel1)).EndInit();
this.kryptonSplitContainerVertical.Panel1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.kryptonSplitContainerVertical.Panel2)).EndInit();
this.kryptonSplitContainerVertical.Panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.kryptonSplitContainerVertical)).EndInit();
this.kryptonSplitContainerVertical.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.kryptonHeaderGroupRightTop.Panel)).EndInit();
this.kryptonHeaderGroupRightTop.Panel.ResumeLayout(false);
this.kryptonHeaderGroupRightTop.Panel.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.kryptonHeaderGroupRightTop)).EndInit();
this.kryptonHeaderGroupRightTop.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.kryptonHeaderGroupRightBottom.Panel)).EndInit();
this.kryptonHeaderGroupRightBottom.Panel.ResumeLayout(false);
this.kryptonHeaderGroupRightBottom.Panel.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.kryptonHeaderGroupRightBottom)).EndInit();
this.kryptonHeaderGroupRightBottom.ResumeLayout(false);
this.toolStrip.ResumeLayout(false);
this.toolStrip.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private ComponentFactory.Krypton.Toolkit.KryptonTextBox textBoxRightTop;
private ComponentFactory.Krypton.Toolkit.KryptonTextBox textBoxLeft;
private ComponentFactory.Krypton.Toolkit.KryptonTextBox textBoxRightBottom;
private System.Windows.Forms.MenuStrip menuStrip;
private System.Windows.Forms.ToolStrip toolStrip;
private System.Windows.Forms.ToolStripContainer toolStripContainer1;
private ComponentFactory.Krypton.Toolkit.KryptonPanel kryptonPanel1;
private ComponentFactory.Krypton.Toolkit.KryptonManager kryptonManager;
private ComponentFactory.Krypton.Toolkit.KryptonSplitContainer kryptonSplitContainerHorizontal;
private ComponentFactory.Krypton.Toolkit.KryptonHeaderGroup kryptonHeaderGroupLeft;
private ComponentFactory.Krypton.Toolkit.KryptonSplitContainer kryptonSplitContainerVertical;
private ComponentFactory.Krypton.Toolkit.KryptonHeaderGroup kryptonHeaderGroupRightTop;
private ComponentFactory.Krypton.Toolkit.KryptonHeaderGroup kryptonHeaderGroupRightBottom;
private ComponentFactory.Krypton.Toolkit.ButtonSpecHeaderGroup buttonSpecUpDown;
private ComponentFactory.Krypton.Toolkit.ButtonSpecHeaderGroup buttonSpecLeftRight;
private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem menuSystem;
private System.Windows.Forms.ToolStripMenuItem menuSparkle;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripButton toolSystem;
private System.Windows.Forms.ToolStripButton toolSparkle;
private System.Windows.Forms.ToolStripMenuItem menuOffice2010;
private System.Windows.Forms.ToolStripMenuItem menuOffice2007;
private System.Windows.Forms.ToolStripButton toolOffice2007;
private System.Windows.Forms.ToolStripButton toolOffice2010;
private System.Windows.Forms.StatusStrip statusStrip1;
}
}
| |
namespace BooCompiler.Tests
{
using NUnit.Framework;
[TestFixture]
public class PrimitivesIntegrationTestFixture : AbstractCompilerTestCase
{
[Test]
public void at_operator()
{
RunCompilerTestCase(@"at-operator.boo");
}
[Test]
public void bool_1()
{
RunCompilerTestCase(@"bool-1.boo");
}
[Test]
public void char_1()
{
RunCompilerTestCase(@"char-1.boo");
}
[Test]
public void char_2()
{
RunCompilerTestCase(@"char-2.boo");
}
[Test]
public void char_3()
{
RunCompilerTestCase(@"char-3.boo");
}
[Test]
public void char_4()
{
RunCompilerTestCase(@"char-4.boo");
}
[Test]
public void char_5()
{
RunCompilerTestCase(@"char-5.boo");
}
[Test]
public void checked_1()
{
RunCompilerTestCase(@"checked-1.boo");
}
[Test]
public void decimal_1()
{
RunCompilerTestCase(@"decimal-1.boo");
}
[Test]
public void default_1()
{
RunCompilerTestCase(@"default-1.boo");
}
[Test]
public void double_as_bool_1()
{
RunCompilerTestCase(@"double-as-bool-1.boo");
}
[Test]
public void double_precision_is_used_for_literals()
{
RunCompilerTestCase(@"double-precision-is-used-for-literals.boo");
}
[Test]
public void hash_1()
{
RunCompilerTestCase(@"hash-1.boo");
}
[Test]
public void hex_1()
{
RunCompilerTestCase(@"hex-1.boo");
}
[Test]
public void hex_2()
{
RunCompilerTestCase(@"hex-2.boo");
}
[Ignore("implicit casts for comparison operators still not implemented")][Test]
public void implicit_casts_1()
{
RunCompilerTestCase(@"implicit-casts-1.boo");
}
[Test]
public void int_shift_overflow_checked()
{
RunCompilerTestCase(@"int-shift-overflow-checked.boo");
}
[Test]
public void int_shift_overflow_unchecked()
{
RunCompilerTestCase(@"int-shift-overflow-unchecked.boo");
}
[Test]
public void interpolation_1()
{
RunCompilerTestCase(@"interpolation-1.boo");
}
[Test]
public void len_1()
{
RunCompilerTestCase(@"len-1.boo");
}
[Test]
public void list_1()
{
RunCompilerTestCase(@"list-1.boo");
}
[Test]
public void list_2()
{
RunCompilerTestCase(@"list-2.boo");
}
[Test]
public void list_3()
{
RunCompilerTestCase(@"list-3.boo");
}
[Test]
public void long_1()
{
RunCompilerTestCase(@"long-1.boo");
}
[Test]
public void primitives_1()
{
RunCompilerTestCase(@"primitives-1.boo");
}
[Test]
public void promotion_1()
{
RunCompilerTestCase(@"promotion-1.boo");
}
[Test]
public void promotion_2()
{
RunCompilerTestCase(@"promotion-2.boo");
}
[Test]
public void regex_1()
{
RunCompilerTestCase(@"regex-1.boo");
}
[Test]
public void single_as_bool_1()
{
RunCompilerTestCase(@"single-as-bool-1.boo");
}
[Test]
public void string_1()
{
RunCompilerTestCase(@"string-1.boo");
}
[Test]
public void string_yields_chars()
{
RunCompilerTestCase(@"string-yields-chars.boo");
}
[Test]
public void typeof_1()
{
RunCompilerTestCase(@"typeof-1.boo");
}
[Test]
public void typeof_2()
{
RunCompilerTestCase(@"typeof-2.boo");
}
[Test]
public void uint_1()
{
RunCompilerTestCase(@"uint-1.boo");
}
[Test]
public void uint_argument()
{
RunCompilerTestCase(@"uint-argument.boo");
}
[Test]
public void uint_field_initializer()
{
RunCompilerTestCase(@"uint-field-initializer.boo");
}
[Test]
public void ulong_bitshift()
{
RunCompilerTestCase(@"ulong-bitshift.boo");
}
[Test]
public void unsigned_1()
{
RunCompilerTestCase(@"unsigned-1.boo");
}
[Test]
public void unsigned_2()
{
RunCompilerTestCase(@"unsigned-2.boo");
}
[Test]
public void __switch___1()
{
RunCompilerTestCase(@"__switch__-1.boo");
}
override protected string GetRelativeTestCasesPath()
{
return "integration/primitives";
}
}
}
| |
#region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion
namespace System.Web.UI
{
public partial class HtmlBuilder
{
/// <summary>
/// Adds the attribute.
/// </summary>
/// <param name="attribute">The attribute.</param>
/// <param name="value">The value.</param>
public void AddAttribute(string attribute, string value)
{
if (string.IsNullOrEmpty(attribute))
throw new ArgumentNullException("attribute");
_writeCount++;
if (!attribute.StartsWith("style", StringComparison.OrdinalIgnoreCase))
_textWriter.AddAttribute(attribute, value);
else
_textWriter.AddStyleAttribute(attribute.Substring(5), value);
}
/// <summary>
/// Adds the attribute.
/// </summary>
/// <param name="attribute">The attribute.</param>
/// <param name="value">The value.</param>
public void AddAttribute(HtmlAttribute attribute, string value)
{
_writeCount++;
var attribute2 = (int)attribute;
if (attribute2 < HtmlTextWriterEx.HtmlAttributeSplit)
_textWriter.AddAttribute((HtmlTextWriterAttribute)attribute2, value);
else if (attribute2 > HtmlTextWriterEx.HtmlAttributeSplit)
_textWriter.AddStyleAttribute((HtmlTextWriterStyle)attribute2 - HtmlTextWriterEx.HtmlAttributeSplit - 1, value);
else
throw new ArgumentException(string.Format("Local.InvalidHtmlAttribA", attribute.ToString()), "attribute");
}
//public void AddAttribute(params string[] args) { AddAttribute(Nparams.Parse(args), null); }
/// <summary>
/// Adds the attribute.
/// </summary>
/// <param name="args">The args.</param>
/// <param name="throwOnAttributes">The throw on attributes.</param>
public void AddAttribute(Nparams args, string[] throwOnAttributes)
{
if (args == null)
throw new ArgumentNullException("args");
//foreach (string key in attrib.KeyEnum)
//{
// var value = attrib[key];
// int htmlAttrib;
// if (s_htmlAttribEnumInt32Parser.TryGetValue(key, out htmlAttrib) == true)
// {
// AddAttribute((HtmlAttrib)htmlAttrib, value);
// continue;
// }
// else if (key.Length > 0)
// {
// _writeCount++;
// if (key.StartsWith("style", System.StringComparison.InvariantCultureIgnoreCase) == false)
// {
// _textWriter.AddAttribute(key, value);
// continue;
// }
// _textWriter.AddStyleAttribute(key.Substring(5), value);
// continue;
// }
// throw new ArgumentException(string.Format(Local.InvalidHtmlAttribA, key), "attrib");
//}
}
/// <summary>
/// Adds the text writer attribute.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="value">The value.</param>
public void AddTextWriterAttribute(string name, string value) { _writeCount++; _textWriter.AddAttribute(name, value); }
/// <summary>
/// Adds the text writer attribute.
/// </summary>
/// <param name="attribute">The attribute.</param>
/// <param name="value">The value.</param>
public void AddTextWriterAttribute(HtmlTextWriterAttribute attribute, string value) { _writeCount++; _textWriter.AddAttribute(attribute, value); }
/// <summary>
/// Adds the text writer style attribute.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="value">The value.</param>
public void AddTextWriterStyleAttribute(string name, string value) { _writeCount++; _textWriter.AddStyleAttribute(name, value); }
/// <summary>
/// Adds the text writer style attribute.
/// </summary>
/// <param name="attribute">The attribute.</param>
/// <param name="value">The value.</param>
public void AddTextWriterStyleAttribute(HtmlTextWriterStyle attribute, string value) { _writeCount++; _textWriter.AddStyleAttribute(attribute, value); }
/// <summary>
/// Begins the HTML tag.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="args">The args.</param>
/// <returns></returns>
public HtmlBuilder BeginHtmlTag(HtmlTag tag, params string[] args) { return BeginHtmlTag(tag, Nparams.Parse(args)); }
/// <summary>
/// Begins the HTML tag.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="args">The args.</param>
/// <returns></returns>
public HtmlBuilder BeginHtmlTag(HtmlTag tag, Nparams args)
{
if (tag == HtmlTag.Unknown || tag >= HtmlTag._FormReference)
throw new ArgumentException(string.Format("Local.InvalidHtmlTagA", tag.ToString()), "tag");
_writeCount++;
if (args != null)
AddAttribute(args, null);
_textWriter.RenderBeginTag((HtmlTextWriterTag)tag);
return this;
}
/// <summary>
/// Begins the HTML tag.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="args">The args.</param>
/// <returns></returns>
public HtmlBuilder BeginHtmlTag(string tag, params string[] args) { return BeginHtmlTag(tag, Nparams.Parse(args)); }
/// <summary>
/// Begins the HTML tag.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="args">The args.</param>
/// <returns></returns>
public HtmlBuilder BeginHtmlTag(string tag, Nparams args)
{
if (string.IsNullOrEmpty(tag))
throw new ArgumentNullException("tag");
_writeCount++;
if (args != null)
AddAttribute(args, null);
_textWriter.RenderBeginTag(tag);
return this;
}
/// <summary>
/// Empties the HTML tag.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="args">The args.</param>
/// <returns></returns>
public HtmlBuilder EmptyHtmlTag(HtmlTag tag, params string[] args) { return EmptyHtmlTag(tag, Nparams.Parse(args)); }
/// <summary>
/// Empties the HTML tag.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="args">The args.</param>
/// <returns></returns>
public HtmlBuilder EmptyHtmlTag(HtmlTag tag, Nparams args)
{
if (tag == HtmlTag.Unknown || tag >= HtmlTag._FormReference)
throw new ArgumentException(string.Format("Local.InvalidHtmlTagA", tag.ToString()), "tag");
_writeCount++;
if (args != null)
AddAttribute(args, null);
_textWriter.RenderBeginTag((HtmlTextWriterTag)tag);
_textWriter.RenderEndTag();
return this;
}
/// <summary>
/// Empties the HTML tag.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="args">The args.</param>
/// <returns></returns>
public HtmlBuilder EmptyHtmlTag(string tag, params string[] args) { return EmptyHtmlTag(tag, Nparams.Parse(args)); }
/// <summary>
/// Empties the HTML tag.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="args">The args.</param>
/// <returns></returns>
public HtmlBuilder EmptyHtmlTag(string tag, Nparams args)
{
if (string.IsNullOrEmpty(tag))
throw new ArgumentNullException("tag");
_writeCount++;
if (args != null)
AddAttribute(args, null);
_textWriter.RenderBeginTag(tag);
_textWriter.RenderEndTag();
return this;
}
/// <summary>
/// Ends the HTML tag.
/// </summary>
/// <returns></returns>
public HtmlBuilder EndHtmlTag()
{
_writeCount++;
_textWriter.RenderEndTag();
return this;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
**
** Purpose: Create a stream over unmanaged memory, mostly
** useful for memory-mapped files.
**
**
===========================================================*/
using System;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Threading;
using System.Diagnostics.Contracts;
using System.Threading.Tasks;
namespace System.IO {
/*
* This class is used to access a contiguous block of memory, likely outside
* the GC heap (or pinned in place in the GC heap, but a MemoryStream may
* make more sense in those cases). It's great if you have a pointer and
* a length for a section of memory mapped in by someone else and you don't
* want to copy this into the GC heap. UnmanagedMemoryStream assumes these
* two things:
*
* 1) All the memory in the specified block is readable or writable,
* depending on the values you pass to the constructor.
* 2) The lifetime of the block of memory is at least as long as the lifetime
* of the UnmanagedMemoryStream.
* 3) You clean up the memory when appropriate. The UnmanagedMemoryStream
* currently will do NOTHING to free this memory.
* 4) All calls to Write and WriteByte may not be threadsafe currently.
*
* It may become necessary to add in some sort of
* DeallocationMode enum, specifying whether we unmap a section of memory,
* call free, run a user-provided delegate to free the memory, etc etc.
* We'll suggest user write a subclass of UnmanagedMemoryStream that uses
* a SafeHandle subclass to hold onto the memory.
* Check for problems when using this in the negative parts of a
* process's address space. We may need to use unsigned longs internally
* and change the overflow detection logic.
*
* -----SECURITY MODEL AND SILVERLIGHT-----
* A few key notes about exposing UMS in silverlight:
* 1. No ctors are exposed to transparent code. This version of UMS only
* supports byte* (not SafeBuffer). Therefore, framework code can create
* a UMS and hand it to transparent code. Transparent code can use most
* operations on a UMS, but not operations that directly expose a
* pointer.
*
* 2. Scope of "unsafe" and non-CLS compliant operations reduced: The
* Whidbey version of this class has CLSCompliant(false) at the class
* level and unsafe modifiers at the method level. These were reduced to
* only where the unsafe operation is performed -- i.e. immediately
* around the pointer manipulation. Note that this brings UMS in line
* with recent changes in pu/clr to support SafeBuffer.
*
* 3. Currently, the only caller that creates a UMS is ResourceManager,
* which creates read-only UMSs, and therefore operations that can
* change the length will throw because write isn't supported. A
* conservative option would be to formalize the concept that _only_
* read-only UMSs can be creates, and enforce this by making WriteX and
* SetLength SecurityCritical. However, this is a violation of
* security inheritance rules, so we must keep these safe. The
* following notes make this acceptable for future use.
* a. a race condition in WriteX that could have allowed a thread to
* read from unzeroed memory was fixed
* b. memory region cannot be expanded beyond _capacity; in other
* words, a UMS creator is saying a writeable UMS is safe to
* write to anywhere in the memory range up to _capacity, specified
* in the ctor. Even if the caller doesn't specify a capacity, then
* length is used as the capacity.
*/
public class UnmanagedMemoryStream : Stream
{
private const long UnmanagedMemStreamMaxLength = Int64.MaxValue;
[System.Security.SecurityCritical] // auto-generated
private SafeBuffer _buffer;
[SecurityCritical]
private unsafe byte* _mem;
private long _length;
private long _capacity;
private long _position;
private long _offset;
private FileAccess _access;
internal bool _isOpen;
[NonSerialized]
private Task<Int32> _lastReadTask; // The last successful task returned from ReadAsync
// Needed for subclasses that need to map a file, etc.
[System.Security.SecuritySafeCritical] // auto-generated
protected UnmanagedMemoryStream()
{
unsafe {
_mem = null;
}
_isOpen = false;
}
[System.Security.SecuritySafeCritical] // auto-generated
public UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length) {
Initialize(buffer, offset, length, FileAccess.Read, false);
}
[System.Security.SecuritySafeCritical] // auto-generated
public UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length, FileAccess access) {
Initialize(buffer, offset, length, access, false);
}
// We must create one of these without doing a security check. This
// class is created while security is trying to start up. Plus, doing
// a Demand from Assembly.GetManifestResourceStream isn't useful.
[System.Security.SecurityCritical] // auto-generated
internal UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length, FileAccess access, bool skipSecurityCheck) {
Initialize(buffer, offset, length, access, skipSecurityCheck);
}
[System.Security.SecuritySafeCritical] // auto-generated
protected void Initialize(SafeBuffer buffer, long offset, long length, FileAccess access) {
Initialize(buffer, offset, length, access, false);
}
[System.Security.SecurityCritical] // auto-generated
internal void Initialize(SafeBuffer buffer, long offset, long length, FileAccess access, bool skipSecurityCheck) {
if (buffer == null) {
throw new ArgumentNullException("buffer");
}
if (offset < 0) {
throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
if (length < 0) {
throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
if (buffer.ByteLength < (ulong)(offset + length)) {
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidSafeBufferOffLen"));
}
if (access < FileAccess.Read || access > FileAccess.ReadWrite) {
throw new ArgumentOutOfRangeException("access");
}
Contract.EndContractBlock();
if (_isOpen) {
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CalledTwice"));
}
if (!skipSecurityCheck) {
#pragma warning disable 618
new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
#pragma warning restore 618
}
// check for wraparound
unsafe {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
try {
buffer.AcquirePointer(ref pointer);
if ( (pointer + offset + length) < pointer) {
throw new ArgumentException(Environment.GetResourceString("ArgumentOutOfRange_UnmanagedMemStreamWrapAround"));
}
}
finally {
if (pointer != null) {
buffer.ReleasePointer();
}
}
}
_offset = offset;
_buffer = buffer;
_length = length;
_capacity = length;
_access = access;
_isOpen = true;
}
[System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
public unsafe UnmanagedMemoryStream(byte* pointer, long length)
{
Initialize(pointer, length, length, FileAccess.Read, false);
}
[System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
public unsafe UnmanagedMemoryStream(byte* pointer, long length, long capacity, FileAccess access)
{
Initialize(pointer, length, capacity, access, false);
}
// We must create one of these without doing a security check. This
// class is created while security is trying to start up. Plus, doing
// a Demand from Assembly.GetManifestResourceStream isn't useful.
[System.Security.SecurityCritical] // auto-generated
internal unsafe UnmanagedMemoryStream(byte* pointer, long length, long capacity, FileAccess access, bool skipSecurityCheck)
{
Initialize(pointer, length, capacity, access, skipSecurityCheck);
}
[System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
protected unsafe void Initialize(byte* pointer, long length, long capacity, FileAccess access)
{
Initialize(pointer, length, capacity, access, false);
}
[System.Security.SecurityCritical] // auto-generated
internal unsafe void Initialize(byte* pointer, long length, long capacity, FileAccess access, bool skipSecurityCheck)
{
if (pointer == null)
throw new ArgumentNullException("pointer");
if (length < 0 || capacity < 0)
throw new ArgumentOutOfRangeException((length < 0) ? "length" : "capacity", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (length > capacity)
throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_LengthGreaterThanCapacity"));
Contract.EndContractBlock();
// Check for wraparound.
if (((byte*) ((long)pointer + capacity)) < pointer)
throw new ArgumentOutOfRangeException("capacity", Environment.GetResourceString("ArgumentOutOfRange_UnmanagedMemStreamWrapAround"));
if (access < FileAccess.Read || access > FileAccess.ReadWrite)
throw new ArgumentOutOfRangeException("access", Environment.GetResourceString("ArgumentOutOfRange_Enum"));
if (_isOpen)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CalledTwice"));
if (!skipSecurityCheck)
#pragma warning disable 618
new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
#pragma warning restore 618
_mem = pointer;
_offset = 0;
_length = length;
_capacity = capacity;
_access = access;
_isOpen = true;
}
public override bool CanRead {
[Pure]
get { return _isOpen && (_access & FileAccess.Read) != 0; }
}
public override bool CanSeek {
[Pure]
get { return _isOpen; }
}
public override bool CanWrite {
[Pure]
get { return _isOpen && (_access & FileAccess.Write) != 0; }
}
[System.Security.SecuritySafeCritical] // auto-generated
protected override void Dispose(bool disposing)
{
_isOpen = false;
unsafe { _mem = null; }
// Stream allocates WaitHandles for async calls. So for correctness
// call base.Dispose(disposing) for better perf, avoiding waiting
// for the finalizers to run on those types.
base.Dispose(disposing);
}
public override void Flush() {
if (!_isOpen) __Error.StreamIsClosed();
}
[HostProtection(ExternalThreading=true)]
[ComVisible(false)]
public override Task FlushAsync(CancellationToken cancellationToken) {
if (cancellationToken.IsCancellationRequested)
return Task.FromCancellation(cancellationToken);
try {
Flush();
return Task.CompletedTask;
} catch(Exception ex) {
return Task.FromException(ex);
}
}
public override long Length {
get {
if (!_isOpen) __Error.StreamIsClosed();
return Interlocked.Read(ref _length);
}
}
public long Capacity {
get {
if (!_isOpen) __Error.StreamIsClosed();
return _capacity;
}
}
public override long Position {
get {
if (!CanSeek) __Error.StreamIsClosed();
Contract.EndContractBlock();
return Interlocked.Read(ref _position);
}
[System.Security.SecuritySafeCritical] // auto-generated
set {
if (value < 0)
throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
if (!CanSeek) __Error.StreamIsClosed();
#if WIN32
unsafe {
// On 32 bit machines, ensure we don't wrap around.
if (value > (long) Int32.MaxValue || _mem + value < _mem)
throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_StreamLength"));
}
#endif
Interlocked.Exchange(ref _position, value);
}
}
[CLSCompliant(false)]
public unsafe byte* PositionPointer {
[System.Security.SecurityCritical] // auto-generated_required
get {
if (_buffer != null) {
throw new NotSupportedException(Environment.GetResourceString("NotSupported_UmsSafeBuffer"));
}
// Use a temp to avoid a race
long pos = Interlocked.Read(ref _position);
if (pos > _capacity)
throw new IndexOutOfRangeException(Environment.GetResourceString("IndexOutOfRange_UMSPosition"));
byte * ptr = _mem + pos;
if (!_isOpen) __Error.StreamIsClosed();
return ptr;
}
[System.Security.SecurityCritical] // auto-generated_required
set {
if (_buffer != null)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_UmsSafeBuffer"));
if (!_isOpen) __Error.StreamIsClosed();
// Note: subtracting pointers returns an Int64. Working around
// to avoid hitting compiler warning CS0652 on this line.
if (new IntPtr(value - _mem).ToInt64() > UnmanagedMemStreamMaxLength)
throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_UnmanagedMemStreamLength"));
if (value < _mem)
throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin"));
Interlocked.Exchange(ref _position, value - _mem);
}
}
internal unsafe byte* Pointer {
[System.Security.SecurityCritical] // auto-generated
get {
if (_buffer != null)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_UmsSafeBuffer"));
return _mem;
}
}
[System.Security.SecuritySafeCritical] // auto-generated
public override int Read([In, Out] byte[] buffer, int offset, int count) {
if (buffer==null)
throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
if (offset < 0)
throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - offset < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock(); // Keep this in sync with contract validation in ReadAsync
if (!_isOpen) __Error.StreamIsClosed();
if (!CanRead) __Error.ReadNotSupported();
// Use a local variable to avoid a race where another thread
// changes our position after we decide we can read some bytes.
long pos = Interlocked.Read(ref _position);
long len = Interlocked.Read(ref _length);
long n = len - pos;
if (n > count)
n = count;
if (n <= 0)
return 0;
int nInt = (int) n; // Safe because n <= count, which is an Int32
if (nInt < 0)
nInt = 0; // _position could be beyond EOF
Contract.Assert(pos + nInt >= 0, "_position + n >= 0"); // len is less than 2^63 -1.
if (_buffer != null) {
unsafe {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
try {
_buffer.AcquirePointer(ref pointer);
Buffer.Memcpy(buffer, offset, pointer + pos + _offset, 0, nInt);
}
finally {
if (pointer != null) {
_buffer.ReleasePointer();
}
}
}
}
else {
unsafe {
Buffer.Memcpy(buffer, offset, _mem + pos, 0, nInt);
}
}
Interlocked.Exchange(ref _position, pos + n);
return nInt;
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task<Int32> ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) {
if (buffer==null)
throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
if (offset < 0)
throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - offset < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock(); // contract validation copied from Read(...)
if (cancellationToken.IsCancellationRequested)
return Task.FromCancellation<Int32>(cancellationToken);
try {
Int32 n = Read(buffer, offset, count);
Task<Int32> t = _lastReadTask;
return (t != null && t.Result == n) ? t : (_lastReadTask = Task.FromResult<Int32>(n));
} catch (Exception ex) {
Contract.Assert(! (ex is OperationCanceledException));
return Task.FromException<Int32>(ex);
}
}
[System.Security.SecuritySafeCritical] // auto-generated
public override int ReadByte() {
if (!_isOpen) __Error.StreamIsClosed();
if (!CanRead) __Error.ReadNotSupported();
long pos = Interlocked.Read(ref _position); // Use a local to avoid a race condition
long len = Interlocked.Read(ref _length);
if (pos >= len)
return -1;
Interlocked.Exchange(ref _position, pos + 1);
int result;
if (_buffer != null) {
unsafe {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
try {
_buffer.AcquirePointer(ref pointer);
result = *(pointer + pos + _offset);
}
finally {
if (pointer != null) {
_buffer.ReleasePointer();
}
}
}
}
else {
unsafe {
result = _mem[pos];
}
}
return result;
}
public override long Seek(long offset, SeekOrigin loc) {
if (!_isOpen) __Error.StreamIsClosed();
if (offset > UnmanagedMemStreamMaxLength)
throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_UnmanagedMemStreamLength"));
switch(loc) {
case SeekOrigin.Begin:
if (offset < 0)
throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin"));
Interlocked.Exchange(ref _position, offset);
break;
case SeekOrigin.Current:
long pos = Interlocked.Read(ref _position);
if (offset + pos < 0)
throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin"));
Interlocked.Exchange(ref _position, offset + pos);
break;
case SeekOrigin.End:
long len = Interlocked.Read(ref _length);
if (len + offset < 0)
throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin"));
Interlocked.Exchange(ref _position, len + offset);
break;
default:
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidSeekOrigin"));
}
long finalPos = Interlocked.Read(ref _position);
Contract.Assert(finalPos >= 0, "_position >= 0");
return finalPos;
}
[System.Security.SecuritySafeCritical] // auto-generated
public override void SetLength(long value) {
if (value < 0)
throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
if (_buffer != null)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_UmsSafeBuffer"));
if (!_isOpen) __Error.StreamIsClosed();
if (!CanWrite) __Error.WriteNotSupported();
if (value > _capacity)
throw new IOException(Environment.GetResourceString("IO.IO_FixedCapacity"));
long pos = Interlocked.Read(ref _position);
long len = Interlocked.Read(ref _length);
if (value > len) {
unsafe {
Buffer.ZeroMemory(_mem+len, value-len);
}
}
Interlocked.Exchange(ref _length, value);
if (pos > value) {
Interlocked.Exchange(ref _position, value);
}
}
[System.Security.SecuritySafeCritical] // auto-generated
public override void Write(byte[] buffer, int offset, int count) {
if (buffer==null)
throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
if (offset < 0)
throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - offset < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock(); // Keep contract validation in sync with WriteAsync(..)
if (!_isOpen) __Error.StreamIsClosed();
if (!CanWrite) __Error.WriteNotSupported();
long pos = Interlocked.Read(ref _position); // Use a local to avoid a race condition
long len = Interlocked.Read(ref _length);
long n = pos + count;
// Check for overflow
if (n < 0)
throw new IOException(Environment.GetResourceString("IO.IO_StreamTooLong"));
if (n > _capacity) {
throw new NotSupportedException(Environment.GetResourceString("IO.IO_FixedCapacity"));
}
if (_buffer == null) {
// Check to see whether we are now expanding the stream and must
// zero any memory in the middle.
if (pos > len) {
unsafe {
Buffer.ZeroMemory(_mem+len, pos-len);
}
}
// set length after zeroing memory to avoid race condition of accessing unzeroed memory
if (n > len) {
Interlocked.Exchange(ref _length, n);
}
}
if (_buffer != null) {
long bytesLeft = _capacity - pos;
if (bytesLeft < count) {
throw new ArgumentException(Environment.GetResourceString("Arg_BufferTooSmall"));
}
unsafe {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
try {
_buffer.AcquirePointer(ref pointer);
Buffer.Memcpy(pointer + pos + _offset, 0, buffer, offset, count);
}
finally {
if (pointer != null) {
_buffer.ReleasePointer();
}
}
}
}
else {
unsafe {
Buffer.Memcpy(_mem + pos, 0, buffer, offset, count);
}
}
Interlocked.Exchange(ref _position, n);
return;
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) {
if (buffer==null)
throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
if (offset < 0)
throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - offset < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock(); // contract validation copied from Write(..)
if (cancellationToken.IsCancellationRequested)
return Task.FromCancellation(cancellationToken);
try {
Write(buffer, offset, count);
return Task.CompletedTask;
} catch (Exception ex) {
Contract.Assert(! (ex is OperationCanceledException));
return Task.FromException<Int32>(ex);
}
}
[System.Security.SecuritySafeCritical] // auto-generated
public override void WriteByte(byte value) {
if (!_isOpen) __Error.StreamIsClosed();
if (!CanWrite) __Error.WriteNotSupported();
long pos = Interlocked.Read(ref _position); // Use a local to avoid a race condition
long len = Interlocked.Read(ref _length);
long n = pos + 1;
if (pos >= len) {
// Check for overflow
if (n < 0)
throw new IOException(Environment.GetResourceString("IO.IO_StreamTooLong"));
if (n > _capacity)
throw new NotSupportedException(Environment.GetResourceString("IO.IO_FixedCapacity"));
// Check to see whether we are now expanding the stream and must
// zero any memory in the middle.
// don't do if created from SafeBuffer
if (_buffer == null) {
if (pos > len) {
unsafe {
Buffer.ZeroMemory(_mem+len, pos-len);
}
}
// set length after zeroing memory to avoid race condition of accessing unzeroed memory
Interlocked.Exchange(ref _length, n);
}
}
if (_buffer != null) {
unsafe {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
try {
_buffer.AcquirePointer(ref pointer);
*(pointer + pos + _offset) = value;
}
finally {
if (pointer != null) {
_buffer.ReleasePointer();
}
}
}
}
else {
unsafe {
_mem[pos] = value;
}
}
Interlocked.Exchange(ref _position, n);
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
namespace System
{
//Only contains static methods. Does not require serialization
using System;
using System.Runtime.CompilerServices;
////using System.Runtime.Versioning;
public static class Buffer
{
// Copies from one primitive array to another primitive array without
// respecting types. This calls memmove internally.
//// [ResourceExposure( ResourceScope.None )]
[MethodImpl( MethodImplOptions.InternalCall )]
public static extern void BlockCopy( Array src ,
int srcOffset ,
Array dst ,
int dstOffset ,
int count );
//// // A very simple and efficient array copy that assumes all of the
//// // parameter validation has already been done. All counts here are
//// // in bytes.
//// [ResourceExposure( ResourceScope.None )]
[MethodImpl( MethodImplOptions.InternalCall )]
internal static extern void InternalBlockCopy( Array src ,
int srcOffset ,
Array dst ,
int dstOffset ,
int count );
//// // This is ported from the optimized CRT assembly in memchr.asm. The JIT generates
//// // pretty good code here and this ends up being within a couple % of the CRT asm.
//// // It is however cross platform as the CRT hasn't ported their fast version to 64-bit
//// // platforms.
//// //
//// internal unsafe static int IndexOfByte( byte* src, byte value, int index, int count )
//// {
//// BCLDebug.Assert( src != null, "src should not be null" );
////
//// byte* pByte = src + index;
////
//// // Align up the pointer to sizeof(int).
//// while(((int)pByte & 3) != 0)
//// {
//// if(count == 0)
//// {
//// return -1;
//// }
//// else if(*pByte == value)
//// {
//// return (int)(pByte - src);
//// }
////
//// count--;
//// pByte++;
//// }
////
//// // Fill comparer with value byte for comparisons
//// //
//// // comparer = 0/0/value/value
//// uint comparer = (((uint)value << 8) + (uint)value);
//// // comparer = value/value/value/value
//// comparer = (comparer << 16) + comparer;
////
//// // Run through buffer until we hit a 4-byte section which contains
//// // the byte we're looking for or until we exhaust the buffer.
//// while(count > 3)
//// {
//// // Test the buffer for presence of value. comparer contains the byte
//// // replicated 4 times.
//// uint t1 = *(uint*)pByte;
//// t1 = t1 ^ comparer;
//// uint t2 = 0x7efefeff + t1;
//// t1 = t1 ^ 0xffffffff;
//// t1 = t1 ^ t2;
//// t1 = t1 & 0x81010100;
////
//// // if t1 is zero then these 4-bytes don't contain a match
//// if(t1 != 0)
//// {
//// // We've found a match for value, figure out which position it's in.
//// int foundIndex = (int)(pByte - src);
//// if(pByte[0] == value)
//// {
//// return foundIndex;
//// }
//// else if(pByte[1] == value)
//// {
//// return foundIndex + 1;
//// }
//// else if(pByte[2] == value)
//// {
//// return foundIndex + 2;
//// }
//// else if(pByte[3] == value)
//// {
//// return foundIndex + 3;
//// }
//// }
////
//// count -= 4;
//// pByte += 4;
////
//// }
////
//// // Catch any bytes that might be left at the tail of the buffer
//// while(count > 0)
//// {
//// if(*pByte == value)
//// {
//// return (int)(pByte - src);
//// }
////
//// count--;
//// pByte++;
//// }
////
//// // If we don't have a match return -1;
//// return -1;
//// }
////
//// // Gets a particular byte out of the array. The array must be an
//// // array of primitives.
//// //
//// // This essentially does the following:
//// // return ((byte*)array) + index.
//// //
//// [ResourceExposure( ResourceScope.None )]
//// [MethodImpl( MethodImplOptions.InternalCall )]
//// public static extern byte GetByte( Array array, int index );
////
//// // Sets a particular byte in an the array. The array must be an
//// // array of primitives.
//// //
//// // This essentially does the following:
//// // *(((byte*)array) + index) = value.
//// //
//// [ResourceExposure( ResourceScope.None )]
//// [MethodImpl( MethodImplOptions.InternalCall )]
//// public static extern void SetByte( Array array, int index, byte value );
////
//// // Gets a particular byte out of the array. The array must be an
//// // array of primitives.
//// //
//// // This essentially does the following:
//// // return array.length * sizeof(array.UnderlyingElementType).
//// //
//// [ResourceExposure( ResourceScope.None )]
//// [MethodImpl( MethodImplOptions.InternalCall )]
//// public static extern int ByteLength( Array array );
////
//// internal unsafe static void ZeroMemory( byte* src, long len )
//// {
//// while(len-- > 0)
//// {
//// *(src + len) = 0;
//// }
//// }
////
//// internal unsafe static void memcpy( byte* src, int srcIndex, byte[] dest, int destIndex, int len )
//// {
//// BCLDebug.Assert( (srcIndex >= 0) && (destIndex >= 0) && (len >= 0), "Index and length must be non-negative!" );
//// BCLDebug.Assert( dest.Length - destIndex >= len, "not enough bytes in dest" );
////
//// // If dest has 0 elements, the fixed statement will throw an
//// // IndexOutOfRangeException. Special-case 0-byte copies.
//// if(len == 0)
//// {
//// return;
//// }
////
//// fixed(byte* pDest = dest)
//// {
//// memcpyimpl( src + srcIndex, pDest + destIndex, len );
//// }
//// }
////
//// internal unsafe static void memcpy( byte[] src, int srcIndex, byte* pDest, int destIndex, int len )
//// {
//// BCLDebug.Assert( (srcIndex >= 0) && (destIndex >= 0) && (len >= 0), "Index and length must be non-negative!" );
//// BCLDebug.Assert( src.Length - srcIndex >= len, "not enough bytes in src" );
////
//// // If dest has 0 elements, the fixed statement will throw an
//// // IndexOutOfRangeException. Special-case 0-byte copies.
//// if(len == 0)
//// {
//// return;
//// }
////
//// fixed(byte* pSrc = src)
//// {
//// memcpyimpl( pSrc + srcIndex, pDest + destIndex, len );
//// }
//// }
////
//// internal unsafe static void memcpy( char* pSrc, int srcIndex, char* pDest, int destIndex, int len )
//// {
//// BCLDebug.Assert( (srcIndex >= 0) && (destIndex >= 0) && (len >= 0), "Index and length must be non-negative!" );
////
//// // No boundary check for buffer overruns - dangerous
//// if(len == 0)
//// {
//// return;
//// }
////
//// memcpyimpl( (byte*)(char*)(pSrc + srcIndex), (byte*)(char*)(pDest + destIndex), len * 2 );
//// }
//--//
[MethodImpl( MethodImplOptions.InternalCall )]
internal unsafe extern static void InternalMemoryCopy( byte* src ,
byte* dst ,
int count );
[MethodImpl( MethodImplOptions.InternalCall )]
internal unsafe extern static void InternalMemoryCopy( sbyte* src ,
sbyte* dst ,
int count );
[MethodImpl( MethodImplOptions.InternalCall )]
internal unsafe extern static void InternalMemoryCopy( ushort* src ,
ushort* dst ,
int count );
[MethodImpl( MethodImplOptions.InternalCall )]
internal unsafe extern static void InternalMemoryCopy( short* src ,
short* dst ,
int count );
[MethodImpl( MethodImplOptions.InternalCall )]
internal unsafe extern static void InternalMemoryCopy( char* src ,
char* dst ,
int count );
[MethodImpl( MethodImplOptions.InternalCall )]
internal unsafe extern static void InternalMemoryCopy( uint* src ,
uint* dst ,
int count );
[MethodImpl( MethodImplOptions.InternalCall )]
internal unsafe extern static void InternalMemoryCopy( int* src ,
int* dst ,
int count );
//--//
[MethodImpl( MethodImplOptions.InternalCall )]
internal unsafe extern static void InternalBackwardMemoryCopy( byte* src ,
byte* dst ,
int count );
[MethodImpl( MethodImplOptions.InternalCall )]
internal unsafe extern static void InternalBackwardMemoryCopy( sbyte* src ,
sbyte* dst ,
int count );
[MethodImpl( MethodImplOptions.InternalCall )]
internal unsafe extern static void InternalBackwardMemoryCopy( ushort* src ,
ushort* dst ,
int count );
[MethodImpl( MethodImplOptions.InternalCall )]
internal unsafe extern static void InternalBackwardMemoryCopy( short* src ,
short* dst ,
int count );
[MethodImpl( MethodImplOptions.InternalCall )]
internal unsafe extern static void InternalBackwardMemoryCopy( char* src ,
char* dst ,
int count );
[MethodImpl( MethodImplOptions.InternalCall )]
internal unsafe extern static void InternalBackwardMemoryCopy( uint* src ,
uint* dst ,
int count );
[MethodImpl( MethodImplOptions.InternalCall )]
internal unsafe extern static void InternalBackwardMemoryCopy( int* src ,
int* dst ,
int count );
//--//
[MethodImpl( MethodImplOptions.InternalCall )]
internal unsafe extern static void InternalMemoryMove( byte* src ,
byte* dst ,
int count );
[MethodImpl( MethodImplOptions.InternalCall )]
internal unsafe extern static void InternalMemoryMove( sbyte* src ,
sbyte* dst ,
int count );
[MethodImpl( MethodImplOptions.InternalCall )]
internal unsafe extern static void InternalMemoryMove( ushort* src ,
ushort* dst ,
int count );
[MethodImpl( MethodImplOptions.InternalCall )]
internal unsafe extern static void InternalMemoryMove( short* src ,
short* dst ,
int count );
[MethodImpl( MethodImplOptions.InternalCall )]
internal unsafe extern static void InternalMemoryMove( char* src ,
char* dst ,
int count );
[MethodImpl( MethodImplOptions.InternalCall )]
internal unsafe extern static void InternalMemoryMove( uint* src ,
uint* dst ,
int count );
[MethodImpl( MethodImplOptions.InternalCall )]
internal unsafe extern static void InternalMemoryMove( int* src ,
int* dst ,
int count );
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
namespace WorkItemTime
{
public static class DataTableUtilities
{
public static void ForEachRow(this DataTable table, Action<DataRow> rowAction)
{
foreach (var row in table.AsEnumerable())
{
rowAction(row);
}
}
public static void ForEach<TItem>(this IEnumerable<TItem> enumerable, Action<TItem> action)
{
foreach (var item in enumerable)
action(item);
}
}
public class Data
{
public DataSet UberSet { get; private set; }
public const string SettingsTableName = "settings";
public const string SettingsTableKey = "key";
public const string SettingsTableValue = "value";
public const string SettingsTableComment = "comment";
public const string SettingsTfptPathAndFileName = "TFPT Path and File Name";
public const string SettingsTfsCollectionName = "TFS Collection Name";
public const string SettingsTfsWorkHoursFieldName = "TFS Work Hours Field Name";
public const string ActivityTableName = "activity";
public const string ActivityDateTime = "datetime";
public const string ActivityDescription = "description";
public const string ActivityComment = "comment";
public const string ActivityStatus = "status";
public const string ActivityStatusDateTime = "statusDateTime";
public const string ActivityKind = "kind";
public const string ActivityWorkItem = "workitem";
public const string ActivityStatusNotSentToTfs = "Not Set To TFS";
public const string ActivityStatusSendingToTfs = "Sending to TFS";
public const string ActivityStatusSentToTfs = "Sent To TFS";
public const string ActivityKindStart = "Start";
public const string ActivityKindStop = "Stop";
public const string LogTableName = "log";
public const string LogMessage = "message";
public const string TfsEditsTableName = "tfsEdits";
public const string TfsEditsWorkItem = ActivityWorkItem;
public const string TfsEditsDurationMinutes = "duration";
public const string TfsEditsComment = ActivityComment;
public const string TfsEditsApiOutput = "apiOutput";
public const string TfsEditsApiError = "apiError";
public const string TfsEditsStatus = "status";
public const string TfsEditsStatusNone = "none";
public const string TfsEditsStatusPending = "pending";
public const string TfsEditsStatusReading = "reading";
public const string TfsEditsStatusWriting = "writing";
public const string TfsEditsStatusSuccess = "success";
public const string TfsEditsStatusError = "error";
public void Load()
{
this.UberSet = new DataSet();
try
{
this.UberSet.ReadXml("data.xml");
}
catch(Exception ex)
{
this.UberSet = this.CreateDataSet();
}
}
public void Save()
{
this.UberSet.WriteXml("data.xml", XmlWriteMode.WriteSchema);
}
public DataSet CreateDataSet()
{
var dataSet = new DataSet();
var activityTable = dataSet.Tables.Add(ActivityTableName);
activityTable.Columns.Add(ActivityDateTime, typeof(DateTime));
activityTable.Columns.Add(ActivityDescription, typeof(string));
activityTable.Columns.Add(ActivityKind, typeof(string));
activityTable.Columns.Add(ActivityComment, typeof(string));
activityTable.Columns.Add(ActivityStatus, typeof(string));//approved, posting, posted
activityTable.Columns.Add(ActivityStatusDateTime, typeof(DateTime));
var wi = activityTable.Columns.Add(ActivityWorkItem, typeof(Int32));
wi.AllowDBNull = true;
var settingsTable = dataSet.Tables.Add(SettingsTableName);
var keyColumn = settingsTable.Columns.Add(SettingsTableKey, typeof(string));
settingsTable.Columns.Add(SettingsTableValue, typeof(string));
settingsTable.Columns.Add(SettingsTableComment, typeof(string));
settingsTable.PrimaryKey = new[] {keyColumn};
settingsTable.Rows.Add(SettingsTfptPathAndFileName, @"C:\Program Files (x86)\Microsoft Team Foundation Server 2013 Power Tools\tfpt.exe", "the exe");
settingsTable.Rows.Add(SettingsTfsCollectionName, "http://tfstta.int.thomson.com:8080/tfs/DefaultCollection", "the collection");
settingsTable.Rows.Add(SettingsTfsWorkHoursFieldName, "Actual Work", "TFS WI field name to increment");
var tfsEditsTable = dataSet.Tables.Add(TfsEditsTableName);
wi = tfsEditsTable.Columns.Add(TfsEditsWorkItem, typeof(Int32));
wi.AllowDBNull = true;
//tfsEditsTable.PrimaryKey = new[] { tfsEditsTable.Columns.Add(TfsEditsWorkItem)};
tfsEditsTable.Columns.Add(TfsEditsDurationMinutes, typeof(Int32));
tfsEditsTable.Columns.Add(TfsEditsComment);
tfsEditsTable.Columns.Add(TfsEditsStatus);
tfsEditsTable.Columns.Add(TfsEditsApiOutput);
tfsEditsTable.Columns.Add(TfsEditsApiError);
return dataSet;
}
public static void SetActivityStatus(DataRow activityRow, string status)
{
activityRow.SetField(Data.ActivityStatus, status);
activityRow.SetField(Data.ActivityStatusDateTime, DateTime.Now);
}
public void CalculateDurations(DataSet uberSet)
{
var activityTable = uberSet.Tables[Data.ActivityTableName];
var tfsEditsTable = uberSet.Tables[Data.TfsEditsTableName];
tfsEditsTable.Rows.Clear();
DataRow previousActivity = null;
DateTime? currentDateTimeStart = null;
DataRow tfsEdit = null;
foreach (DataRow currentActivity in activityTable.Rows.OfType<DataRow>().OrderBy(row=>row.Field<DateTime>(Data.ActivityDateTime)))
{
if (currentActivity.Field<string>(Data.ActivityKind) == ActivityKindStart && previousActivity == null)
{
//make the tfs row
tfsEdit = tfsEditsTable.NewRow();
tfsEdit.SetField(Data.TfsEditsDurationMinutes, 0);
//iterate to second row
previousActivity = currentActivity;
continue;
}
if (currentActivity.Field<string>(Data.ActivityKind) == ActivityKindStart
&& previousActivity.Field<string>(Data.ActivityKind) == ActivityKindStop)
{
if (currentActivity.Field<Int32?>(Data.ActivityWorkItem).HasValue)
{
//see if we have already encountered this WI
tfsEdit = tfsEditsTable.AsEnumerable()
.FirstOrDefault(
row =>
{
return
row.Field<Int32?>(Data.ActivityWorkItem).HasValue
&& row.Field<Int32?>(Data.ActivityWorkItem).Value ==
currentActivity.Field<Int32?>(Data.ActivityWorkItem).Value;
});
if (tfsEdit == null)
{
//make the tfs row
tfsEdit = tfsEditsTable.NewRow();
tfsEdit.SetField(Data.TfsEditsDurationMinutes, 0);
}
}
}
else if (currentActivity.Field<string>(Data.ActivityKind) == ActivityKindStop
&& previousActivity.Field<string>(Data.ActivityKind) == ActivityKindStart)
{
//accumulate the time
var duration = currentActivity.Field<DateTime>(Data.ActivityDateTime)
- previousActivity.Field<DateTime>(Data.ActivityDateTime);
tfsEdit.SetField(Data.TfsEditsDurationMinutes, duration.Minutes);
tfsEdit.SetField(Data.TfsEditsWorkItem, previousActivity.Field<Int32?>(Data.ActivityWorkItem));
//append comment
var activityComment = currentActivity.Field<string>(Data.ActivityComment);
if (!string.IsNullOrWhiteSpace(activityComment))
{
var tfsEditComment = tfsEdit.Field<string>(Data.TfsEditsComment) ?? "";
tfsEditComment += Environment.NewLine + activityComment;
tfsEdit.SetField(Data.TfsEditsComment, tfsEditComment);
}
if (tfsEditsTable.Rows.IndexOf(tfsEdit) == -1)
{
tfsEditsTable.Rows.Add(tfsEdit);
}
}
previousActivity = currentActivity;
}
}
}
}
| |
#region Changes
/*
Changed by Miha Strehar in 2016:
CultureInfo.CurrentCulture.TextInfo.ToTitleCase(input) to CultureInfo.CurrentCulture.TextInfo.ToLower(input)
*/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
#if !NET35
using System.Net;
#endif
using System.Linq;
using System.Linq.Expressions;
using System.Text.RegularExpressions;
#if NET35
using System.Web;
#endif
using DotLiquidCore.Util;
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
namespace DotLiquidCore
{
public static class StandardFilters
{
/// <summary>
/// Return the size of an array or of an string
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static int Size(object input)
{
if (input is string)
return ((string) input).Length;
if (input is IEnumerable)
return ((IEnumerable) input).Cast<object>().Count();
return 0;
}
/// <summary>
/// Return a Part of a String
/// </summary>
/// <param name="input"></param>
/// <param name="start"></param>
/// <param name="len"></param>
/// <returns></returns>
public static string Slice(string input, int start, int len = 1)
{
if (input == null || start > input.Length)
return null;
if (start < 0)
start += input.Length;
if (start + len > input.Length)
len = input.Length - start;
return input.Substring(start, len);
}
/// <summary>
/// convert a input string to DOWNCASE
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static string Downcase(string input)
{
return input == null ? input : input.ToLower();
}
/// <summary>
/// convert a input string to UPCASE
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static string Upcase(string input)
{
return input == null
? input
: input.ToUpper();
}
/// <summary>
/// capitalize words in the input sentence
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static string Capitalize(string input)
{
if (input.IsNullOrWhiteSpace())
return input;
return string.IsNullOrEmpty(input)
? input
: CultureInfo.CurrentCulture.TextInfo.ToLower(input);
}
public static string Escape(string input)
{
if (string.IsNullOrEmpty(input))
return input;
try
{
#if NET35
return HttpUtility.HtmlEncode(input);
#else
return WebUtility.HtmlEncode(input);
#endif
}
catch
{
return input;
}
}
public static string H(string input)
{
return Escape(input);
}
#if NET35
/// <summary>
/// Truncates a string down to 15 characters
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static string Truncate(string input)
{
return Truncate(input, 15, "...");
}
/// <summary>
/// Truncates a string down to <paramref name="length"/> characters
/// </summary>
/// <param name="input"></param>
/// <param name="length"></param>
/// <returns></returns>
public static string Truncate(string input, int length)
{
return Truncate(input, length, "...");
}
/// <summary>
/// Truncates a string down to x characters
/// </summary>
/// <param name="input"></param>
/// <param name="length"></param>
/// <param name="truncateString"></param>
/// <returns></returns>
public static string Truncate(string input, int length, string truncateString)
#else
/// <summary>
/// Truncates a string down to x characters
/// </summary>
/// <param name="input"></param>
/// <param name="length"></param>
/// <param name="truncateString"></param>
/// <returns></returns>
public static string Truncate(string input, int length = 50, string truncateString = "...")
#endif
{
if (string.IsNullOrEmpty(input))
return input;
int l = length - truncateString.Length;
return input.Length > length
? input.Substring(0, l < 0 ? 0 : l) + truncateString
: input;
}
#if NET35
public static string TruncateWords(string input)
{
return TruncateWords(input, 15);
}
public static string TruncateWords(string input, int words)
{
return TruncateWords(input, words, "...");
}
public static string TruncateWords(string input, int words, string truncateString)
#else
public static string TruncateWords(string input, int words = 15, string truncateString = "...")
#endif
{
if (string.IsNullOrEmpty(input))
return input;
var wordList = input.Split(' ').ToList();
int l = words < 0 ? 0 : words;
return wordList.Count > l
? string.Join(" ", wordList.Take(l).ToArray()) + truncateString
: input;
}
/// <summary>
/// Split input string into an array of substrings separated by given pattern.
/// </summary>
/// <param name="input"></param>
/// <param name="pattern"></param>
/// <returns></returns>
public static string[] Split(string input, string pattern)
{
return input.IsNullOrWhiteSpace()
? new[] { input }
: input.Split(new[] { pattern }, StringSplitOptions.RemoveEmptyEntries);
}
public static string StripHtml(string input)
{
return input.IsNullOrWhiteSpace()
? input
: Regex.Replace(input, @"<.*?>", string.Empty);
}
/// <summary>
/// Remove all newlines from the string
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static string StripNewlines(string input)
{
return input.IsNullOrWhiteSpace()
? input
: Regex.Replace(input, @"(\r?\n)", String.Empty);
//: Regex.Replace(input, Environment.NewLine, string.Empty);
}
#if NET35
/// <summary>
/// Join elements of the array with a certain character between them
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static string Join(IEnumerable input)
{
return Join(input, " ");
}
/// <summary>
/// Join elements of the array with a certain character between them
/// </summary>
/// <param name="input"></param>
/// <param name="glue"></param>
/// <returns></returns>
public static string Join(IEnumerable input, string glue)
#else
/// <summary>
/// Join elements of the array with a certain character between them
/// </summary>
/// <param name="input"></param>
/// <param name="glue"></param>
/// <returns></returns>
public static string Join(IEnumerable input, string glue = " ")
#endif
{
if (input == null)
return null;
IEnumerable<object> castInput = input.Cast<object>();
#if NET35
return string.Join(glue, castInput.Select(o => o.ToString()).ToArray());
#else
return string.Join(glue, castInput);
#endif
}
#if NET35
/// <summary>
/// Sort elements of the array
/// provide optional property with which to sort an array of hashes or drops
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static IEnumerable Sort(object input)
{
return Sort(input, null);
}
/// <summary>
/// Sort elements of the array
/// provide optional property with which to sort an array of hashes or drops
/// </summary>
/// <param name="input"></param>
/// <param name="property"></param>
/// <returns></returns>
public static IEnumerable Sort(object input, string property)
#else
/// <summary>
/// Sort elements of the array
/// provide optional property with which to sort an array of hashes or drops
/// </summary>
/// <param name="input"></param>
/// <param name="property"></param>
/// <returns></returns>
public static IEnumerable Sort(object input, string property = null)
#endif
{
List<object> ary;
if (input is IEnumerable)
ary = ((IEnumerable) input).Flatten().Cast<object>().ToList();
else
ary = new List<object>(new[] { input });
if (!ary.Any())
return ary;
if (string.IsNullOrEmpty(property))
ary.Sort();
else if ((ary.All(o => o is IDictionary)) && ((IDictionary) ary.First()).Contains(property))
ary.Sort((a, b) => Comparer.Default.Compare(((IDictionary) a)[property], ((IDictionary) b)[property]));
else if (ary.All(o => o.RespondTo(property)))
ary.Sort((a, b) => Comparer.Default.Compare(a.Send(property), b.Send(property)));
return ary;
}
/// <summary>
/// Map/collect on a given property
/// </summary>
/// <param name="input"></param>
/// <param name="property"></param>
/// <returns></returns>
public static IEnumerable Map(IEnumerable input, string property)
{
List<object> ary = input.Cast<object>().ToList();
if (!ary.Any())
return ary;
if ((ary.All(o => o is IDictionary)) && ((IDictionary) ary.First()).Contains(property))
return ary.Select(e => ((IDictionary) e)[property]);
if (ary.All(o => o.RespondTo(property)))
return ary.Select(e => e.Send(property));
return ary;
}
#if NET35
/// <summary>
/// Replace occurrences of a string with another
/// </summary>
/// <param name="input"></param>
/// <param name="string"></param>
/// <returns></returns>
public static string Replace(string input, string @string)
{
return Replace(input, @string, " ");
}
/// <summary>
/// Replace occurrences of a string with another
/// </summary>
/// <param name="input"></param>
/// <param name="string"></param>
/// <param name="replacement"></param>
/// <returns></returns>
public static string Replace(string input, string @string, string replacement)
#else
/// <summary>
/// Replace occurrences of a string with another
/// </summary>
/// <param name="input"></param>
/// <param name="string"></param>
/// <param name="replacement"></param>
/// <returns></returns>
public static string Replace(string input, string @string, string replacement = "")
#endif
{
if (string.IsNullOrEmpty(input) || string.IsNullOrEmpty(@string))
return input;
return string.IsNullOrEmpty(input)
? input
: Regex.Replace(input, @string, replacement);
}
#if NET35
/// <summary>
/// Replace the first occurence of a string with another
/// </summary>
/// <param name="input"></param>
/// <param name="string"></param>
/// <param name="replacement"></param>
/// <returns></returns>
public static string ReplaceFirst(string input, string @string)
{
return ReplaceFirst(input, @string, "");
}
/// <summary>
/// Replace the first occurence of a string with another
/// </summary>
/// <param name="input"></param>
/// <param name="string"></param>
/// <param name="replacement"></param>
/// <returns></returns>
public static string ReplaceFirst(string input, string @string, string replacement)
#else
/// <summary>
/// Replace the first occurence of a string with another
/// </summary>
/// <param name="input"></param>
/// <param name="string"></param>
/// <param name="replacement"></param>
/// <returns></returns>
public static string ReplaceFirst(string input, string @string, string replacement = "")
#endif
{
if (string.IsNullOrEmpty(input) || string.IsNullOrEmpty(@string))
return input;
bool doneReplacement = false;
return Regex.Replace(input, @string, m =>
{
if (doneReplacement)
return m.Value;
doneReplacement = true;
return replacement;
});
}
/// <summary>
/// Remove a substring
/// </summary>
/// <param name="input"></param>
/// <param name="string"></param>
/// <returns></returns>
public static string Remove(string input, string @string)
{
return input.IsNullOrWhiteSpace()
? input
: input.Replace(@string, string.Empty);
}
/// <summary>
/// Remove the first occurrence of a substring
/// </summary>
/// <param name="input"></param>
/// <param name="string"></param>
/// <returns></returns>
public static string RemoveFirst(string input, string @string)
{
return input.IsNullOrWhiteSpace()
? input
: ReplaceFirst(input, @string, string.Empty);
}
/// <summary>
/// Add one string to another
/// </summary>
/// <param name="input"></param>
/// <param name="string"></param>
/// <returns></returns>
public static string Append(string input, string @string)
{
return input == null
? input
: input + @string;
}
/// <summary>
/// Prepend a string to another
/// </summary>
/// <param name="input"></param>
/// <param name="string"></param>
/// <returns></returns>
public static string Prepend(string input, string @string)
{
return input == null
? input
: @string + input;
}
/// <summary>
/// Add <br /> tags in front of all newlines in input string
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static string NewlineToBr(string input)
{
return input.IsNullOrWhiteSpace()
? input
: Regex.Replace(input, @"(\r?\n)", "<br />$1");
}
/// <summary>
/// Formats a date using a .NET date format string
/// </summary>
/// <param name="input"></param>
/// <param name="format"></param>
/// <returns></returns>
public static string Date(object input, string format)
{
if (input == null)
return null;
if (format.IsNullOrWhiteSpace())
return input.ToString();
DateTime date;
return DateTime.TryParse(input.ToString(), out date)
? Liquid.UseRubyDateFormat ? date.ToStrFTime(format) : date.ToString(format)
: input.ToString();
}
/// <summary>
/// Get the first element of the passed in array
///
/// Example:
/// {{ product.images | first | to_img }}
/// </summary>
/// <param name="array"></param>
/// <returns></returns>
public static object First(IEnumerable array)
{
if (array == null)
return null;
return array.Cast<object>().FirstOrDefault();
}
/// <summary>
/// Get the last element of the passed in array
///
/// Example:
/// {{ product.images | last | to_img }}
/// </summary>
/// <param name="array"></param>
/// <returns></returns>
public static object Last(IEnumerable array)
{
if (array == null)
return null;
return array.Cast<object>().LastOrDefault();
}
/// <summary>
/// Addition
/// </summary>
/// <param name="input"></param>
/// <param name="operand"></param>
/// <returns></returns>
public static object Plus(object input, object operand)
{
return input is string
? string.Concat(input, operand)
: DoMathsOperation(input, operand, Expression.Add);
}
/// <summary>
/// Subtraction
/// </summary>
/// <param name="input"></param>
/// <param name="operand"></param>
/// <returns></returns>
public static object Minus(object input, object operand)
{
return DoMathsOperation(input, operand, Expression.Subtract);
}
/// <summary>
/// Multiplication
/// </summary>
/// <param name="input"></param>
/// <param name="operand"></param>
/// <returns></returns>
public static object Times(object input, object operand)
{
return input is string && operand is int
? Enumerable.Repeat((string) input, (int) operand)
: DoMathsOperation(input, operand, Expression.Multiply);
}
/// <summary>
/// Division
/// </summary>
/// <param name="input"></param>
/// <param name="operand"></param>
/// <returns></returns>
public static object DividedBy(object input, object operand)
{
return DoMathsOperation(input, operand, Expression.Divide);
}
public static object Modulo(object input, object operand)
{
return DoMathsOperation(input, operand, Expression.Modulo);
}
private static object DoMathsOperation(object input, object operand, Func<Expression, Expression, BinaryExpression> operation)
{
return input == null || operand == null
? null
: ExpressionUtility.CreateExpression(operation, input.GetType(), operand.GetType(), input.GetType(), true)
.DynamicInvoke(input, operand);
}
}
internal static class StringExtensions
{
public static bool IsNullOrWhiteSpace(this string s)
{
return string.IsNullOrEmpty(s) || s.Trim().Length == 0;
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace SelfLoadSoftDelete.Business.ERCLevel
{
/// <summary>
/// H10Level11111 (editable child object).<br/>
/// This is a generated base class of <see cref="H10Level11111"/> business object.
/// </summary>
/// <remarks>
/// This class contains one child collection:<br/>
/// - <see cref="H11Level111111Objects"/> of type <see cref="H11Level111111Coll"/> (1:M relation to <see cref="H12Level111111"/>)<br/>
/// This class is an item of <see cref="H09Level11111Coll"/> collection.
/// </remarks>
[Serializable]
public partial class H10Level11111 : BusinessBase<H10Level11111>
{
#region Static Fields
private static int _lastID;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Level_1_1_1_1_1_ID"/> property.
/// </summary>
public static readonly PropertyInfo<int> Level_1_1_1_1_1_IDProperty = RegisterProperty<int>(p => p.Level_1_1_1_1_1_ID, "Level_1_1_1_1_1 ID");
/// <summary>
/// Gets the Level_1_1_1_1_1 ID.
/// </summary>
/// <value>The Level_1_1_1_1_1 ID.</value>
public int Level_1_1_1_1_1_ID
{
get { return GetProperty(Level_1_1_1_1_1_IDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="Level_1_1_1_1_1_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Level_1_1_1_1_1_NameProperty = RegisterProperty<string>(p => p.Level_1_1_1_1_1_Name, "Level_1_1_1_1_1 Name");
/// <summary>
/// Gets or sets the Level_1_1_1_1_1 Name.
/// </summary>
/// <value>The Level_1_1_1_1_1 Name.</value>
public string Level_1_1_1_1_1_Name
{
get { return GetProperty(Level_1_1_1_1_1_NameProperty); }
set { SetProperty(Level_1_1_1_1_1_NameProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="H11Level111111SingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<H11Level111111Child> H11Level111111SingleObjectProperty = RegisterProperty<H11Level111111Child>(p => p.H11Level111111SingleObject, "H11 Level111111 Single Object", RelationshipTypes.Child);
/// <summary>
/// Gets the H11 Level111111 Single Object ("self load" child property).
/// </summary>
/// <value>The H11 Level111111 Single Object.</value>
public H11Level111111Child H11Level111111SingleObject
{
get { return GetProperty(H11Level111111SingleObjectProperty); }
private set { LoadProperty(H11Level111111SingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="H11Level111111ASingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<H11Level111111ReChild> H11Level111111ASingleObjectProperty = RegisterProperty<H11Level111111ReChild>(p => p.H11Level111111ASingleObject, "H11 Level111111 ASingle Object", RelationshipTypes.Child);
/// <summary>
/// Gets the H11 Level111111 ASingle Object ("self load" child property).
/// </summary>
/// <value>The H11 Level111111 ASingle Object.</value>
public H11Level111111ReChild H11Level111111ASingleObject
{
get { return GetProperty(H11Level111111ASingleObjectProperty); }
private set { LoadProperty(H11Level111111ASingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="H11Level111111Objects"/> property.
/// </summary>
public static readonly PropertyInfo<H11Level111111Coll> H11Level111111ObjectsProperty = RegisterProperty<H11Level111111Coll>(p => p.H11Level111111Objects, "H11 Level111111 Objects", RelationshipTypes.Child);
/// <summary>
/// Gets the H11 Level111111 Objects ("self load" child property).
/// </summary>
/// <value>The H11 Level111111 Objects.</value>
public H11Level111111Coll H11Level111111Objects
{
get { return GetProperty(H11Level111111ObjectsProperty); }
private set { LoadProperty(H11Level111111ObjectsProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="H10Level11111"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="H10Level11111"/> object.</returns>
internal static H10Level11111 NewH10Level11111()
{
return DataPortal.CreateChild<H10Level11111>();
}
/// <summary>
/// Factory method. Loads a <see cref="H10Level11111"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="H10Level11111"/> object.</returns>
internal static H10Level11111 GetH10Level11111(SafeDataReader dr)
{
H10Level11111 obj = new H10Level11111();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(dr);
obj.MarkOld();
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="H10Level11111"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
private H10Level11111()
{
// Prevent direct creation
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="H10Level11111"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
LoadProperty(Level_1_1_1_1_1_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID));
LoadProperty(H11Level111111SingleObjectProperty, DataPortal.CreateChild<H11Level111111Child>());
LoadProperty(H11Level111111ASingleObjectProperty, DataPortal.CreateChild<H11Level111111ReChild>());
LoadProperty(H11Level111111ObjectsProperty, DataPortal.CreateChild<H11Level111111Coll>());
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="H10Level11111"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(Level_1_1_1_1_1_IDProperty, dr.GetInt32("Level_1_1_1_1_1_ID"));
LoadProperty(Level_1_1_1_1_1_NameProperty, dr.GetString("Level_1_1_1_1_1_Name"));
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Loads child objects.
/// </summary>
internal void FetchChildren()
{
LoadProperty(H11Level111111SingleObjectProperty, H11Level111111Child.GetH11Level111111Child(Level_1_1_1_1_1_ID));
LoadProperty(H11Level111111ASingleObjectProperty, H11Level111111ReChild.GetH11Level111111ReChild(Level_1_1_1_1_1_ID));
LoadProperty(H11Level111111ObjectsProperty, H11Level111111Coll.GetH11Level111111Coll(Level_1_1_1_1_1_ID));
}
/// <summary>
/// Inserts a new <see cref="H10Level11111"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(H08Level1111 parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("AddH10Level11111", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_1_1_1_ID", parent.Level_1_1_1_1_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_ID", ReadProperty(Level_1_1_1_1_1_IDProperty)).Direction = ParameterDirection.Output;
cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_Name", ReadProperty(Level_1_1_1_1_1_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
LoadProperty(Level_1_1_1_1_1_IDProperty, (int) cmd.Parameters["@Level_1_1_1_1_1_ID"].Value);
}
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="H10Level11111"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update()
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("UpdateH10Level11111", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_ID", ReadProperty(Level_1_1_1_1_1_IDProperty)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_Name", ReadProperty(Level_1_1_1_1_1_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
}
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Self deletes the <see cref="H10Level11111"/> object from database.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf()
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
// flushes all pending data operations
FieldManager.UpdateChildren(this);
using (var cmd = new SqlCommand("DeleteH10Level11111", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_ID", ReadProperty(Level_1_1_1_1_1_IDProperty)).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd);
OnDeletePre(args);
cmd.ExecuteNonQuery();
OnDeletePost(args);
}
}
// removes all previous references to children
LoadProperty(H11Level111111SingleObjectProperty, DataPortal.CreateChild<H11Level111111Child>());
LoadProperty(H11Level111111ASingleObjectProperty, DataPortal.CreateChild<H11Level111111ReChild>());
LoadProperty(H11Level111111ObjectsProperty, DataPortal.CreateChild<H11Level111111Coll>());
}
#endregion
#region Pseudo Events
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
/* ====================================================================
*/
using System;
using System.Xml;
using System.Collections;
using System.Collections.Specialized;
using System.Threading;
using Oranikle.Report.Engine;
namespace Oranikle.Report.Engine
{
///<summary>
/// A report expression: includes original source, parsed expression and type information.
///</summary>
[Serializable]
public class Expression : ReportLink, IExpr
{
string _Source; // source of expression
IExpr _Expr; // expression after parse
TypeCode _Type; // type of expression; only available after parsed
ExpressionType _ExpectedType; // expected type of expression
string _UniqueName; // unique name of expression; not always created
public Expression(ReportDefn r, ReportLink p, XmlNode xNode, ExpressionType et) : this(r, p, xNode.InnerText, et){}
public Expression(ReportDefn r, ReportLink p, String xNode, ExpressionType et) : base(r, p)
{
_Source = xNode;
_Type = TypeCode.Empty;
_ExpectedType = et;
_Expr = null;
}
// UniqueName of expression
public string UniqueName
{
get {return _UniqueName;}
}
override public void FinalPass()
{
// optimization: avoid expression overhead if this isn't really an expression
if (_Source == null)
{
_Expr = new Constant("");
return;
}
else if (_Source == "" || // empty expression
_Source[0] != '=') // if 1st char not '='
{
_Expr = new Constant(_Source); // this is a constant value
return;
}
Parser p = new Parser(OwnerReport.DataCache);
// find the fields that are part of the DataRegion (if there is one)
IDictionary fields=null;
ReportLink dr = Parent;
Grouping grp= null; // remember if in a table group or detail group or list group
Matrix m=null;
ReportLink phpf=null;
while (dr != null)
{
if (dr is Grouping)
p.NoAggregateFunctions = true;
else if (dr is TableGroup)
grp = ((TableGroup) dr).Grouping;
else if (dr is Matrix)
{
m = (Matrix) dr; // if matrix we need to pass special
break;
}
else if (dr is Details)
{
grp = ((Details) dr).Grouping;
}
else if (dr is List)
{
grp = ((List) dr).Grouping;
break;
}
else if (dr is PageHeader || dr is PageFooter)
{
phpf = dr;
}
else if (dr is DataRegion || dr is DataSetDefn)
break;
dr = dr.Parent;
}
if (dr != null)
{
if (dr is DataSetDefn)
{
DataSetDefn d = (DataSetDefn) dr;
if (d.Fields != null)
fields = d.Fields.Items;
}
else // must be a DataRegion
{
DataRegion d = (DataRegion) dr;
if (d.DataSetDefn != null &&
d.DataSetDefn.Fields != null)
fields = d.DataSetDefn.Fields.Items;
}
}
NameLookup lu = new NameLookup(fields, OwnerReport.LUReportParameters,
OwnerReport.LUReportItems,OwnerReport.LUGlobals,
OwnerReport.LUUser, OwnerReport.LUAggrScope,
grp, m, OwnerReport.CodeModules, OwnerReport.Classes, OwnerReport.DataSetsDefn,
OwnerReport.CodeType);
if (phpf != null)
{
// Non-null when expression is in PageHeader or PageFooter;
// Expression name needed for dynamic lookup of ReportItems on a page.
lu.PageFooterHeader = phpf;
lu.ExpressionName = _UniqueName = "xn_" + Interlocked.Increment(ref Parser.Counter).ToString();
}
try
{
_Expr = p.Parse(lu, _Source);
}
catch (Exception e)
{
_Expr = new ConstantError(e.Message);
// Invalid expression
OwnerReport.rl.LogError(8, ErrorText(e.Message));
}
// Optimize removing any expression that always result in a constant
try
{
_Expr = _Expr.ConstantOptimization();
}
catch(Exception ex)
{
OwnerReport.rl.LogError(4, "Expression:" + _Source + "\r\nConstant Optimization exception:\r\n" + ex.Message + "\r\nStack trace:\r\n" + ex.StackTrace );
}
_Type = _Expr.GetTypeCode();
return;
}
private string ErrorText(string msg)
{
ReportLink rl = this.Parent;
while (rl != null)
{
if (rl is ReportItem)
break;
rl = rl.Parent;
}
string prefix="Expression";
if (rl != null)
{
ReportItem ri = rl as ReportItem;
if (ri.Name != null)
prefix = ri.Name.Nm + " expression";
}
return prefix + " '" + _Source + "' failed to parse: " + msg;
}
private void ReportError(Report rpt, int severity, string err)
{
if (rpt == null)
OwnerReport.rl.LogError(severity, err);
else
rpt.rl.LogError(severity, err);
}
public string Source
{
get { return _Source; }
}
public IExpr Expr
{
get { return _Expr; }
}
public TypeCode Type
{
get { return _Type; }
}
public ExpressionType ExpectedType
{
get { return _ExpectedType; }
}
#region IExpr Members
public System.TypeCode GetTypeCode()
{
if (_Expr == null)
return System.TypeCode.Object; // we really don't know the type
return _Expr.GetTypeCode();
}
public bool IsConstant()
{
if (_Expr == null)
{
this.FinalPass(); // expression hasn't been parsed yet -- let try to parse it.
if (_Expr == null)
return false; // no luck; then don't treat as constant
}
return _Expr.IsConstant();
}
public IExpr ConstantOptimization()
{
return this;
}
public object Evaluate(Report rpt, Row row)
{
try
{
// Check to see if we're evaluating an expression in a page header or footer;
// If that is the case the rows are cached by page.
if (row == null && this.UniqueName != null)
{
Rows rows = rpt.GetPageExpressionRows(UniqueName);
if (rows != null && rows.Data != null && rows.Data.Count > 0)
row = rows.Data[0];
}
return _Expr.Evaluate(rpt, row);
}
catch (Exception e)
{
string err;
if (e.InnerException != null)
err = String.Format("Exception evaluating {0}. {1}. {2}", _Source, e.Message, e.InnerException.Message);
else
err = String.Format("Exception evaluating {0}. {1}", _Source, e.Message);
ReportError(rpt, 4, err);
return null;
}
}
public string EvaluateString(Report rpt, Row row)
{
try
{
return _Expr.EvaluateString(rpt, row);
}
catch (Exception e)
{
string err = String.Format("Exception evaluating {0}. {1}", _Source, e.Message);
ReportError(rpt, 4, err);
return null;
}
}
public double EvaluateDouble(Report rpt, Row row)
{
try
{
return _Expr.EvaluateDouble(rpt, row);
}
catch (Exception e)
{
string err = String.Format("Exception evaluating {0}. {1}", _Source, e.Message);
ReportError(rpt, 4, err);
return double.NaN;
}
}
public decimal EvaluateDecimal(Report rpt, Row row)
{
try
{
return _Expr.EvaluateDecimal(rpt, row);
}
catch (Exception e)
{
string err = String.Format("Exception evaluating {0}. {1}", _Source, e.Message);
ReportError(rpt, 4, err);
return decimal.MinValue;
}
}
public int EvaluateInt32(Report rpt, Row row)
{
try
{
return _Expr.EvaluateInt32(rpt, row);
}
catch (Exception e)
{
string err = String.Format("Exception evaluating {0}. {1}", _Source, e.Message);
ReportError(rpt, 4, err);
return int.MinValue;
}
}
public DateTime EvaluateDateTime(Report rpt, Row row)
{
try
{
return _Expr.EvaluateDateTime(rpt, row);
}
catch (Exception e)
{
string err = String.Format("Exception evaluating {0}. {1}", _Source, e.Message);
ReportError(rpt, 4, err);
return DateTime.MinValue;
}
}
public bool EvaluateBoolean(Report rpt, Row row)
{
try
{
return _Expr.EvaluateBoolean(rpt, row);
}
catch (Exception e)
{
string err = String.Format("Exception evaluating {0}. {1}", _Source, e.Message);
ReportError(rpt, 4, err);
return false;
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace System.ComponentModel
{
public class BackgroundWorker : IDisposable
{
// Private instance members
private bool _canCancelWorker = false;
private bool _workerReportsProgress = false;
private bool _cancellationPending = false;
private bool _isRunning = false;
private AsyncOperation _asyncOperation = null;
private readonly SendOrPostCallback _operationCompleted;
private readonly SendOrPostCallback _progressReporter;
public BackgroundWorker()
{
_operationCompleted = new SendOrPostCallback(AsyncOperationCompleted);
_progressReporter = new SendOrPostCallback(ProgressReporter);
}
~BackgroundWorker() // exists for backwards compatibility
{
Dispose(false);
}
private void AsyncOperationCompleted(object arg)
{
_isRunning = false;
_cancellationPending = false;
OnRunWorkerCompleted((RunWorkerCompletedEventArgs)arg);
}
public bool CancellationPending
{
get
{
return _cancellationPending;
}
}
public void CancelAsync()
{
if (!WorkerSupportsCancellation)
{
throw new InvalidOperationException(SR.BackgroundWorker_WorkerDoesntSupportCancellation);
}
_cancellationPending = true;
}
public event DoWorkEventHandler DoWork;
public bool IsBusy
{
get
{
return _isRunning;
}
}
protected virtual void OnDoWork(DoWorkEventArgs e)
{
DoWorkEventHandler handler = DoWork;
if (handler != null)
{
handler(this, e);
}
}
protected virtual void OnRunWorkerCompleted(RunWorkerCompletedEventArgs e)
{
RunWorkerCompletedEventHandler handler = RunWorkerCompleted;
if (handler != null)
{
handler(this, e);
}
}
protected virtual void OnProgressChanged(ProgressChangedEventArgs e)
{
ProgressChangedEventHandler handler = ProgressChanged;
if (handler != null)
{
handler(this, e);
}
}
public event ProgressChangedEventHandler ProgressChanged;
// Gets invoked through the AsyncOperation on the proper thread.
private void ProgressReporter(object arg)
{
OnProgressChanged((ProgressChangedEventArgs)arg);
}
// Cause progress update to be posted through current AsyncOperation.
public void ReportProgress(int percentProgress)
{
ReportProgress(percentProgress, null);
}
// Cause progress update to be posted through current AsyncOperation.
public void ReportProgress(int percentProgress, object userState)
{
if (!WorkerReportsProgress)
{
throw new InvalidOperationException(SR.BackgroundWorker_WorkerDoesntReportProgress);
}
ProgressChangedEventArgs args = new ProgressChangedEventArgs(percentProgress, userState);
if (_asyncOperation != null)
{
_asyncOperation.Post(_progressReporter, args);
}
else
{
_progressReporter(args);
}
}
public void RunWorkerAsync()
{
RunWorkerAsync(null);
}
public void RunWorkerAsync(object argument)
{
if (_isRunning)
{
throw new InvalidOperationException(SR.BackgroundWorker_WorkerAlreadyRunning);
}
_isRunning = true;
_cancellationPending = false;
_asyncOperation = AsyncOperationManager.CreateOperation(null);
Task.Factory.StartNew(
(arg) => WorkerThreadStart(arg),
argument,
CancellationToken.None,
TaskCreationOptions.DenyChildAttach,
TaskScheduler.Default
);
}
public event RunWorkerCompletedEventHandler RunWorkerCompleted;
public bool WorkerReportsProgress
{
get
{
return _workerReportsProgress;
}
set
{
_workerReportsProgress = value;
}
}
public bool WorkerSupportsCancellation
{
get
{
return _canCancelWorker;
}
set
{
_canCancelWorker = value;
}
}
private void WorkerThreadStart(object argument)
{
Debug.Assert(_asyncOperation != null, "_asyncOperation not initialized");
object workerResult = null;
Exception error = null;
bool cancelled = false;
try
{
DoWorkEventArgs doWorkArgs = new DoWorkEventArgs(argument);
OnDoWork(doWorkArgs);
if (doWorkArgs.Cancel)
{
cancelled = true;
}
else
{
workerResult = doWorkArgs.Result;
}
}
catch (Exception exception)
{
error = exception;
}
var e = new RunWorkerCompletedEventArgs(workerResult, error, cancelled);
_asyncOperation.PostOperationCompleted(_operationCompleted, e);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace WebApi.SitemapService.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
private const int DefaultCollectionSize = 3;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
//
//
// A pair of schedulers that together support concurrent (reader) / exclusive (writer)
// task scheduling. Using just the exclusive scheduler can be used to simulate a serial
// processing queue, and using just the concurrent scheduler with a specified
// MaximumConcurrentlyLevel can be used to achieve a MaxDegreeOfParallelism across
// a bunch of tasks, parallel loops, dataflow blocks, etc.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Security;
namespace System.Threading.Tasks
{
/// <summary>
/// Provides concurrent and exclusive task schedulers that coordinate to execute
/// tasks while ensuring that concurrent tasks may run concurrently and exclusive tasks never do.
/// </summary>
[DebuggerDisplay("Concurrent={ConcurrentTaskCountForDebugger}, Exclusive={ExclusiveTaskCountForDebugger}, Mode={ModeForDebugger}")]
[DebuggerTypeProxy(typeof(ConcurrentExclusiveSchedulerPair.DebugView))]
public class ConcurrentExclusiveSchedulerPair
{
/// <summary>A dictionary mapping thread ID to a processing mode to denote what kinds of tasks are currently being processed on this thread.</summary>
private readonly ConcurrentDictionary<int, ProcessingMode> m_threadProcessingMapping = new ConcurrentDictionary<int, ProcessingMode>();
/// <summary>The scheduler used to queue and execute "concurrent" tasks that may run concurrently with other concurrent tasks.</summary>
private readonly ConcurrentExclusiveTaskScheduler m_concurrentTaskScheduler;
/// <summary>The scheduler used to queue and execute "exclusive" tasks that must run exclusively while no other tasks for this pair are running.</summary>
private readonly ConcurrentExclusiveTaskScheduler m_exclusiveTaskScheduler;
/// <summary>The underlying task scheduler to which all work should be scheduled.</summary>
private readonly TaskScheduler m_underlyingTaskScheduler;
/// <summary>
/// The maximum number of tasks allowed to run concurrently. This only applies to concurrent tasks,
/// since exlusive tasks are inherently limited to 1.
/// </summary>
private readonly int m_maxConcurrencyLevel;
/// <summary>The maximum number of tasks we can process before recyling our runner tasks.</summary>
private readonly int m_maxItemsPerTask;
/// <summary>
/// If positive, it represents the number of concurrently running concurrent tasks.
/// If negative, it means an exclusive task has been scheduled.
/// If 0, nothing has been scheduled.
/// </summary>
private int m_processingCount;
/// <summary>Completion state for a task representing the completion of this pair.</summary>
/// <remarks>Lazily-initialized only if the scheduler pair is shutting down or if the Completion is requested.</remarks>
private CompletionState m_completionState;
/// <summary>A constant value used to signal unlimited processing.</summary>
private const int UNLIMITED_PROCESSING = -1;
/// <summary>Constant used for m_processingCount to indicate that an exclusive task is being processed.</summary>
private const int EXCLUSIVE_PROCESSING_SENTINEL = -1;
/// <summary>Default MaxItemsPerTask to use for processing if none is specified.</summary>
private const int DEFAULT_MAXITEMSPERTASK = UNLIMITED_PROCESSING;
/// <summary>Default MaxConcurrencyLevel is the processor count if not otherwise specified.</summary>
private static Int32 DefaultMaxConcurrencyLevel { get { return Environment.ProcessorCount; } }
/// <summary>Gets the sync obj used to protect all state on this instance.</summary>
private object ValueLock { get { return m_threadProcessingMapping; } }
/// <summary>
/// Initializes the ConcurrentExclusiveSchedulerPair.
/// </summary>
public ConcurrentExclusiveSchedulerPair() :
this(TaskScheduler.Default, DefaultMaxConcurrencyLevel, DEFAULT_MAXITEMSPERTASK)
{ }
/// <summary>
/// Initializes the ConcurrentExclusiveSchedulerPair to target the specified scheduler.
/// </summary>
/// <param name="taskScheduler">The target scheduler on which this pair should execute.</param>
public ConcurrentExclusiveSchedulerPair(TaskScheduler taskScheduler) :
this(taskScheduler, DefaultMaxConcurrencyLevel, DEFAULT_MAXITEMSPERTASK)
{ }
/// <summary>
/// Initializes the ConcurrentExclusiveSchedulerPair to target the specified scheduler with a maximum concurrency level.
/// </summary>
/// <param name="taskScheduler">The target scheduler on which this pair should execute.</param>
/// <param name="maxConcurrencyLevel">The maximum number of tasks to run concurrently.</param>
public ConcurrentExclusiveSchedulerPair(TaskScheduler taskScheduler, int maxConcurrencyLevel) :
this(taskScheduler, maxConcurrencyLevel, DEFAULT_MAXITEMSPERTASK)
{ }
/// <summary>
/// Initializes the ConcurrentExclusiveSchedulerPair to target the specified scheduler with a maximum
/// concurrency level and a maximum number of scheduled tasks that may be processed as a unit.
/// </summary>
/// <param name="taskScheduler">The target scheduler on which this pair should execute.</param>
/// <param name="maxConcurrencyLevel">The maximum number of tasks to run concurrently.</param>
/// <param name="maxItemsPerTask">The maximum number of tasks to process for each underlying scheduled task used by the pair.</param>
public ConcurrentExclusiveSchedulerPair(TaskScheduler taskScheduler, int maxConcurrencyLevel, int maxItemsPerTask)
{
// Validate arguments
if (taskScheduler == null) throw new ArgumentNullException(nameof(taskScheduler));
if (maxConcurrencyLevel == 0 || maxConcurrencyLevel < -1) throw new ArgumentOutOfRangeException(nameof(maxConcurrencyLevel));
if (maxItemsPerTask == 0 || maxItemsPerTask < -1) throw new ArgumentOutOfRangeException(nameof(maxItemsPerTask));
Contract.EndContractBlock();
// Store configuration
m_underlyingTaskScheduler = taskScheduler;
m_maxConcurrencyLevel = maxConcurrencyLevel;
m_maxItemsPerTask = maxItemsPerTask;
// Downgrade to the underlying scheduler's max degree of parallelism if it's lower than the user-supplied level
int mcl = taskScheduler.MaximumConcurrencyLevel;
if (mcl > 0 && mcl < m_maxConcurrencyLevel) m_maxConcurrencyLevel = mcl;
// Treat UNLIMITED_PROCESSING/-1 for both MCL and MIPT as the biggest possible value so that we don't
// have to special case UNLIMITED_PROCESSING later on in processing.
if (m_maxConcurrencyLevel == UNLIMITED_PROCESSING) m_maxConcurrencyLevel = Int32.MaxValue;
if (m_maxItemsPerTask == UNLIMITED_PROCESSING) m_maxItemsPerTask = Int32.MaxValue;
// Create the concurrent/exclusive schedulers for this pair
m_exclusiveTaskScheduler = new ConcurrentExclusiveTaskScheduler(this, 1, ProcessingMode.ProcessingExclusiveTask);
m_concurrentTaskScheduler = new ConcurrentExclusiveTaskScheduler(this, m_maxConcurrencyLevel, ProcessingMode.ProcessingConcurrentTasks);
}
/// <summary>Informs the scheduler pair that it should not accept any more tasks.</summary>
/// <remarks>
/// Calling <see cref="Complete"/> is optional, and it's only necessary if the <see cref="Completion"/>
/// will be relied on for notification of all processing being completed.
/// </remarks>
public void Complete()
{
lock (ValueLock)
{
if (!CompletionRequested)
{
RequestCompletion();
CleanupStateIfCompletingAndQuiesced();
}
}
}
/// <summary>Gets a <see cref="System.Threading.Tasks.Task"/> that will complete when the scheduler has completed processing.</summary>
public Task Completion
{
// ValueLock not needed, but it's ok if it's held
get { return EnsureCompletionStateInitialized().Task; }
}
/// <summary>Gets the lazily-initialized completion state.</summary>
private CompletionState EnsureCompletionStateInitialized()
{
// ValueLock not needed, but it's ok if it's held
return LazyInitializer.EnsureInitialized(ref m_completionState, () => new CompletionState());
}
/// <summary>Gets whether completion has been requested.</summary>
private bool CompletionRequested
{
// ValueLock not needed, but it's ok if it's held
get { return m_completionState != null && Volatile.Read(ref m_completionState.m_completionRequested); }
}
/// <summary>Sets that completion has been requested.</summary>
private void RequestCompletion()
{
ContractAssertMonitorStatus(ValueLock, held: true);
EnsureCompletionStateInitialized().m_completionRequested = true;
}
/// <summary>
/// Cleans up state if and only if there's no processing currently happening
/// and no more to be done later.
/// </summary>
private void CleanupStateIfCompletingAndQuiesced()
{
ContractAssertMonitorStatus(ValueLock, held: true);
if (ReadyToComplete) CompleteTaskAsync();
}
/// <summary>Gets whether the pair is ready to complete.</summary>
private bool ReadyToComplete
{
get
{
ContractAssertMonitorStatus(ValueLock, held: true);
// We can only complete if completion has been requested and no processing is currently happening.
if (!CompletionRequested || m_processingCount != 0) return false;
// Now, only allow shutdown if an exception occurred or if there are no more tasks to process.
var cs = EnsureCompletionStateInitialized();
return
(cs.m_exceptions != null && cs.m_exceptions.Count > 0) ||
(m_concurrentTaskScheduler.m_tasks.IsEmpty && m_exclusiveTaskScheduler.m_tasks.IsEmpty);
}
}
/// <summary>Completes the completion task asynchronously.</summary>
private void CompleteTaskAsync()
{
Contract.Requires(ReadyToComplete, "The block must be ready to complete to be here.");
ContractAssertMonitorStatus(ValueLock, held: true);
// Ensure we only try to complete once, then schedule completion
// in order to escape held locks and the caller's context
var cs = EnsureCompletionStateInitialized();
if (!cs.m_completionQueued)
{
cs.m_completionQueued = true;
ThreadPool.QueueUserWorkItem(state =>
{
var localCs = (CompletionState)state; // don't use 'cs', as it'll force a closure
Debug.Assert(!localCs.Task.IsCompleted, "Completion should only happen once.");
var exceptions = localCs.m_exceptions;
bool success = (exceptions != null && exceptions.Count > 0) ?
localCs.TrySetException(exceptions) :
localCs.TrySetResult(default(VoidTaskResult));
Debug.Assert(success, "Expected to complete completion task.");
}, cs);
}
}
/// <summary>Initiatites scheduler shutdown due to a worker task faulting..</summary>
/// <param name="faultedTask">The faulted worker task that's initiating the shutdown.</param>
private void FaultWithTask(Task faultedTask)
{
Contract.Requires(faultedTask != null && faultedTask.IsFaulted && faultedTask.Exception.InnerExceptions.Count > 0,
"Needs a task in the faulted state and thus with exceptions.");
ContractAssertMonitorStatus(ValueLock, held: true);
// Store the faulted task's exceptions
var cs = EnsureCompletionStateInitialized();
if (cs.m_exceptions == null) cs.m_exceptions = new List<Exception>();
cs.m_exceptions.AddRange(faultedTask.Exception.InnerExceptions);
// Now that we're doomed, request completion
RequestCompletion();
}
/// <summary>
/// Gets a TaskScheduler that can be used to schedule tasks to this pair
/// that may run concurrently with other tasks on this pair.
/// </summary>
public TaskScheduler ConcurrentScheduler { get { return m_concurrentTaskScheduler; } }
/// <summary>
/// Gets a TaskScheduler that can be used to schedule tasks to this pair
/// that must run exclusively with regards to other tasks on this pair.
/// </summary>
public TaskScheduler ExclusiveScheduler { get { return m_exclusiveTaskScheduler; } }
/// <summary>Gets the number of tasks waiting to run concurrently.</summary>
/// <remarks>This does not take the necessary lock, as it's only called from under the debugger.</remarks>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
private int ConcurrentTaskCountForDebugger { get { return m_concurrentTaskScheduler.m_tasks.Count; } }
/// <summary>Gets the number of tasks waiting to run exclusively.</summary>
/// <remarks>This does not take the necessary lock, as it's only called from under the debugger.</remarks>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
private int ExclusiveTaskCountForDebugger { get { return m_exclusiveTaskScheduler.m_tasks.Count; } }
/// <summary>Notifies the pair that new work has arrived to be processed.</summary>
/// <param name="fairly">Whether tasks should be scheduled fairly with regards to other tasks.</param>
/// <remarks>Must only be called while holding the lock.</remarks>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
[SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals")]
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
private void ProcessAsyncIfNecessary(bool fairly = false)
{
ContractAssertMonitorStatus(ValueLock, held: true);
// If the current processing count is >= 0, we can potentially launch further processing.
if (m_processingCount >= 0)
{
// We snap whether there are any exclusive tasks or concurrent tasks waiting.
// (We grab the concurrent count below only once we know we need it.)
// With processing happening concurrent to this operation, this data may
// immediately be out of date, but it can only go from non-empty
// to empty and not the other way around. As such, this is safe,
// as worst case is we'll schedule an extra task when we didn't
// otherwise need to, and we'll just eat its overhead.
bool exclusiveTasksAreWaiting = !m_exclusiveTaskScheduler.m_tasks.IsEmpty;
// If there's no processing currently happening but there are waiting exclusive tasks,
// let's start processing those exclusive tasks.
Task processingTask = null;
if (m_processingCount == 0 && exclusiveTasksAreWaiting)
{
// Launch exclusive task processing
m_processingCount = EXCLUSIVE_PROCESSING_SENTINEL; // -1
try
{
processingTask = new Task(thisPair => ((ConcurrentExclusiveSchedulerPair)thisPair).ProcessExclusiveTasks(), this,
default(CancellationToken), GetCreationOptionsForTask(fairly));
processingTask.Start(m_underlyingTaskScheduler);
// When we call Start, if the underlying scheduler throws in QueueTask, TPL will fault the task and rethrow
// the exception. To deal with that, we need a reference to the task object, so that we can observe its exception.
// Hence, we separate creation and starting, so that we can store a reference to the task before we attempt QueueTask.
}
catch
{
m_processingCount = 0;
FaultWithTask(processingTask);
}
}
// If there are no waiting exclusive tasks, there are concurrent tasks, and we haven't reached our maximum
// concurrency level for processing, let's start processing more concurrent tasks.
else
{
int concurrentTasksWaitingCount = m_concurrentTaskScheduler.m_tasks.Count;
if (concurrentTasksWaitingCount > 0 && !exclusiveTasksAreWaiting && m_processingCount < m_maxConcurrencyLevel)
{
// Launch concurrent task processing, up to the allowed limit
for (int i = 0; i < concurrentTasksWaitingCount && m_processingCount < m_maxConcurrencyLevel; ++i)
{
++m_processingCount;
try
{
processingTask = new Task(thisPair => ((ConcurrentExclusiveSchedulerPair)thisPair).ProcessConcurrentTasks(), this,
default(CancellationToken), GetCreationOptionsForTask(fairly));
processingTask.Start(m_underlyingTaskScheduler); // See above logic for why we use new + Start rather than StartNew
}
catch
{
--m_processingCount;
FaultWithTask(processingTask);
}
}
}
}
// Check to see if all tasks have completed and if completion has been requested.
CleanupStateIfCompletingAndQuiesced();
}
else Debug.Assert(m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL, "The processing count must be the sentinel if it's not >= 0.");
}
/// <summary>
/// Processes exclusive tasks serially until either there are no more to process
/// or we've reached our user-specified maximum limit.
/// </summary>
private void ProcessExclusiveTasks()
{
Contract.Requires(m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL, "Processing exclusive tasks requires being in exclusive mode.");
Contract.Requires(!m_exclusiveTaskScheduler.m_tasks.IsEmpty, "Processing exclusive tasks requires tasks to be processed.");
ContractAssertMonitorStatus(ValueLock, held: false);
try
{
// Note that we're processing exclusive tasks on the current thread
Debug.Assert(!m_threadProcessingMapping.ContainsKey(Thread.CurrentThread.ManagedThreadId),
"This thread should not yet be involved in this pair's processing.");
m_threadProcessingMapping[Thread.CurrentThread.ManagedThreadId] = ProcessingMode.ProcessingExclusiveTask;
// Process up to the maximum number of items per task allowed
for (int i = 0; i < m_maxItemsPerTask; i++)
{
// Get the next available exclusive task. If we can't find one, bail.
Task exclusiveTask;
if (!m_exclusiveTaskScheduler.m_tasks.TryDequeue(out exclusiveTask)) break;
// Execute the task. If the scheduler was previously faulted,
// this task could have been faulted when it was queued; ignore such tasks.
if (!exclusiveTask.IsFaulted) m_exclusiveTaskScheduler.ExecuteTask(exclusiveTask);
}
}
finally
{
// We're no longer processing exclusive tasks on the current thread
ProcessingMode currentMode;
m_threadProcessingMapping.TryRemove(Thread.CurrentThread.ManagedThreadId, out currentMode);
Debug.Assert(currentMode == ProcessingMode.ProcessingExclusiveTask,
"Somehow we ended up escaping exclusive mode.");
lock (ValueLock)
{
// When this task was launched, we tracked it by setting m_processingCount to WRITER_IN_PROGRESS.
// now reset it to 0. Then check to see whether there's more processing to be done.
// There might be more concurrent tasks available, for example, if concurrent tasks arrived
// after we exited the loop, or if we exited the loop while concurrent tasks were still
// available but we hit our maxItemsPerTask limit.
Debug.Assert(m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL, "The processing mode should not have deviated from exclusive.");
m_processingCount = 0;
ProcessAsyncIfNecessary(true);
}
}
}
/// <summary>
/// Processes concurrent tasks serially until either there are no more to process,
/// we've reached our user-specified maximum limit, or exclusive tasks have arrived.
/// </summary>
private void ProcessConcurrentTasks()
{
Contract.Requires(m_processingCount > 0, "Processing concurrent tasks requires us to be in concurrent mode.");
ContractAssertMonitorStatus(ValueLock, held: false);
try
{
// Note that we're processing concurrent tasks on the current thread
Debug.Assert(!m_threadProcessingMapping.ContainsKey(Thread.CurrentThread.ManagedThreadId),
"This thread should not yet be involved in this pair's processing.");
m_threadProcessingMapping[Thread.CurrentThread.ManagedThreadId] = ProcessingMode.ProcessingConcurrentTasks;
// Process up to the maximum number of items per task allowed
for (int i = 0; i < m_maxItemsPerTask; i++)
{
// Get the next available concurrent task. If we can't find one, bail.
Task concurrentTask;
if (!m_concurrentTaskScheduler.m_tasks.TryDequeue(out concurrentTask)) break;
// Execute the task. If the scheduler was previously faulted,
// this task could have been faulted when it was queued; ignore such tasks.
if (!concurrentTask.IsFaulted) m_concurrentTaskScheduler.ExecuteTask(concurrentTask);
// Now check to see if exclusive tasks have arrived; if any have, they take priority
// so we'll bail out here. Note that we could have checked this condition
// in the for loop's condition, but that could lead to extra overhead
// in the case where a concurrent task arrives, this task is launched, and then
// before entering the loop an exclusive task arrives. If we didn't execute at
// least one task, we would have spent all of the overhead to launch a
// task but with none of the benefit. There's of course also an inherent
// race condition here with regards to exclusive tasks arriving, and we're ok with
// executing one more concurrent task than we should before giving priority to exclusive tasks.
if (!m_exclusiveTaskScheduler.m_tasks.IsEmpty) break;
}
}
finally
{
// We're no longer processing concurrent tasks on the current thread
ProcessingMode currentMode;
m_threadProcessingMapping.TryRemove(Thread.CurrentThread.ManagedThreadId, out currentMode);
Debug.Assert(currentMode == ProcessingMode.ProcessingConcurrentTasks,
"Somehow we ended up escaping concurrent mode.");
lock (ValueLock)
{
// When this task was launched, we tracked it with a positive processing count;
// decrement that count. Then check to see whether there's more processing to be done.
// There might be more concurrent tasks available, for example, if concurrent tasks arrived
// after we exited the loop, or if we exited the loop while concurrent tasks were still
// available but we hit our maxItemsPerTask limit.
Debug.Assert(m_processingCount > 0, "The procesing mode should not have deviated from concurrent.");
if (m_processingCount > 0) --m_processingCount;
ProcessAsyncIfNecessary(true);
}
}
}
#if PRENET45
/// <summary>
/// Type used with TaskCompletionSource(Of TResult) as the TResult
/// to ensure that the resulting task can't be upcast to something
/// that in the future could lead to compat problems.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses")]
[DebuggerNonUserCode]
private struct VoidTaskResult { }
#endif
/// <summary>
/// Holder for lazily-initialized state about the completion of a scheduler pair.
/// Completion is only triggered either by rare exceptional conditions or by
/// the user calling Complete, and as such we only lazily initialize this
/// state in one of those conditions or if the user explicitly asks for
/// the Completion.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses")]
private sealed class CompletionState : TaskCompletionSource<VoidTaskResult>
{
/// <summary>Whether the scheduler has had completion requested.</summary>
/// <remarks>This variable is not volatile, so to gurantee safe reading reads, Volatile.Read is used in TryExecuteTaskInline.</remarks>
internal bool m_completionRequested;
/// <summary>Whether completion processing has been queued.</summary>
internal bool m_completionQueued;
/// <summary>Unrecoverable exceptions incurred while processing.</summary>
internal List<Exception> m_exceptions;
}
/// <summary>
/// A scheduler shim used to queue tasks to the pair and execute those tasks on request of the pair.
/// </summary>
[DebuggerDisplay("Count={CountForDebugger}, MaxConcurrencyLevel={m_maxConcurrencyLevel}, Id={Id}")]
[DebuggerTypeProxy(typeof(ConcurrentExclusiveTaskScheduler.DebugView))]
private sealed class ConcurrentExclusiveTaskScheduler : TaskScheduler
{
/// <summary>Cached delegate for invoking TryExecuteTaskShim.</summary>
private static readonly Func<object, bool> s_tryExecuteTaskShim = new Func<object, bool>(TryExecuteTaskShim);
/// <summary>The parent pair.</summary>
private readonly ConcurrentExclusiveSchedulerPair m_pair;
/// <summary>The maximum concurrency level for the scheduler.</summary>
private readonly int m_maxConcurrencyLevel;
/// <summary>The processing mode of this scheduler, exclusive or concurrent.</summary>
private readonly ProcessingMode m_processingMode;
/// <summary>Gets the queue of tasks for this scheduler.</summary>
internal readonly IProducerConsumerQueue<Task> m_tasks;
/// <summary>Initializes the scheduler.</summary>
/// <param name="pair">The parent pair.</param>
/// <param name="maxConcurrencyLevel">The maximum degree of concurrency this scheduler may use.</param>
/// <param name="processingMode">The processing mode of this scheduler.</param>
internal ConcurrentExclusiveTaskScheduler(ConcurrentExclusiveSchedulerPair pair, int maxConcurrencyLevel, ProcessingMode processingMode)
{
Contract.Requires(pair != null, "Scheduler must be associated with a valid pair.");
Contract.Requires(processingMode == ProcessingMode.ProcessingConcurrentTasks || processingMode == ProcessingMode.ProcessingExclusiveTask,
"Scheduler must be for concurrent or exclusive processing.");
Contract.Requires(
(processingMode == ProcessingMode.ProcessingConcurrentTasks && (maxConcurrencyLevel >= 1 || maxConcurrencyLevel == UNLIMITED_PROCESSING)) ||
(processingMode == ProcessingMode.ProcessingExclusiveTask && maxConcurrencyLevel == 1),
"If we're in concurrent mode, our concurrency level should be positive or unlimited. If exclusive, it should be 1.");
m_pair = pair;
m_maxConcurrencyLevel = maxConcurrencyLevel;
m_processingMode = processingMode;
m_tasks = (processingMode == ProcessingMode.ProcessingExclusiveTask) ?
(IProducerConsumerQueue<Task>)new SingleProducerSingleConsumerQueue<Task>() :
(IProducerConsumerQueue<Task>)new MultiProducerMultiConsumerQueue<Task>();
}
/// <summary>Gets the maximum concurrency level this scheduler is able to support.</summary>
public override int MaximumConcurrencyLevel { get { return m_maxConcurrencyLevel; } }
/// <summary>Queues a task to the scheduler.</summary>
/// <param name="task">The task to be queued.</param>
protected internal override void QueueTask(Task task)
{
Debug.Assert(task != null, "Infrastructure should have provided a non-null task.");
lock (m_pair.ValueLock)
{
// If the scheduler has already had completion requested, no new work is allowed to be scheduled
if (m_pair.CompletionRequested) throw new InvalidOperationException(GetType().Name);
// Queue the task, and then let the pair know that more work is now available to be scheduled
m_tasks.Enqueue(task);
m_pair.ProcessAsyncIfNecessary();
}
}
/// <summary>Executes a task on this scheduler.</summary>
/// <param name="task">The task to be executed.</param>
internal void ExecuteTask(Task task)
{
Debug.Assert(task != null, "Infrastructure should have provided a non-null task.");
base.TryExecuteTask(task);
}
/// <summary>Tries to execute the task synchronously on this scheduler.</summary>
/// <param name="task">The task to execute.</param>
/// <param name="taskWasPreviouslyQueued">Whether the task was previously queued to the scheduler.</param>
/// <returns>true if the task could be executed; otherwise, false.</returns>
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
{
Debug.Assert(task != null, "Infrastructure should have provided a non-null task.");
// If the scheduler has had completion requested, no new work is allowed to be scheduled.
// A non-locked read on m_completionRequested (in CompletionRequested) is acceptable here because:
// a) we don't need to be exact... a Complete call could come in later in the function anyway
// b) this is only a fast path escape hatch. To actually inline the task,
// we need to be inside of an already executing task, and in such a case,
// while completion may have been requested, we can't have shutdown yet.
if (!taskWasPreviouslyQueued && m_pair.CompletionRequested) return false;
// We know the implementation of the default scheduler and how it will behave.
// As it's the most common underlying scheduler, we optimize for it.
bool isDefaultScheduler = m_pair.m_underlyingTaskScheduler == TaskScheduler.Default;
// If we're targeting the default scheduler and taskWasPreviouslyQueued is true,
// we know that the default scheduler will only allow it to be inlined
// if we're on a thread pool thread (but it won't always allow it in that case,
// since it'll only allow inlining if it can find the task in the local queue).
// As such, if we're not on a thread pool thread, we know for sure the
// task won't be inlined, so let's not even try.
if (isDefaultScheduler && taskWasPreviouslyQueued && !Thread.CurrentThread.IsThreadPoolThread)
{
return false;
}
else
{
// If a task is already running on this thread, allow inline execution to proceed.
// If there's already a task from this scheduler running on the current thread, we know it's safe
// to run this task, in effect temporarily taking that task's count allocation.
ProcessingMode currentThreadMode;
if (m_pair.m_threadProcessingMapping.TryGetValue(Thread.CurrentThread.ManagedThreadId, out currentThreadMode) &&
currentThreadMode == m_processingMode)
{
// If we're targeting the default scheduler and taskWasPreviouslyQueued is false,
// we know the default scheduler will allow it, so we can just execute it here.
// Otherwise, delegate to the target scheduler's inlining.
return (isDefaultScheduler && !taskWasPreviouslyQueued) ?
TryExecuteTask(task) :
TryExecuteTaskInlineOnTargetScheduler(task);
}
}
// We're not in the context of a task already executing on this scheduler. Bail.
return false;
}
/// <summary>
/// Implements a reasonable approximation for TryExecuteTaskInline on the underlying scheduler,
/// which we can't call directly on the underlying scheduler.
/// </summary>
/// <param name="task">The task to execute inline if possible.</param>
/// <returns>true if the task was inlined successfully; otherwise, false.</returns>
[SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "ignored")]
private bool TryExecuteTaskInlineOnTargetScheduler(Task task)
{
// We'd like to simply call TryExecuteTaskInline here, but we can't.
// As there's no built-in API for this, a workaround is to create a new task that,
// when executed, will simply call TryExecuteTask to run the real task, and then
// we run our new shim task synchronously on the target scheduler. If all goes well,
// our synchronous invocation will succeed in running the shim task on the current thread,
// which will in turn run the real task on the current thread. If the scheduler
// doesn't allow that execution, RunSynchronously will block until the underlying scheduler
// is able to invoke the task, which might account for an additional but unavoidable delay.
// Once it's done, we can return whether the task executed by returning the
// shim task's Result, which is in turn the result of TryExecuteTask.
var t = new Task<bool>(s_tryExecuteTaskShim, Tuple.Create(this, task));
try
{
t.RunSynchronously(m_pair.m_underlyingTaskScheduler);
return t.Result;
}
catch
{
Debug.Assert(t.IsFaulted, "Task should be faulted due to the scheduler faulting it and throwing the exception.");
var ignored = t.Exception;
throw;
}
finally { t.Dispose(); }
}
/// <summary>Shim used to invoke this.TryExecuteTask(task).</summary>
/// <param name="state">A tuple of the ConcurrentExclusiveTaskScheduler and the task to execute.</param>
/// <returns>true if the task was successfully inlined; otherwise, false.</returns>
/// <remarks>
/// This method is separated out not because of performance reasons but so that
/// the SecuritySafeCritical attribute may be employed.
/// </remarks>
private static bool TryExecuteTaskShim(object state)
{
var tuple = (Tuple<ConcurrentExclusiveTaskScheduler, Task>)state;
return tuple.Item1.TryExecuteTask(tuple.Item2);
}
/// <summary>Gets for debugging purposes the tasks scheduled to this scheduler.</summary>
/// <returns>An enumerable of the tasks queued.</returns>
protected override IEnumerable<Task> GetScheduledTasks() { return m_tasks; }
/// <summary>Gets the number of tasks queued to this scheduler.</summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
private int CountForDebugger { get { return m_tasks.Count; } }
/// <summary>Provides a debug view for ConcurrentExclusiveTaskScheduler.</summary>
private sealed class DebugView
{
/// <summary>The scheduler being debugged.</summary>
private readonly ConcurrentExclusiveTaskScheduler m_taskScheduler;
/// <summary>Initializes the debug view.</summary>
/// <param name="scheduler">The scheduler being debugged.</param>
public DebugView(ConcurrentExclusiveTaskScheduler scheduler)
{
Contract.Requires(scheduler != null, "Need a scheduler with which to construct the debug view.");
m_taskScheduler = scheduler;
}
/// <summary>Gets this pair's maximum allowed concurrency level.</summary>
public int MaximumConcurrencyLevel { get { return m_taskScheduler.m_maxConcurrencyLevel; } }
/// <summary>Gets the tasks scheduled to this scheduler.</summary>
public IEnumerable<Task> ScheduledTasks { get { return m_taskScheduler.m_tasks; } }
/// <summary>Gets the scheduler pair with which this scheduler is associated.</summary>
public ConcurrentExclusiveSchedulerPair SchedulerPair { get { return m_taskScheduler.m_pair; } }
}
}
/// <summary>Provides a debug view for ConcurrentExclusiveSchedulerPair.</summary>
private sealed class DebugView
{
/// <summary>The pair being debugged.</summary>
private readonly ConcurrentExclusiveSchedulerPair m_pair;
/// <summary>Initializes the debug view.</summary>
/// <param name="pair">The pair being debugged.</param>
public DebugView(ConcurrentExclusiveSchedulerPair pair)
{
Contract.Requires(pair != null, "Need a pair with which to construct the debug view.");
m_pair = pair;
}
/// <summary>Gets a representation of the execution state of the pair.</summary>
public ProcessingMode Mode { get { return m_pair.ModeForDebugger; } }
/// <summary>Gets the number of tasks waiting to run exclusively.</summary>
public IEnumerable<Task> ScheduledExclusive { get { return m_pair.m_exclusiveTaskScheduler.m_tasks; } }
/// <summary>Gets the number of tasks waiting to run concurrently.</summary>
public IEnumerable<Task> ScheduledConcurrent { get { return m_pair.m_concurrentTaskScheduler.m_tasks; } }
/// <summary>Gets the number of tasks currently being executed.</summary>
public int CurrentlyExecutingTaskCount
{
get { return (m_pair.m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL) ? 1 : m_pair.m_processingCount; }
}
/// <summary>Gets the underlying task scheduler that actually executes the tasks.</summary>
public TaskScheduler TargetScheduler { get { return m_pair.m_underlyingTaskScheduler; } }
}
/// <summary>Gets an enumeration for debugging that represents the current state of the scheduler pair.</summary>
/// <remarks>This is only for debugging. It does not take the necessary locks to be useful for runtime usage.</remarks>
private ProcessingMode ModeForDebugger
{
get
{
// If our completion task is done, so are we.
if (m_completionState != null && m_completionState.Task.IsCompleted) return ProcessingMode.Completed;
// Otherwise, summarize our current state.
var mode = ProcessingMode.NotCurrentlyProcessing;
if (m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL) mode |= ProcessingMode.ProcessingExclusiveTask;
if (m_processingCount >= 1) mode |= ProcessingMode.ProcessingConcurrentTasks;
if (CompletionRequested) mode |= ProcessingMode.Completing;
return mode;
}
}
/// <summary>Asserts that a given synchronization object is either held or not held.</summary>
/// <param name="syncObj">The monitor to check.</param>
/// <param name="held">Whether we want to assert that it's currently held or not held.</param>
[Conditional("DEBUG")]
internal static void ContractAssertMonitorStatus(object syncObj, bool held)
{
Contract.Requires(syncObj != null, "The monitor object to check must be provided.");
#if PRENET45
#if DEBUG
// This check is expensive,
// which is why it's protected by ShouldCheckMonitorStatus and controlled by an environment variable DEBUGSYNC.
if (ShouldCheckMonitorStatus)
{
bool exceptionThrown;
try
{
Monitor.Pulse(syncObj); // throws a SynchronizationLockException if the monitor isn't held by this thread
exceptionThrown = false;
}
catch (SynchronizationLockException) { exceptionThrown = true; }
Debug.Assert(held == !exceptionThrown, "The locking scheme was not correctly followed.");
}
#endif
#else
Debug.Assert(Monitor.IsEntered(syncObj) == held, "The locking scheme was not correctly followed.");
#endif
}
/// <summary>Gets the options to use for tasks.</summary>
/// <param name="isReplacementReplica">If this task is being created to replace another.</param>
/// <remarks>
/// These options should be used for all tasks that have the potential to run user code or
/// that are repeatedly spawned and thus need a modicum of fair treatment.
/// </remarks>
/// <returns>The options to use.</returns>
internal static TaskCreationOptions GetCreationOptionsForTask(bool isReplacementReplica = false)
{
TaskCreationOptions options =
#if PRENET45
TaskCreationOptions.None;
#else
TaskCreationOptions.DenyChildAttach;
#endif
if (isReplacementReplica) options |= TaskCreationOptions.PreferFairness;
return options;
}
/// <summary>Provides an enumeration that represents the current state of the scheduler pair.</summary>
[Flags]
private enum ProcessingMode : byte
{
/// <summary>The scheduler pair is currently dormant, with no work scheduled.</summary>
NotCurrentlyProcessing = 0x0,
/// <summary>The scheduler pair has queued processing for exclusive tasks.</summary>
ProcessingExclusiveTask = 0x1,
/// <summary>The scheduler pair has queued processing for concurrent tasks.</summary>
ProcessingConcurrentTasks = 0x2,
/// <summary>Completion has been requested.</summary>
Completing = 0x4,
/// <summary>The scheduler pair is finished processing.</summary>
Completed = 0x8
}
}
}
| |
//
// X11NotificationArea.cs
//
// Authors:
// Todd Berman <[email protected]>
// Ed Catmur <[email protected]>
// Miguel de Icaza <[email protected]>
// Aaron Bockover <[email protected]>
//
// Copyright (C) 2005 Todd Berman
// Copyright (C) 2005 Ed Catmur
// Copyright (C) 2005-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.
//
// NOTE: throughout IntPtr is used for the Xlib long type, as this tends to
// have the correct width and does not require any configure checks.
using System;
using System.Runtime.InteropServices;
using Gtk;
using Gdk;
#pragma warning disable 0169, 0414
public class X11NotificationArea : Plug
{
private uint stamp;
private Orientation orientation;
private IntPtr selection_atom;
private IntPtr manager_atom;
private IntPtr system_tray_opcode_atom;
private IntPtr orientation_atom;
private IntPtr message_data_atom;
private IntPtr manager_window;
private FilterFunc filter;
public X11NotificationArea (string name)
{
Title = name;
Init ();
}
public X11NotificationArea (string name, Gdk.Screen screen)
{
Title = name;
Screen = screen;
Init ();
}
[DllImport ("libc")]
private static extern IntPtr memcpy (ref XClientMessageEvent.DataUnion dest, IntPtr src, IntPtr len);
public uint SendMessage (uint timeout, string message)
{
if (manager_window == IntPtr.Zero) {
return 0;
}
byte[] arr = System.Text.Encoding.UTF8.GetBytes (message);
IntPtr unmanaged_arr = Marshal.AllocHGlobal (arr.Length);
Marshal.Copy (arr, 0, unmanaged_arr, arr.Length);
SendManagerMessage (SystemTrayMessage.BeginMessage, (IntPtr) Id, timeout, (uint) arr.Length, ++stamp);
gdk_error_trap_push ();
for (int index = 0; index < message.Length; index += 20) {
XClientMessageEvent ev = new XClientMessageEvent ();
IntPtr display = gdk_x11_display_get_xdisplay (Display.Handle);
ev.type = XEventName.ClientMessage;
ev.window = (IntPtr) Id;
ev.format = 8;
ev.message_type = message_data_atom;
int len = Math.Min (arr.Length - index, 20);
memcpy (ref ev.data, (IntPtr)((int)unmanaged_arr + index), (IntPtr)len);
XSendEvent (display, manager_window, false, (IntPtr) EventMask.StructureNotifyMask, ref ev);
XSync (display, false);
}
gdk_error_trap_pop ();
return stamp;
}
public void CancelMessage (uint id)
{
if (id == 0) {
return;
}
SendManagerMessage (SystemTrayMessage.CancelMessage, (IntPtr) Id, id, 0, 0);
}
private void Init ()
{
stamp = 1;
orientation = Orientation.Horizontal;
AddEvents ((int)EventMask.PropertyChangeMask);
filter = new FilterFunc (ManagerFilter);
}
[GLib.ConnectBefore]
private void TransparentExposeEvent (object obj, Gtk.ExposeEventArgs args)
{
Gtk.Widget widget = (Gtk.Widget)obj;
Gdk.Rectangle area = args.Event.Area;
widget.GdkWindow.ClearArea (area.X, area.Y, area.Width, area.Height);
}
private void MakeTransparentAgain (object obj, Gtk.StyleSetArgs args)
{
Gtk.Widget widget = (Gtk.Widget)obj;
widget.GdkWindow.SetBackPixmap (null, true);
}
private void MakeTransparent (object obj, EventArgs args)
{
Gtk.Widget widget = (Gtk.Widget)obj;
if (widget.IsNoWindow || widget.IsAppPaintable)
return;
widget.AppPaintable = true;
widget.DoubleBuffered = false;
widget.GdkWindow.SetBackPixmap (null, true);
widget.ExposeEvent += TransparentExposeEvent;
widget.StyleSet += MakeTransparentAgain;
}
protected override void OnRealized ()
{
base.OnRealized ();
MakeTransparent (this, EventArgs.Empty);
Display display = Screen.Display;
IntPtr xdisplay = gdk_x11_display_get_xdisplay (display.Handle);
selection_atom = XInternAtom (xdisplay, "_NET_SYSTEM_TRAY_S" + Screen.Number.ToString (), false);
manager_atom = XInternAtom (xdisplay, "MANAGER", false);
system_tray_opcode_atom = XInternAtom (xdisplay, "_NET_SYSTEM_TRAY_OPCODE", false);
orientation_atom = XInternAtom (xdisplay, "_NET_SYSTEM_TRAY_ORIENTATION", false);
message_data_atom = XInternAtom (xdisplay, "_NET_SYSTEM_TRAY_MESSAGE_DATA", false);
UpdateManagerWindow (false);
SendDockRequest ();
Screen.RootWindow.AddFilter (filter);
}
protected override void OnAdded (Gtk.Widget child)
{
child.Realized += MakeTransparent;
base.OnAdded (child);
}
protected override void OnUnrealized ()
{
if (manager_window != IntPtr.Zero) {
Gdk.Window gdkwin = Gdk.Window.ForeignNewForDisplay (Display, (uint)manager_window);
if (gdkwin != null) {
gdkwin.RemoveFilter (filter);
}
}
Screen.RootWindow.RemoveFilter (filter);
base.OnUnrealized ();
}
private void UpdateManagerWindow (bool dock_if_realized)
{
if(Handle == IntPtr.Zero || Display == null || Display.Handle == IntPtr.Zero) {
return;
}
IntPtr xdisplay = gdk_x11_display_get_xdisplay (Display.Handle);
if (manager_window != IntPtr.Zero) {
return;
}
XGrabServer (xdisplay);
manager_window = XGetSelectionOwner (xdisplay, selection_atom);
if (manager_window != IntPtr.Zero) {
XSelectInput (xdisplay, manager_window, (IntPtr) (EventMask.StructureNotifyMask | EventMask.PropertyChangeMask));
}
XUngrabServer (xdisplay);
XFlush (xdisplay);
if (manager_window != IntPtr.Zero) {
Gdk.Window gdkwin = Gdk.Window.ForeignNewForDisplay (Display, (uint)manager_window);
if (gdkwin != null) {
gdkwin.AddFilter (filter);
}
if (dock_if_realized && IsRealized) {
SendDockRequest ();
}
GetOrientationProperty ();
}
}
private void SendDockRequest ()
{
SendManagerMessage (SystemTrayMessage.RequestDock, manager_window, Id, 0, 0);
}
private void SendManagerMessage (SystemTrayMessage message, IntPtr window, uint data1, uint data2, uint data3)
{
XClientMessageEvent ev = new XClientMessageEvent ();
IntPtr display;
ev.type = XEventName.ClientMessage;
ev.window = window;
ev.message_type = system_tray_opcode_atom;
ev.format = 32;
ev.data.ptr1 = (IntPtr)gdk_x11_get_server_time (GdkWindow.Handle);
ev.data.ptr2 = (IntPtr)message;
ev.data.ptr3 = (IntPtr)data1;
ev.data.ptr4 = (IntPtr)data2;
ev.data.ptr5 = (IntPtr)data3;
display = gdk_x11_display_get_xdisplay (Display.Handle);
gdk_error_trap_push ();
XSendEvent (display, manager_window, false, (IntPtr) EventMask.NoEventMask, ref ev);
XSync (display, false);
gdk_error_trap_pop ();
}
private FilterReturn ManagerFilter (IntPtr xevent, Event evnt)
{
XAnyEvent xev = (XAnyEvent) Marshal.PtrToStructure (xevent, typeof(XAnyEvent));
if (xev.type == XEventName.ClientMessage){
XClientMessageEvent xclient = (XClientMessageEvent) Marshal.PtrToStructure (xevent, typeof(XClientMessageEvent));
if (xclient.message_type == manager_atom && xclient.data.ptr2 == selection_atom) {
UpdateManagerWindow (true);
return FilterReturn.Continue;
}
}
if (xev.window == manager_window) {
if (xev.type == XEventName.PropertyNotify){
XPropertyEvent xproperty = (XPropertyEvent) Marshal.PtrToStructure (xevent, typeof(XPropertyEvent));
if (xproperty.atom == orientation_atom) {
GetOrientationProperty();
return FilterReturn.Continue;
}
}
if (xev.type == XEventName.DestroyNotify) {
ManagerWindowDestroyed();
}
}
return FilterReturn.Continue;
}
private void ManagerWindowDestroyed ()
{
if (manager_window != IntPtr.Zero) {
Gdk.Window gdkwin = Gdk.Window.ForeignNewForDisplay (Display, (uint) manager_window);
if (gdkwin != null) {
gdkwin.RemoveFilter (filter);
}
manager_window = IntPtr.Zero;
UpdateManagerWindow (true);
}
}
private void GetOrientationProperty ()
{
IntPtr display;
IntPtr type;
int format;
IntPtr prop_return;
IntPtr nitems, bytes_after;
int error, result;
if (manager_window == IntPtr.Zero) {
return;
}
display = gdk_x11_display_get_xdisplay (Display.Handle);
gdk_error_trap_push ();
type = IntPtr.Zero;
result = XGetWindowProperty (display, manager_window, orientation_atom, (IntPtr) 0,
(IntPtr) System.Int32.MaxValue, false, (IntPtr) XAtom.Cardinal, out type, out format,
out nitems, out bytes_after, out prop_return);
error = gdk_error_trap_pop ();
if (error != 0 || result != 0) {
return;
}
if (type == (IntPtr) XAtom.Cardinal) {
orientation = ((SystemTrayOrientation) Marshal.ReadInt32 (prop_return) == SystemTrayOrientation.Horz)
? Orientation.Horizontal
: Orientation.Vertical;
}
if (prop_return != IntPtr.Zero) {
XFree (prop_return);
}
}
[DllImport ("libgdk-x11-2.0.so.0")]
private static extern IntPtr gdk_x11_display_get_xdisplay (IntPtr display);
[DllImport ("libgdk-x11-2.0.so.0")]
private static extern int gdk_x11_get_server_time (IntPtr window);
[DllImport ("libgdk-x11-2.0.so.0")]
private static extern void gdk_error_trap_push ();
[DllImport ("libgdk-x11-2.0.so.0")]
private static extern int gdk_error_trap_pop ();
[DllImport ("libX11.so.6")]
private extern static IntPtr XInternAtom(IntPtr display, string atom_name, bool only_if_exists);
[DllImport ("libX11.so.6")]
private extern static void XGrabServer (IntPtr display);
[DllImport ("libX11.so.6")]
private extern static void XUngrabServer (IntPtr display);
[DllImport ("libX11.so.6")]
private extern static int XFlush (IntPtr display);
[DllImport ("libX11.so.6")]
private extern static int XSync (IntPtr display, bool discard);
[DllImport ("libX11.so.6")]
private extern static int XFree (IntPtr display);
[DllImport ("libX11.so.6")]
private extern static IntPtr XGetSelectionOwner (IntPtr display, IntPtr atom);
[DllImport ("libX11.so.6")]
private extern static IntPtr XSelectInput (IntPtr display, IntPtr window, IntPtr mask);
[DllImport ("libX11.so.6")]
private extern static int XSendEvent (IntPtr display, IntPtr window, bool propagate, IntPtr event_mask,
ref XClientMessageEvent send_event);
[DllImport ("libX11.so.6")]
private extern static int XGetWindowProperty (IntPtr display, IntPtr w, IntPtr property, IntPtr long_offset,
IntPtr long_length, bool deleteProp, IntPtr req_type,
out IntPtr actual_type_return, out int actual_format_return,
out IntPtr nitems_return, out IntPtr bytes_after_return,
out IntPtr prop_return);
[Flags]
private enum EventMask {
NoEventMask = 0,
KeyPressMask = 1 << 0,
KeyReleaseMask = 1 << 1,
ButtonPressMask = 1 << 2,
ButtonReleaseMask = 1 << 3,
EnterWindowMask = 1 << 4,
LeaveWindowMask = 1 << 5,
PointerMotionMask = 1 << 6,
PointerMotionHintMask = 1 << 7,
Button1MotionMask = 1 << 8,
Button2MotionMask = 1 << 9,
Button3MotionMask = 1 << 10,
Button4MotionMask = 1 << 11,
Button5MotionMask = 1 << 12,
ButtonMotionMask = 1 << 13,
KeymapStateMask = 1 << 14,
ExposureMask = 1 << 15,
VisibilityChangeMask = 1 << 16,
StructureNotifyMask = 1 << 17,
ResizeRedirectMask = 1 << 18,
SubstructureNotifyMask = 1 << 19,
SubstructureRedirectMask = 1 << 20,
FocusChangeMask = 1 << 21,
PropertyChangeMask = 1 << 22,
ColormapChangeMask = 1 << 23,
OwnerGrabButtonMask = 1 << 24
}
private enum SystemTrayMessage {
RequestDock = 0,
BeginMessage = 1,
CancelMessage = 2
}
private enum SystemTrayOrientation {
Horz = 0,
Vert = 1
}
private enum XEventName {
KeyPress = 2,
KeyRelease = 3,
ButtonPress = 4,
ButtonRelease = 5,
MotionNotify = 6,
EnterNotify = 7,
LeaveNotify = 8,
FocusIn = 9,
FocusOut = 10,
KeymapNotify = 11,
Expose = 12,
GraphicsExpose = 13,
NoExpose = 14,
VisibilityNotify = 15,
CreateNotify = 16,
DestroyNotify = 17,
UnmapNotify = 18,
MapNotify = 19,
MapRequest = 20,
ReparentNotify = 21,
ConfigureNotify = 22,
ConfigureRequest = 23,
GravityNotify = 24,
ResizeRequest = 25,
CirculateNotify = 26,
CirculateRequest = 27,
PropertyNotify = 28,
SelectionClear = 29,
SelectionRequest = 30,
SelectionNotify = 31,
ColormapNotify = 32,
ClientMessage = 33,
MappingNotify = 34,
TimerNotify = 100,
LASTEvent
}
private enum XAtom {
Cardinal = 6,
LASTAtom
}
[StructLayout(LayoutKind.Sequential)]
private struct XAnyEvent
{
internal XEventName type;
internal IntPtr serial;
internal bool send_event;
internal IntPtr display;
internal IntPtr window;
}
[StructLayout(LayoutKind.Sequential)]
private struct XPropertyEvent
{
internal XEventName type;
internal IntPtr serial;
internal bool send_event;
internal IntPtr display;
internal IntPtr window;
internal IntPtr atom;
internal IntPtr time;
internal int state;
}
[StructLayout(LayoutKind.Sequential)]
private struct XClientMessageEvent
{
internal XEventName type;
internal IntPtr serial;
internal bool send_event;
internal IntPtr display;
internal IntPtr window;
internal IntPtr message_type;
internal int format;
[StructLayout(LayoutKind.Sequential)]
internal struct DataUnion
{
internal IntPtr ptr1;
internal IntPtr ptr2;
internal IntPtr ptr3;
internal IntPtr ptr4;
internal IntPtr ptr5;
}
internal DataUnion data;
}
}
#pragma warning restore 0169, 0414
| |
namespace ZetaResourceEditor.UI.Main
{
partial class MainForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose( bool disposing )
{
if ( disposing && (components != null) )
{
components.Dispose();
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
this.mainFormMainSplitContainer = new DevExpress.XtraEditors.SplitContainerControl();
this.ProjectFilesControl = new ZetaResourceEditor.UI.Main.LeftTree.ProjectFilesUserControl();
this.GroupFilesControl = new ZetaResourceEditor.UI.Main.RightContent.GroupFilesUserControl();
this.ribbon = new DevExpress.XtraBars.Ribbon.RibbonControl();
this.applicationMenu1 = new DevExpress.XtraBars.Ribbon.ApplicationMenu(this.components);
this.barSubRecentFiles = new DevExpress.XtraBars.BarSubItem();
this.barSubRecentProjects = new DevExpress.XtraBars.BarSubItem();
this.infoButton = new DevExpress.XtraBars.BarButtonItem();
this.buttonExit = new DevExpress.XtraBars.BarButtonItem();
this.buttonOnlineManual = new DevExpress.XtraBars.BarButtonItem();
this.buttonWebsite = new DevExpress.XtraBars.BarButtonItem();
this.buttonOpenResourceFiles = new DevExpress.XtraBars.BarButtonItem();
this.buttonSaveResourceFiles = new DevExpress.XtraBars.BarButtonItem();
this.buttonSaveAllFiles = new DevExpress.XtraBars.BarButtonItem();
this.buttonCloseResourceFiles = new DevExpress.XtraBars.BarButtonItem();
this.buttonCloseAllDocuments = new DevExpress.XtraBars.BarButtonItem();
this.buttonOpenProjectFile = new DevExpress.XtraBars.BarButtonItem();
this.buttonSaveProjectFile = new DevExpress.XtraBars.BarButtonItem();
this.buttonCloseProject = new DevExpress.XtraBars.BarButtonItem();
this.buttonFind = new DevExpress.XtraBars.BarButtonItem();
this.buttonFindNext = new DevExpress.XtraBars.BarButtonItem();
this.buttonTranslateMissingLanguages = new DevExpress.XtraBars.BarButtonItem();
this.buttonAddNewTag = new DevExpress.XtraBars.BarButtonItem();
this.buttonDeleteTag = new DevExpress.XtraBars.BarButtonItem();
this.buttonRenameTag = new DevExpress.XtraBars.BarButtonItem();
this.buttonQuickTranslate = new DevExpress.XtraBars.BarButtonItem();
this.buttonRefresh = new DevExpress.XtraBars.BarButtonItem();
this.buttonOptions = new DevExpress.XtraBars.BarButtonItem();
this.buttonCreateNewProject = new DevExpress.XtraBars.BarButtonItem();
this.buttonAutomaticallyAddFileGroupsToProject = new DevExpress.XtraBars.BarButtonItem();
this.buttonAddFileGroupToProject = new DevExpress.XtraBars.BarButtonItem();
this.buttonRemoveFileGroupFromProject = new DevExpress.XtraBars.BarButtonItem();
this.buttonEditFileGroupSettings = new DevExpress.XtraBars.BarButtonItem();
this.buttonAddFilesToFileGroup = new DevExpress.XtraBars.BarButtonItem();
this.buttonRemoveFileFromGroup = new DevExpress.XtraBars.BarButtonItem();
this.buttonEditProjectSettings = new DevExpress.XtraBars.BarButtonItem();
this.barMdiChildrenListItem1 = new DevExpress.XtraBars.BarMdiChildrenListItem();
this.barMdiChildrenListItem2 = new DevExpress.XtraBars.BarMdiChildrenListItem();
this.barListItem1 = new DevExpress.XtraBars.BarListItem();
this.buttonUpdateAvailable = new DevExpress.XtraBars.BarButtonItem();
this.buttonOpenFileGroupFolder = new DevExpress.XtraBars.BarButtonItem();
this.barStaticItem1 = new DevExpress.XtraBars.BarStaticItem();
this.buttonExport = new DevExpress.XtraBars.BarButtonItem();
this.buttonImport = new DevExpress.XtraBars.BarButtonItem();
this.buttonMoveDown = new DevExpress.XtraBars.BarButtonItem();
this.buttonMoveUp = new DevExpress.XtraBars.BarButtonItem();
this.buttonShowHideProjectPanel = new DevExpress.XtraBars.BarButtonItem();
this.buttonCreateNewFile = new DevExpress.XtraBars.BarButtonItem();
this.buttonCreateNewFiles = new DevExpress.XtraBars.BarButtonItem();
this.resetLayoutButton = new DevExpress.XtraBars.BarButtonItem();
this.buttonAddFromVisualStudio = new DevExpress.XtraBars.BarButtonItem();
this.buttonConfigureLanguageColumns = new DevExpress.XtraBars.BarButtonItem();
this.buttonReplace = new DevExpress.XtraBars.BarButtonItem();
this.ribbonPage1 = new DevExpress.XtraBars.Ribbon.RibbonPage();
this.updateRibbonPageGroup = new DevExpress.XtraBars.Ribbon.RibbonPageGroup();
this.ribbonPageGroup2 = new DevExpress.XtraBars.Ribbon.RibbonPageGroup();
this.ribbonPageGroup10 = new DevExpress.XtraBars.Ribbon.RibbonPageGroup();
this.ribbonPageGroup1 = new DevExpress.XtraBars.Ribbon.RibbonPageGroup();
this.ribbonPageGroup5 = new DevExpress.XtraBars.Ribbon.RibbonPageGroup();
this.ribbonPageGroup3 = new DevExpress.XtraBars.Ribbon.RibbonPageGroup();
this.ribbonPage4 = new DevExpress.XtraBars.Ribbon.RibbonPage();
this.ribbonPageGroup8 = new DevExpress.XtraBars.Ribbon.RibbonPageGroup();
this.ribbonPageGroup9 = new DevExpress.XtraBars.Ribbon.RibbonPageGroup();
this.ribbonPageGroup4 = new DevExpress.XtraBars.Ribbon.RibbonPageGroup();
this.ribbonPage3 = new DevExpress.XtraBars.Ribbon.RibbonPage();
this.ribbonPageGroup7 = new DevExpress.XtraBars.Ribbon.RibbonPageGroup();
this.ribbonPageGroup6 = new DevExpress.XtraBars.Ribbon.RibbonPageGroup();
this.ribbonPageGroup11 = new DevExpress.XtraBars.Ribbon.RibbonPageGroup();
this.repositoryItemHyperLinkEdit1 = new DevExpress.XtraEditors.Repository.RepositoryItemHyperLinkEdit();
this.clientPanel = new ExtendedControlsLibrary.Skinning.CustomPanel.MyPanelControl();
this.updateAvailableCheckerBackgroundWorker = new System.ComponentModel.BackgroundWorker();
this.updateAvailableBlinkTimer = new System.Windows.Forms.Timer(this.components);
this.blinkImageCollection = new DevExpress.Utils.ImageCollection(this.components);
((System.ComponentModel.ISupportInitialize)(this.mainFormMainSplitContainer)).BeginInit();
this.mainFormMainSplitContainer.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.ribbon)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.applicationMenu1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.repositoryItemHyperLinkEdit1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.clientPanel)).BeginInit();
this.clientPanel.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.blinkImageCollection)).BeginInit();
this.SuspendLayout();
//
// mainFormMainSplitContainer
//
this.mainFormMainSplitContainer.CollapsePanel = DevExpress.XtraEditors.SplitCollapsePanel.Panel1;
this.mainFormMainSplitContainer.Dock = System.Windows.Forms.DockStyle.Fill;
this.mainFormMainSplitContainer.Location = new System.Drawing.Point(0, 0);
this.mainFormMainSplitContainer.Name = "mainFormMainSplitContainer";
this.mainFormMainSplitContainer.Panel1.Controls.Add(this.ProjectFilesControl);
this.mainFormMainSplitContainer.Panel1.MinSize = 250;
this.mainFormMainSplitContainer.Panel1.Text = "Panel1";
this.mainFormMainSplitContainer.Panel2.Controls.Add(this.GroupFilesControl);
this.mainFormMainSplitContainer.Size = new System.Drawing.Size(685, 408);
this.mainFormMainSplitContainer.SplitterPosition = 200;
this.mainFormMainSplitContainer.TabIndex = 0;
this.mainFormMainSplitContainer.Text = "splitContainerControl1";
//
// projectFilesUserControl
//
this.ProjectFilesControl.Appearance.Font = new System.Drawing.Font("Segoe UI", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
this.ProjectFilesControl.Appearance.Options.UseFont = true;
this.ProjectFilesControl.Dock = System.Windows.Forms.DockStyle.Fill;
this.ProjectFilesControl.Location = new System.Drawing.Point(0, 0);
this.ProjectFilesControl.Name = "ProjectFilesControl";
this.ProjectFilesControl.Size = new System.Drawing.Size(250, 408);
this.ProjectFilesControl.TabIndex = 0;
//
// groupFilesControl
//
this.GroupFilesControl.Appearance.Font = new System.Drawing.Font("Segoe UI", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
this.GroupFilesControl.Appearance.Options.UseFont = true;
this.GroupFilesControl.Dock = System.Windows.Forms.DockStyle.Fill;
this.GroupFilesControl.Location = new System.Drawing.Point(0, 0);
this.GroupFilesControl.Name = "GroupFilesControl";
this.GroupFilesControl.Size = new System.Drawing.Size(430, 408);
this.GroupFilesControl.TabIndex = 0;
//
// ribbon
//
this.ribbon.ApplicationButtonDropDownControl = this.applicationMenu1;
this.ribbon.ApplicationButtonText = null;
this.ribbon.ExpandCollapseItem.Id = 0;
this.ribbon.Items.AddRange(new DevExpress.XtraBars.BarItem[] {
this.ribbon.ExpandCollapseItem,
this.infoButton,
this.buttonExit,
this.buttonOnlineManual,
this.buttonWebsite,
this.buttonOpenResourceFiles,
this.buttonSaveResourceFiles,
this.buttonSaveAllFiles,
this.buttonCloseResourceFiles,
this.buttonCloseAllDocuments,
this.buttonOpenProjectFile,
this.buttonSaveProjectFile,
this.buttonCloseProject,
this.buttonFind,
this.buttonFindNext,
this.buttonTranslateMissingLanguages,
this.buttonAddNewTag,
this.buttonDeleteTag,
this.buttonRenameTag,
this.buttonQuickTranslate,
this.buttonRefresh,
this.buttonOptions,
this.buttonCreateNewProject,
this.buttonAutomaticallyAddFileGroupsToProject,
this.buttonAddFileGroupToProject,
this.buttonRemoveFileGroupFromProject,
this.buttonEditFileGroupSettings,
this.buttonAddFilesToFileGroup,
this.buttonRemoveFileFromGroup,
this.buttonEditProjectSettings,
this.barMdiChildrenListItem1,
this.barMdiChildrenListItem2,
this.barListItem1,
this.buttonUpdateAvailable,
this.buttonOpenFileGroupFolder,
this.barStaticItem1,
this.buttonExport,
this.buttonImport,
this.barSubRecentFiles,
this.barSubRecentProjects,
this.buttonMoveDown,
this.buttonMoveUp,
this.buttonShowHideProjectPanel,
this.buttonCreateNewFile,
this.buttonCreateNewFiles,
this.resetLayoutButton,
this.buttonAddFromVisualStudio,
this.buttonConfigureLanguageColumns,
this.buttonReplace});
this.ribbon.ItemsVertAlign = DevExpress.Utils.VertAlignment.Top;
this.ribbon.Location = new System.Drawing.Point(0, 0);
this.ribbon.MaxItemId = 75;
this.ribbon.Name = "ribbon";
this.ribbon.Pages.AddRange(new DevExpress.XtraBars.Ribbon.RibbonPage[] {
this.ribbonPage1,
this.ribbonPage4,
this.ribbonPage3});
this.ribbon.RepositoryItems.AddRange(new DevExpress.XtraEditors.Repository.RepositoryItem[] {
this.repositoryItemHyperLinkEdit1});
this.ribbon.RibbonStyle = DevExpress.XtraBars.Ribbon.RibbonControlStyle.Office2013;
this.ribbon.Size = new System.Drawing.Size(685, 143);
//
// applicationMenu1
//
this.applicationMenu1.ItemLinks.Add(this.barSubRecentFiles);
this.applicationMenu1.ItemLinks.Add(this.barSubRecentProjects);
this.applicationMenu1.Name = "applicationMenu1";
this.applicationMenu1.Ribbon = this.ribbon;
this.applicationMenu1.BeforePopup += new System.ComponentModel.CancelEventHandler(this.applicationMenu1_BeforePopup);
//
// barSubRecentFiles
//
this.barSubRecentFiles.Caption = "Recent resource files";
this.barSubRecentFiles.Description = "Loads recently opened resource files";
this.barSubRecentFiles.Id = 50;
this.barSubRecentFiles.ImageOptions.LargeImage = ((System.Drawing.Image)(resources.GetObject("barSubRecentFiles.ImageOptions.LargeImage")));
this.barSubRecentFiles.Name = "barSubRecentFiles";
//
// barSubRecentProjects
//
this.barSubRecentProjects.Caption = "Recent projects";
this.barSubRecentProjects.Description = "Loads a recently opened project";
this.barSubRecentProjects.Id = 52;
this.barSubRecentProjects.ImageOptions.LargeImage = ((System.Drawing.Image)(resources.GetObject("barSubRecentProjects.ImageOptions.LargeImage")));
this.barSubRecentProjects.Name = "barSubRecentProjects";
//
// infoButton
//
this.infoButton.Caption = "Info";
this.infoButton.Description = "Displays application and version information";
this.infoButton.Id = 0;
this.infoButton.ImageOptions.Image = ((System.Drawing.Image)(resources.GetObject("infoButton.ImageOptions.Image")));
this.infoButton.ImageOptions.LargeImage = ((System.Drawing.Image)(resources.GetObject("infoButton.ImageOptions.LargeImage")));
this.infoButton.Name = "infoButton";
this.infoButton.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.aboutZetaResxEditorToolStripMenuItem_Click);
//
// buttonExit
//
this.buttonExit.Caption = "Exit";
this.buttonExit.Description = "Exits the application";
this.buttonExit.Id = 1;
this.buttonExit.Name = "buttonExit";
this.buttonExit.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.buttonExit_ItemClick);
//
// buttonOnlineManual
//
this.buttonOnlineManual.Caption = "Online manual";
this.buttonOnlineManual.Hint = "Shows the online manual";
this.buttonOnlineManual.Id = 2;
this.buttonOnlineManual.ImageOptions.LargeImage = ((System.Drawing.Image)(resources.GetObject("buttonOnlineManual.ImageOptions.LargeImage")));
this.buttonOnlineManual.ItemShortcut = new DevExpress.XtraBars.BarShortcut(System.Windows.Forms.Keys.F1);
this.buttonOnlineManual.Name = "buttonOnlineManual";
this.buttonOnlineManual.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.onlineManualToolStripMenuItem_Click);
//
// buttonWebsite
//
this.buttonWebsite.Caption = "Website";
this.buttonWebsite.Id = 3;
this.buttonWebsite.ImageOptions.LargeImage = ((System.Drawing.Image)(resources.GetObject("buttonWebsite.ImageOptions.LargeImage")));
this.buttonWebsite.Name = "buttonWebsite";
this.buttonWebsite.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.visitVendorsWebsiteToolStripMenuItem_Click);
//
// buttonOpenResourceFiles
//
this.buttonOpenResourceFiles.Caption = "Open resource files";
this.buttonOpenResourceFiles.Hint = "Opens existing resource files";
this.buttonOpenResourceFiles.Id = 5;
this.buttonOpenResourceFiles.ImageOptions.Image = ((System.Drawing.Image)(resources.GetObject("buttonOpenResourceFiles.ImageOptions.Image")));
this.buttonOpenResourceFiles.ImageOptions.LargeImage = ((System.Drawing.Image)(resources.GetObject("buttonOpenResourceFiles.ImageOptions.LargeImage")));
this.buttonOpenResourceFiles.ItemShortcut = new DevExpress.XtraBars.BarShortcut((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.O));
this.buttonOpenResourceFiles.Name = "buttonOpenResourceFiles";
this.buttonOpenResourceFiles.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.openToolStripMenuItem_Click);
//
// buttonSaveResourceFiles
//
this.buttonSaveResourceFiles.Caption = "Save files";
this.buttonSaveResourceFiles.Hint = "Saves the currently opened resource file group";
this.buttonSaveResourceFiles.Id = 6;
this.buttonSaveResourceFiles.ImageOptions.Image = ((System.Drawing.Image)(resources.GetObject("buttonSaveResourceFiles.ImageOptions.Image")));
this.buttonSaveResourceFiles.ImageOptions.LargeImage = ((System.Drawing.Image)(resources.GetObject("buttonSaveResourceFiles.ImageOptions.LargeImage")));
this.buttonSaveResourceFiles.ItemShortcut = new DevExpress.XtraBars.BarShortcut((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.S));
this.buttonSaveResourceFiles.Name = "buttonSaveResourceFiles";
this.buttonSaveResourceFiles.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.saveToolStripMenuItem_Click);
//
// buttonSaveAllFiles
//
this.buttonSaveAllFiles.Caption = "Save all files";
this.buttonSaveAllFiles.Hint = "Saves all modified resource files and the project itself";
this.buttonSaveAllFiles.Id = 7;
this.buttonSaveAllFiles.ImageOptions.Image = ((System.Drawing.Image)(resources.GetObject("buttonSaveAllFiles.ImageOptions.Image")));
this.buttonSaveAllFiles.ImageOptions.LargeImage = ((System.Drawing.Image)(resources.GetObject("buttonSaveAllFiles.ImageOptions.LargeImage")));
this.buttonSaveAllFiles.ItemShortcut = new DevExpress.XtraBars.BarShortcut(((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Shift)
| System.Windows.Forms.Keys.S));
this.buttonSaveAllFiles.Name = "buttonSaveAllFiles";
this.buttonSaveAllFiles.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.saveAllToolStripButton_Click);
//
// buttonCloseResourceFiles
//
this.buttonCloseResourceFiles.Caption = "Close resource files";
this.buttonCloseResourceFiles.Hint = "Close the currently open resource file data grid";
this.buttonCloseResourceFiles.Id = 8;
this.buttonCloseResourceFiles.ImageOptions.Image = ((System.Drawing.Image)(resources.GetObject("buttonCloseResourceFiles.ImageOptions.Image")));
this.buttonCloseResourceFiles.ImageOptions.LargeImage = ((System.Drawing.Image)(resources.GetObject("buttonCloseResourceFiles.ImageOptions.LargeImage")));
this.buttonCloseResourceFiles.ItemShortcut = new DevExpress.XtraBars.BarShortcut((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.F4));
this.buttonCloseResourceFiles.Name = "buttonCloseResourceFiles";
this.buttonCloseResourceFiles.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.closeToolStripMenuItem_Click);
//
// buttonCloseAllDocuments
//
this.buttonCloseAllDocuments.Caption = "Close all documents";
this.buttonCloseAllDocuments.Hint = "Closes all open resource file group editor windows";
this.buttonCloseAllDocuments.Id = 9;
this.buttonCloseAllDocuments.ImageOptions.Image = ((System.Drawing.Image)(resources.GetObject("buttonCloseAllDocuments.ImageOptions.Image")));
this.buttonCloseAllDocuments.ImageOptions.LargeImage = ((System.Drawing.Image)(resources.GetObject("buttonCloseAllDocuments.ImageOptions.LargeImage")));
this.buttonCloseAllDocuments.ItemShortcut = new DevExpress.XtraBars.BarShortcut(((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Shift)
| System.Windows.Forms.Keys.W));
this.buttonCloseAllDocuments.Name = "buttonCloseAllDocuments";
this.buttonCloseAllDocuments.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.closeAllDocumentsToolStripMenuItem_Click);
//
// buttonOpenProjectFile
//
this.buttonOpenProjectFile.Caption = "Open project file";
this.buttonOpenProjectFile.Hint = "Opens an existing project file";
this.buttonOpenProjectFile.Id = 10;
this.buttonOpenProjectFile.ImageOptions.Image = ((System.Drawing.Image)(resources.GetObject("buttonOpenProjectFile.ImageOptions.Image")));
this.buttonOpenProjectFile.ImageOptions.LargeImage = ((System.Drawing.Image)(resources.GetObject("buttonOpenProjectFile.ImageOptions.LargeImage")));
this.buttonOpenProjectFile.ItemShortcut = new DevExpress.XtraBars.BarShortcut(((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Shift)
| System.Windows.Forms.Keys.O));
this.buttonOpenProjectFile.Name = "buttonOpenProjectFile";
this.buttonOpenProjectFile.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.openProjectFileToolStripMenuItem_Click);
//
// buttonSaveProjectFile
//
this.buttonSaveProjectFile.Caption = "Save project file";
this.buttonSaveProjectFile.Id = 11;
this.buttonSaveProjectFile.ImageOptions.Image = ((System.Drawing.Image)(resources.GetObject("buttonSaveProjectFile.ImageOptions.Image")));
this.buttonSaveProjectFile.ImageOptions.LargeImage = ((System.Drawing.Image)(resources.GetObject("buttonSaveProjectFile.ImageOptions.LargeImage")));
this.buttonSaveProjectFile.Name = "buttonSaveProjectFile";
this.buttonSaveProjectFile.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.saveProjectFileToolStripMenuItem_Click);
//
// buttonCloseProject
//
this.buttonCloseProject.Caption = "Close project";
this.buttonCloseProject.Id = 12;
this.buttonCloseProject.ImageOptions.Image = ((System.Drawing.Image)(resources.GetObject("buttonCloseProject.ImageOptions.Image")));
this.buttonCloseProject.ImageOptions.LargeImage = ((System.Drawing.Image)(resources.GetObject("buttonCloseProject.ImageOptions.LargeImage")));
this.buttonCloseProject.Name = "buttonCloseProject";
this.buttonCloseProject.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.closeProjectFileToolStripMenuItem_Click);
//
// buttonFind
//
this.buttonFind.Caption = "Find";
this.buttonFind.Hint = "Searches for text in the currently opened resource file group data grid";
this.buttonFind.Id = 13;
this.buttonFind.ImageOptions.Image = ((System.Drawing.Image)(resources.GetObject("buttonFind.ImageOptions.Image")));
this.buttonFind.ImageOptions.LargeImage = ((System.Drawing.Image)(resources.GetObject("buttonFind.ImageOptions.LargeImage")));
this.buttonFind.ItemShortcut = new DevExpress.XtraBars.BarShortcut((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.F));
this.buttonFind.Name = "buttonFind";
this.buttonFind.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.findToolStripMenuItem_Click);
//
// buttonFindNext
//
this.buttonFindNext.Caption = "Find next";
this.buttonFindNext.Hint = "Continues a previously started search";
this.buttonFindNext.Id = 14;
this.buttonFindNext.ImageOptions.Image = ((System.Drawing.Image)(resources.GetObject("buttonFindNext.ImageOptions.Image")));
this.buttonFindNext.ImageOptions.LargeImage = ((System.Drawing.Image)(resources.GetObject("buttonFindNext.ImageOptions.LargeImage")));
this.buttonFindNext.ItemShortcut = new DevExpress.XtraBars.BarShortcut(System.Windows.Forms.Keys.F3);
this.buttonFindNext.Name = "buttonFindNext";
this.buttonFindNext.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.findNextToolStripMenuItem_Click);
//
// buttonTranslateMissingLanguages
//
this.buttonTranslateMissingLanguages.Caption = "Translate missing languages";
this.buttonTranslateMissingLanguages.Id = 15;
this.buttonTranslateMissingLanguages.ImageOptions.Image = ((System.Drawing.Image)(resources.GetObject("buttonTranslateMissingLanguages.ImageOptions.Image")));
this.buttonTranslateMissingLanguages.ImageOptions.LargeImage = ((System.Drawing.Image)(resources.GetObject("buttonTranslateMissingLanguages.ImageOptions.LargeImage")));
this.buttonTranslateMissingLanguages.Name = "buttonTranslateMissingLanguages";
this.buttonTranslateMissingLanguages.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.translateMissingLanguagesToolStripMenuItem_Click);
//
// buttonAddNewTag
//
this.buttonAddNewTag.Caption = "Add new tag";
this.buttonAddNewTag.Hint = "Adds a new tag to the currently open resource file group data grid";
this.buttonAddNewTag.Id = 18;
this.buttonAddNewTag.ImageOptions.LargeImage = ((System.Drawing.Image)(resources.GetObject("buttonAddNewTag.ImageOptions.LargeImage")));
this.buttonAddNewTag.ItemShortcut = new DevExpress.XtraBars.BarShortcut((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.N));
this.buttonAddNewTag.Name = "buttonAddNewTag";
this.buttonAddNewTag.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.addTagToolStripMenuItem_Click);
//
// buttonDeleteTag
//
this.buttonDeleteTag.Caption = "Delete tag";
this.buttonDeleteTag.Hint = "Deletes the currently selected row";
this.buttonDeleteTag.Id = 19;
this.buttonDeleteTag.ImageOptions.Image = ((System.Drawing.Image)(resources.GetObject("buttonDeleteTag.ImageOptions.Image")));
this.buttonDeleteTag.ImageOptions.LargeImage = ((System.Drawing.Image)(resources.GetObject("buttonDeleteTag.ImageOptions.LargeImage")));
this.buttonDeleteTag.ItemShortcut = new DevExpress.XtraBars.BarShortcut((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Delete));
this.buttonDeleteTag.Name = "buttonDeleteTag";
this.buttonDeleteTag.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.deleteTagToolStripMenuItem_Click);
//
// buttonRenameTag
//
this.buttonRenameTag.Caption = "Rename tag";
this.buttonRenameTag.Hint = "Renames the currently selected tag";
this.buttonRenameTag.Id = 20;
this.buttonRenameTag.ImageOptions.Image = ((System.Drawing.Image)(resources.GetObject("buttonRenameTag.ImageOptions.Image")));
this.buttonRenameTag.ImageOptions.LargeImage = ((System.Drawing.Image)(resources.GetObject("buttonRenameTag.ImageOptions.LargeImage")));
this.buttonRenameTag.ItemShortcut = new DevExpress.XtraBars.BarShortcut((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.R));
this.buttonRenameTag.Name = "buttonRenameTag";
this.buttonRenameTag.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.renameTagToolStripMenuItem_Click);
//
// buttonQuickTranslate
//
this.buttonQuickTranslate.Caption = "Quick translate";
this.buttonQuickTranslate.Hint = "Opens the Quick translate window";
this.buttonQuickTranslate.Id = 21;
this.buttonQuickTranslate.ImageOptions.Image = ((System.Drawing.Image)(resources.GetObject("buttonQuickTranslate.ImageOptions.Image")));
this.buttonQuickTranslate.ImageOptions.LargeImage = ((System.Drawing.Image)(resources.GetObject("buttonQuickTranslate.ImageOptions.LargeImage")));
this.buttonQuickTranslate.ItemShortcut = new DevExpress.XtraBars.BarShortcut(System.Windows.Forms.Keys.F9);
this.buttonQuickTranslate.Name = "buttonQuickTranslate";
this.buttonQuickTranslate.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.quickTranslationToolStripMenuItem_Click);
//
// buttonRefresh
//
this.buttonRefresh.Caption = "Refresh file list";
this.buttonRefresh.Hint = "Refreshes the project file list";
this.buttonRefresh.Id = 22;
this.buttonRefresh.ImageOptions.Image = ((System.Drawing.Image)(resources.GetObject("buttonRefresh.ImageOptions.Image")));
this.buttonRefresh.ImageOptions.LargeImage = ((System.Drawing.Image)(resources.GetObject("buttonRefresh.ImageOptions.LargeImage")));
this.buttonRefresh.ImageOptions.LargeImageIndex = 1;
this.buttonRefresh.ItemShortcut = new DevExpress.XtraBars.BarShortcut(System.Windows.Forms.Keys.F5);
this.buttonRefresh.Name = "buttonRefresh";
this.buttonRefresh.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.refreshProjectFilesListToolStripMenuItem_Click);
//
// buttonOptions
//
this.buttonOptions.Caption = "Options";
this.buttonOptions.Id = 23;
this.buttonOptions.ImageOptions.LargeImage = ((System.Drawing.Image)(resources.GetObject("buttonOptions.ImageOptions.LargeImage")));
this.buttonOptions.ItemShortcut = new DevExpress.XtraBars.BarShortcut((System.Windows.Forms.Keys.Alt | System.Windows.Forms.Keys.F7));
this.buttonOptions.Name = "buttonOptions";
this.buttonOptions.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.optionsToolStripMenuItem1_Click);
//
// buttonCreateNewProject
//
this.buttonCreateNewProject.Caption = "Create new project";
this.buttonCreateNewProject.Hint = "Creates a new project";
this.buttonCreateNewProject.Id = 24;
this.buttonCreateNewProject.ImageOptions.Image = ((System.Drawing.Image)(resources.GetObject("buttonCreateNewProject.ImageOptions.Image")));
this.buttonCreateNewProject.ImageOptions.LargeImage = ((System.Drawing.Image)(resources.GetObject("buttonCreateNewProject.ImageOptions.LargeImage")));
this.buttonCreateNewProject.ItemShortcut = new DevExpress.XtraBars.BarShortcut(((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Shift)
| System.Windows.Forms.Keys.N));
this.buttonCreateNewProject.Name = "buttonCreateNewProject";
this.buttonCreateNewProject.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.createNewProjectToolStripMenuItem_Click);
//
// buttonAutomaticallyAddFileGroupsToProject
//
this.buttonAutomaticallyAddFileGroupsToProject.Caption = "Automatically add multiple files";
this.buttonAutomaticallyAddFileGroupsToProject.Id = 25;
this.buttonAutomaticallyAddFileGroupsToProject.ImageOptions.LargeImage = ((System.Drawing.Image)(resources.GetObject("buttonAutomaticallyAddFileGroupsToProject.ImageOptions.LargeImage")));
this.buttonAutomaticallyAddFileGroupsToProject.Name = "buttonAutomaticallyAddFileGroupsToProject";
this.buttonAutomaticallyAddFileGroupsToProject.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.automaticallyAddMultipleFileGroupsToolStripMenuItem_Click);
//
// buttonAddFileGroupToProject
//
this.buttonAddFileGroupToProject.Caption = "Add file group to project";
this.buttonAddFileGroupToProject.Id = 26;
this.buttonAddFileGroupToProject.ImageOptions.Image = ((System.Drawing.Image)(resources.GetObject("buttonAddFileGroupToProject.ImageOptions.Image")));
this.buttonAddFileGroupToProject.ImageOptions.LargeImage = ((System.Drawing.Image)(resources.GetObject("buttonAddFileGroupToProject.ImageOptions.LargeImage")));
this.buttonAddFileGroupToProject.Name = "buttonAddFileGroupToProject";
this.buttonAddFileGroupToProject.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.addResourceFilesToProjectToolStripMenuItem_Click);
//
// buttonRemoveFileGroupFromProject
//
this.buttonRemoveFileGroupFromProject.Caption = "Remove file group from project";
this.buttonRemoveFileGroupFromProject.Id = 27;
this.buttonRemoveFileGroupFromProject.ImageOptions.Image = ((System.Drawing.Image)(resources.GetObject("buttonRemoveFileGroupFromProject.ImageOptions.Image")));
this.buttonRemoveFileGroupFromProject.ImageOptions.LargeImage = ((System.Drawing.Image)(resources.GetObject("buttonRemoveFileGroupFromProject.ImageOptions.LargeImage")));
this.buttonRemoveFileGroupFromProject.Name = "buttonRemoveFileGroupFromProject";
this.buttonRemoveFileGroupFromProject.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.removeResourceFilesFromProjectToolStripMenuItem_Click);
//
// buttonEditFileGroupSettings
//
this.buttonEditFileGroupSettings.Caption = "Edit file group settings";
this.buttonEditFileGroupSettings.Id = 28;
this.buttonEditFileGroupSettings.ImageOptions.Image = ((System.Drawing.Image)(resources.GetObject("buttonEditFileGroupSettings.ImageOptions.Image")));
this.buttonEditFileGroupSettings.ImageOptions.LargeImage = ((System.Drawing.Image)(resources.GetObject("buttonEditFileGroupSettings.ImageOptions.LargeImage")));
this.buttonEditFileGroupSettings.Name = "buttonEditFileGroupSettings";
this.buttonEditFileGroupSettings.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.editResourceFilesSettingsToolStripMenuItem_Click);
//
// buttonAddFilesToFileGroup
//
this.buttonAddFilesToFileGroup.Caption = "Add files to file group";
this.buttonAddFilesToFileGroup.Id = 29;
this.buttonAddFilesToFileGroup.ImageOptions.Image = ((System.Drawing.Image)(resources.GetObject("buttonAddFilesToFileGroup.ImageOptions.Image")));
this.buttonAddFilesToFileGroup.ImageOptions.LargeImage = ((System.Drawing.Image)(resources.GetObject("buttonAddFilesToFileGroup.ImageOptions.LargeImage")));
this.buttonAddFilesToFileGroup.Name = "buttonAddFilesToFileGroup";
this.buttonAddFilesToFileGroup.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.addFilesToFileGroupToolStripMenuItem_Click);
//
// buttonRemoveFileFromGroup
//
this.buttonRemoveFileFromGroup.Caption = "Remove file from group";
this.buttonRemoveFileFromGroup.Id = 30;
this.buttonRemoveFileFromGroup.ImageOptions.Image = ((System.Drawing.Image)(resources.GetObject("buttonRemoveFileFromGroup.ImageOptions.Image")));
this.buttonRemoveFileFromGroup.ImageOptions.LargeImage = ((System.Drawing.Image)(resources.GetObject("buttonRemoveFileFromGroup.ImageOptions.LargeImage")));
this.buttonRemoveFileFromGroup.Name = "buttonRemoveFileFromGroup";
this.buttonRemoveFileFromGroup.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.removeFileFromGroupToolStripMenuItem_Click);
//
// buttonEditProjectSettings
//
this.buttonEditProjectSettings.Caption = "Edit project settings";
this.buttonEditProjectSettings.Id = 31;
this.buttonEditProjectSettings.ImageOptions.Image = ((System.Drawing.Image)(resources.GetObject("buttonEditProjectSettings.ImageOptions.Image")));
this.buttonEditProjectSettings.ImageOptions.LargeImage = ((System.Drawing.Image)(resources.GetObject("buttonEditProjectSettings.ImageOptions.LargeImage")));
this.buttonEditProjectSettings.Name = "buttonEditProjectSettings";
this.buttonEditProjectSettings.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.editProjectSettingsToolStripMenuItem_Click);
//
// barMdiChildrenListItem1
//
this.barMdiChildrenListItem1.Caption = "Recent projects";
this.barMdiChildrenListItem1.Id = 32;
this.barMdiChildrenListItem1.ImageOptions.LargeImageIndex = 35;
this.barMdiChildrenListItem1.Name = "barMdiChildrenListItem1";
//
// barMdiChildrenListItem2
//
this.barMdiChildrenListItem2.Caption = "Recent files";
this.barMdiChildrenListItem2.Id = 33;
this.barMdiChildrenListItem2.ImageOptions.LargeImageIndex = 36;
this.barMdiChildrenListItem2.Name = "barMdiChildrenListItem2";
//
// barListItem1
//
this.barListItem1.Caption = "barListItem1";
this.barListItem1.Id = 34;
this.barListItem1.Name = "barListItem1";
//
// buttonUpdateAvailable
//
this.buttonUpdateAvailable.Caption = "An update is available!";
this.buttonUpdateAvailable.Id = 37;
this.buttonUpdateAvailable.ImageOptions.Image = ((System.Drawing.Image)(resources.GetObject("buttonUpdateAvailable.ImageOptions.Image")));
this.buttonUpdateAvailable.ImageOptions.LargeImage = ((System.Drawing.Image)(resources.GetObject("buttonUpdateAvailable.ImageOptions.LargeImage")));
this.buttonUpdateAvailable.Name = "buttonUpdateAvailable";
this.buttonUpdateAvailable.RibbonStyle = DevExpress.XtraBars.Ribbon.RibbonItemStyles.Large;
this.buttonUpdateAvailable.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.buttonUpdateAvailable_ItemClick);
//
// buttonOpenFileGroupFolder
//
this.buttonOpenFileGroupFolder.Caption = "Open folder";
this.buttonOpenFileGroupFolder.Id = 40;
this.buttonOpenFileGroupFolder.ImageOptions.LargeImage = ((System.Drawing.Image)(resources.GetObject("buttonOpenFileGroupFolder.ImageOptions.LargeImage")));
this.buttonOpenFileGroupFolder.Name = "buttonOpenFileGroupFolder";
this.buttonOpenFileGroupFolder.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.openFolderOfCurrentResourceFileToolStripMenuItem_Click);
//
// barStaticItem1
//
this.barStaticItem1.Caption = "Test Management Software - For Test Cases and Test Plan Templates";
this.barStaticItem1.Id = 44;
this.barStaticItem1.ItemAppearance.Normal.Font = new System.Drawing.Font("Segoe UI", 13F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Underline))), System.Drawing.GraphicsUnit.Pixel);
this.barStaticItem1.ItemAppearance.Normal.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(204)))));
this.barStaticItem1.ItemAppearance.Normal.Options.UseFont = true;
this.barStaticItem1.ItemAppearance.Normal.Options.UseForeColor = true;
this.barStaticItem1.ItemClickFireMode = DevExpress.XtraBars.BarItemEventFireMode.Immediate;
this.barStaticItem1.Name = "barStaticItem1";
this.barStaticItem1.Tag = "http://www.zeta-test.com/";
this.barStaticItem1.TextAlignment = System.Drawing.StringAlignment.Near;
this.barStaticItem1.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.toolStripStatusLabel1_Click);
//
// buttonExport
//
this.buttonExport.Caption = "Export to Microsoft Excel";
this.buttonExport.Id = 48;
this.buttonExport.ImageOptions.Image = ((System.Drawing.Image)(resources.GetObject("buttonExport.ImageOptions.Image")));
this.buttonExport.ImageOptions.LargeImage = ((System.Drawing.Image)(resources.GetObject("buttonExport.ImageOptions.LargeImage")));
this.buttonExport.Name = "buttonExport";
this.buttonExport.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.buttonExport_ItemClick);
//
// buttonImport
//
this.buttonImport.Caption = "Import from Microsoft Excel";
this.buttonImport.Id = 49;
this.buttonImport.ImageOptions.Image = ((System.Drawing.Image)(resources.GetObject("buttonImport.ImageOptions.Image")));
this.buttonImport.ImageOptions.LargeImage = ((System.Drawing.Image)(resources.GetObject("buttonImport.ImageOptions.LargeImage")));
this.buttonImport.Name = "buttonImport";
this.buttonImport.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.buttonImport_ItemClick);
//
// buttonMoveDown
//
this.buttonMoveDown.Caption = "Move down";
this.buttonMoveDown.Hint = "Move the selected item in the project files tree down by one";
this.buttonMoveDown.Id = 53;
this.buttonMoveDown.ImageOptions.Image = ((System.Drawing.Image)(resources.GetObject("buttonMoveDown.ImageOptions.Image")));
this.buttonMoveDown.ImageOptions.LargeImage = ((System.Drawing.Image)(resources.GetObject("buttonMoveDown.ImageOptions.LargeImage")));
this.buttonMoveDown.ItemShortcut = new DevExpress.XtraBars.BarShortcut((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Down));
this.buttonMoveDown.Name = "buttonMoveDown";
this.buttonMoveDown.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.buttonMoveDown_ItemClick);
//
// buttonMoveUp
//
this.buttonMoveUp.Caption = "Move up";
this.buttonMoveUp.Hint = "Move the selected item in the project files tree up by one";
this.buttonMoveUp.Id = 54;
this.buttonMoveUp.ImageOptions.Image = ((System.Drawing.Image)(resources.GetObject("buttonMoveUp.ImageOptions.Image")));
this.buttonMoveUp.ImageOptions.LargeImage = ((System.Drawing.Image)(resources.GetObject("buttonMoveUp.ImageOptions.LargeImage")));
this.buttonMoveUp.ItemShortcut = new DevExpress.XtraBars.BarShortcut((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Up));
this.buttonMoveUp.Name = "buttonMoveUp";
this.buttonMoveUp.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.buttonMoveUp_ItemClick);
//
// buttonShowHideProjectPanel
//
this.buttonShowHideProjectPanel.ButtonStyle = DevExpress.XtraBars.BarButtonStyle.Check;
this.buttonShowHideProjectPanel.Caption = "Show project panel";
this.buttonShowHideProjectPanel.Id = 55;
this.buttonShowHideProjectPanel.ImageOptions.Image = ((System.Drawing.Image)(resources.GetObject("buttonShowHideProjectPanel.ImageOptions.Image")));
this.buttonShowHideProjectPanel.ImageOptions.LargeImage = ((System.Drawing.Image)(resources.GetObject("buttonShowHideProjectPanel.ImageOptions.LargeImage")));
this.buttonShowHideProjectPanel.Name = "buttonShowHideProjectPanel";
this.buttonShowHideProjectPanel.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.buttonShowHideProjectPanel_ItemClick);
//
// buttonCreateNewFile
//
this.buttonCreateNewFile.Caption = "Create new file for language";
this.buttonCreateNewFile.Id = 56;
this.buttonCreateNewFile.ImageOptions.Image = ((System.Drawing.Image)(resources.GetObject("buttonCreateNewFile.ImageOptions.Image")));
this.buttonCreateNewFile.ImageOptions.LargeImage = ((System.Drawing.Image)(resources.GetObject("buttonCreateNewFile.ImageOptions.LargeImage")));
this.buttonCreateNewFile.Name = "buttonCreateNewFile";
this.buttonCreateNewFile.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.buttonCreateNewFile_ItemClick);
//
// buttonCreateNewFiles
//
this.buttonCreateNewFiles.Caption = "Create new files for language";
this.buttonCreateNewFiles.Id = 57;
this.buttonCreateNewFiles.ImageOptions.LargeImage = ((System.Drawing.Image)(resources.GetObject("buttonCreateNewFiles.ImageOptions.LargeImage")));
this.buttonCreateNewFiles.Name = "buttonCreateNewFiles";
this.buttonCreateNewFiles.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.buttonCreateNewFiles_ItemClick);
//
// resetLayoutButton
//
this.resetLayoutButton.Caption = "Reset layout";
this.resetLayoutButton.Id = 59;
this.resetLayoutButton.ImageOptions.Image = ((System.Drawing.Image)(resources.GetObject("resetLayoutButton.ImageOptions.Image")));
this.resetLayoutButton.ImageOptions.LargeImage = ((System.Drawing.Image)(resources.GetObject("resetLayoutButton.ImageOptions.LargeImage")));
this.resetLayoutButton.Name = "resetLayoutButton";
this.resetLayoutButton.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.resetLayoutButton_ItemClick);
//
// buttonAddFromVisualStudio
//
this.buttonAddFromVisualStudio.Caption = "Automatically add from Visual Studio solution";
this.buttonAddFromVisualStudio.Id = 60;
this.buttonAddFromVisualStudio.ImageOptions.Image = ((System.Drawing.Image)(resources.GetObject("buttonAddFromVisualStudio.ImageOptions.Image")));
this.buttonAddFromVisualStudio.ImageOptions.LargeImage = ((System.Drawing.Image)(resources.GetObject("buttonAddFromVisualStudio.ImageOptions.LargeImage")));
this.buttonAddFromVisualStudio.Name = "buttonAddFromVisualStudio";
this.buttonAddFromVisualStudio.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.buttonAddFromVisualStudio_ItemClick);
//
// buttonConfigureLanguageColumns
//
this.buttonConfigureLanguageColumns.Caption = "Configure language columns";
this.buttonConfigureLanguageColumns.Id = 63;
this.buttonConfigureLanguageColumns.ImageOptions.Image = ((System.Drawing.Image)(resources.GetObject("buttonConfigureLanguageColumns.ImageOptions.Image")));
this.buttonConfigureLanguageColumns.ImageOptions.LargeImage = ((System.Drawing.Image)(resources.GetObject("buttonConfigureLanguageColumns.ImageOptions.LargeImage")));
this.buttonConfigureLanguageColumns.Name = "buttonConfigureLanguageColumns";
this.buttonConfigureLanguageColumns.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.buttonConfigureLanguageColumns_ItemClick);
//
// buttonReplace
//
this.buttonReplace.Caption = "Replace";
this.buttonReplace.Id = 68;
this.buttonReplace.ImageOptions.Image = ((System.Drawing.Image)(resources.GetObject("buttonReplace.ImageOptions.Image")));
this.buttonReplace.ImageOptions.LargeImage = ((System.Drawing.Image)(resources.GetObject("buttonReplace.ImageOptions.LargeImage")));
this.buttonReplace.ItemShortcut = new DevExpress.XtraBars.BarShortcut((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.H));
this.buttonReplace.Name = "buttonReplace";
this.buttonReplace.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.barButtonItem1_ItemClick);
//
// ribbonPage1
//
this.ribbonPage1.Groups.AddRange(new DevExpress.XtraBars.Ribbon.RibbonPageGroup[] {
this.updateRibbonPageGroup,
this.ribbonPageGroup2,
this.ribbonPageGroup10,
this.ribbonPageGroup1,
this.ribbonPageGroup5,
this.ribbonPageGroup3});
this.ribbonPage1.Name = "ribbonPage1";
this.ribbonPage1.Text = "Start";
//
// updateRibbonPageGroup
//
this.updateRibbonPageGroup.AllowMinimize = false;
this.updateRibbonPageGroup.AllowTextClipping = false;
this.updateRibbonPageGroup.ItemLinks.Add(this.buttonUpdateAvailable);
this.updateRibbonPageGroup.Name = "updateRibbonPageGroup";
this.updateRibbonPageGroup.ShowCaptionButton = false;
this.updateRibbonPageGroup.Text = "Update";
this.updateRibbonPageGroup.Visible = false;
//
// ribbonPageGroup2
//
this.ribbonPageGroup2.ItemLinks.Add(this.buttonOpenProjectFile);
this.ribbonPageGroup2.ItemLinks.Add(this.buttonCreateNewProject);
this.ribbonPageGroup2.ItemLinks.Add(this.buttonSaveProjectFile);
this.ribbonPageGroup2.ItemLinks.Add(this.buttonCloseProject);
this.ribbonPageGroup2.ItemLinks.Add(this.buttonEditProjectSettings);
this.ribbonPageGroup2.ItemLinks.Add(this.buttonShowHideProjectPanel);
this.ribbonPageGroup2.Name = "ribbonPageGroup2";
this.ribbonPageGroup2.ShowCaptionButton = false;
this.ribbonPageGroup2.Text = "Project files";
//
// ribbonPageGroup10
//
this.ribbonPageGroup10.ItemLinks.Add(this.buttonExport);
this.ribbonPageGroup10.ItemLinks.Add(this.buttonImport);
this.ribbonPageGroup10.Name = "ribbonPageGroup10";
this.ribbonPageGroup10.ShowCaptionButton = false;
this.ribbonPageGroup10.Text = "Import/export";
//
// ribbonPageGroup1
//
this.ribbonPageGroup1.ItemLinks.Add(this.buttonSaveResourceFiles);
this.ribbonPageGroup1.ItemLinks.Add(this.buttonSaveAllFiles);
this.ribbonPageGroup1.ItemLinks.Add(this.buttonOpenResourceFiles);
this.ribbonPageGroup1.ItemLinks.Add(this.buttonCloseResourceFiles);
this.ribbonPageGroup1.ItemLinks.Add(this.buttonCloseAllDocuments);
this.ribbonPageGroup1.Name = "ribbonPageGroup1";
this.ribbonPageGroup1.ShowCaptionButton = false;
this.ribbonPageGroup1.Text = "Resource files";
//
// ribbonPageGroup5
//
this.ribbonPageGroup5.ItemLinks.Add(this.buttonRefresh);
this.ribbonPageGroup5.ItemLinks.Add(this.buttonMoveUp);
this.ribbonPageGroup5.ItemLinks.Add(this.buttonMoveDown);
this.ribbonPageGroup5.ItemLinks.Add(this.resetLayoutButton);
this.ribbonPageGroup5.ItemLinks.Add(this.buttonConfigureLanguageColumns);
this.ribbonPageGroup5.Name = "ribbonPageGroup5";
this.ribbonPageGroup5.ShowCaptionButton = false;
this.ribbonPageGroup5.Text = "View";
//
// ribbonPageGroup3
//
this.ribbonPageGroup3.ItemLinks.Add(this.buttonQuickTranslate);
this.ribbonPageGroup3.ItemLinks.Add(this.buttonTranslateMissingLanguages);
this.ribbonPageGroup3.ItemLinks.Add(this.buttonFind);
this.ribbonPageGroup3.ItemLinks.Add(this.buttonFindNext);
this.ribbonPageGroup3.ItemLinks.Add(this.buttonReplace);
this.ribbonPageGroup3.Name = "ribbonPageGroup3";
this.ribbonPageGroup3.ShowCaptionButton = false;
this.ribbonPageGroup3.Text = "Edit";
//
// ribbonPage4
//
this.ribbonPage4.Groups.AddRange(new DevExpress.XtraBars.Ribbon.RibbonPageGroup[] {
this.ribbonPageGroup8,
this.ribbonPageGroup9,
this.ribbonPageGroup4});
this.ribbonPage4.Name = "ribbonPage4";
this.ribbonPage4.Text = "File groups and tags";
//
// ribbonPageGroup8
//
this.ribbonPageGroup8.ItemLinks.Add(this.buttonAutomaticallyAddFileGroupsToProject);
this.ribbonPageGroup8.ItemLinks.Add(this.buttonAddFromVisualStudio);
this.ribbonPageGroup8.ItemLinks.Add(this.buttonAddFileGroupToProject);
this.ribbonPageGroup8.ItemLinks.Add(this.buttonEditFileGroupSettings);
this.ribbonPageGroup8.ItemLinks.Add(this.buttonRemoveFileGroupFromProject);
this.ribbonPageGroup8.ItemLinks.Add(this.buttonOpenFileGroupFolder);
this.ribbonPageGroup8.Name = "ribbonPageGroup8";
this.ribbonPageGroup8.ShowCaptionButton = false;
this.ribbonPageGroup8.Text = "File groups";
//
// ribbonPageGroup9
//
this.ribbonPageGroup9.ItemLinks.Add(this.buttonAddFilesToFileGroup);
this.ribbonPageGroup9.ItemLinks.Add(this.buttonCreateNewFile);
this.ribbonPageGroup9.ItemLinks.Add(this.buttonRemoveFileFromGroup);
this.ribbonPageGroup9.ItemLinks.Add(this.buttonCreateNewFiles);
this.ribbonPageGroup9.Name = "ribbonPageGroup9";
this.ribbonPageGroup9.ShowCaptionButton = false;
this.ribbonPageGroup9.Text = "Files";
//
// ribbonPageGroup4
//
this.ribbonPageGroup4.ItemLinks.Add(this.buttonAddNewTag);
this.ribbonPageGroup4.ItemLinks.Add(this.buttonRenameTag);
this.ribbonPageGroup4.ItemLinks.Add(this.buttonDeleteTag);
this.ribbonPageGroup4.Name = "ribbonPageGroup4";
this.ribbonPageGroup4.ShowCaptionButton = false;
this.ribbonPageGroup4.Text = "Tags";
//
// ribbonPage3
//
this.ribbonPage3.Groups.AddRange(new DevExpress.XtraBars.Ribbon.RibbonPageGroup[] {
this.ribbonPageGroup7,
this.ribbonPageGroup6,
this.ribbonPageGroup11});
this.ribbonPage3.Name = "ribbonPage3";
this.ribbonPage3.Text = "Extras";
//
// ribbonPageGroup7
//
this.ribbonPageGroup7.ItemLinks.Add(this.buttonOptions);
this.ribbonPageGroup7.Name = "ribbonPageGroup7";
this.ribbonPageGroup7.ShowCaptionButton = false;
this.ribbonPageGroup7.Text = "Extras";
//
// ribbonPageGroup6
//
this.ribbonPageGroup6.ItemLinks.Add(this.buttonOnlineManual);
this.ribbonPageGroup6.ItemLinks.Add(this.buttonWebsite);
this.ribbonPageGroup6.Name = "ribbonPageGroup6";
this.ribbonPageGroup6.ShowCaptionButton = false;
this.ribbonPageGroup6.Text = "Help";
//
// ribbonPageGroup11
//
this.ribbonPageGroup11.ItemLinks.Add(this.infoButton);
this.ribbonPageGroup11.Name = "ribbonPageGroup11";
this.ribbonPageGroup11.ShowCaptionButton = false;
this.ribbonPageGroup11.Text = "Info";
//
// repositoryItemHyperLinkEdit1
//
this.repositoryItemHyperLinkEdit1.Appearance.Font = new System.Drawing.Font("Segoe UI", 13F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel);
this.repositoryItemHyperLinkEdit1.Appearance.Options.UseFont = true;
this.repositoryItemHyperLinkEdit1.AutoHeight = false;
this.repositoryItemHyperLinkEdit1.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder;
this.repositoryItemHyperLinkEdit1.Name = "repositoryItemHyperLinkEdit1";
this.repositoryItemHyperLinkEdit1.SingleClick = true;
this.repositoryItemHyperLinkEdit1.Tag = "http://www.zeta-producer.com/producer.html?from=zre";
//
// clientPanel
//
this.clientPanel.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder;
this.clientPanel.Controls.Add(this.mainFormMainSplitContainer);
this.clientPanel.Dock = System.Windows.Forms.DockStyle.Fill;
this.clientPanel.Location = new System.Drawing.Point(0, 143);
this.clientPanel.Name = "clientPanel";
this.clientPanel.Size = new System.Drawing.Size(685, 408);
this.clientPanel.TabIndex = 2;
//
// updateAvailableCheckerBackgroundWorker
//
this.updateAvailableCheckerBackgroundWorker.DoWork += new System.ComponentModel.DoWorkEventHandler(this.updateAvailableCheckerBackgroundWorker_DoWork);
this.updateAvailableCheckerBackgroundWorker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.updateAvailableCheckerBackgroundWorker_RunWorkerCompleted);
//
// updateAvailableBlinkTimer
//
this.updateAvailableBlinkTimer.Interval = 500;
this.updateAvailableBlinkTimer.Tick += new System.EventHandler(this.updateAvailableBlinkTimer_Tick);
//
// blinkImageCollection
//
this.blinkImageCollection.ImageSize = new System.Drawing.Size(32, 32);
this.blinkImageCollection.ImageStream = ((DevExpress.Utils.ImageCollectionStreamer)(resources.GetObject("blinkImageCollection.ImageStream")));
this.blinkImageCollection.Images.SetKeyName(0, "heart.png");
this.blinkImageCollection.Images.SetKeyName(1, "heart_new.png");
//
// MainForm
//
this.Appearance.Options.UseFont = true;
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None;
this.ClientSize = new System.Drawing.Size(685, 551);
this.Controls.Add(this.clientPanel);
this.Controls.Add(this.ribbon);
this.Font = new System.Drawing.Font("Segoe UI", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "MainForm";
this.Ribbon = this.ribbon;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Zeta Resource Editor";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.mainForm_FormClosing);
this.Load += new System.EventHandler(this.mainForm_Load);
this.Shown += new System.EventHandler(this.mainForm_Shown);
this.DragDrop += new System.Windows.Forms.DragEventHandler(this.mainForm_DragDrop);
this.DragEnter += new System.Windows.Forms.DragEventHandler(this.mainForm_DragEnter);
((System.ComponentModel.ISupportInitialize)(this.mainFormMainSplitContainer)).EndInit();
this.mainFormMainSplitContainer.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.ribbon)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.applicationMenu1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.repositoryItemHyperLinkEdit1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.clientPanel)).EndInit();
this.clientPanel.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.blinkImageCollection)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private DevExpress.XtraBars.Ribbon.RibbonControl ribbon;
private DevExpress.XtraBars.Ribbon.RibbonPage ribbonPage1;
private DevExpress.XtraBars.Ribbon.RibbonPageGroup ribbonPageGroup1;
private ExtendedControlsLibrary.Skinning.CustomPanel.MyPanelControl clientPanel;
private DevExpress.XtraBars.Ribbon.ApplicationMenu applicationMenu1;
private DevExpress.XtraBars.BarButtonItem infoButton;
private DevExpress.XtraBars.BarButtonItem buttonExit;
private System.ComponentModel.BackgroundWorker updateAvailableCheckerBackgroundWorker;
private DevExpress.XtraBars.Ribbon.RibbonPageGroup ribbonPageGroup2;
private DevExpress.XtraBars.Ribbon.RibbonPageGroup ribbonPageGroup3;
private DevExpress.XtraBars.Ribbon.RibbonPageGroup ribbonPageGroup4;
private DevExpress.XtraBars.Ribbon.RibbonPageGroup ribbonPageGroup6;
private DevExpress.XtraBars.BarButtonItem buttonOnlineManual;
private DevExpress.XtraBars.BarButtonItem buttonWebsite;
private DevExpress.XtraBars.BarButtonItem buttonOpenResourceFiles;
private DevExpress.XtraBars.BarButtonItem buttonSaveResourceFiles;
private DevExpress.XtraBars.BarButtonItem buttonSaveAllFiles;
private DevExpress.XtraBars.BarButtonItem buttonCloseResourceFiles;
private DevExpress.XtraBars.BarButtonItem buttonCloseAllDocuments;
private DevExpress.XtraBars.BarButtonItem buttonOpenProjectFile;
private DevExpress.XtraBars.BarButtonItem buttonSaveProjectFile;
private DevExpress.XtraBars.BarButtonItem buttonCloseProject;
private DevExpress.XtraBars.BarButtonItem buttonFind;
private DevExpress.XtraBars.BarButtonItem buttonFindNext;
private DevExpress.XtraBars.BarButtonItem buttonTranslateMissingLanguages;
private DevExpress.XtraBars.BarButtonItem buttonAddNewTag;
private DevExpress.XtraBars.BarButtonItem buttonDeleteTag;
private DevExpress.XtraBars.BarButtonItem buttonRenameTag;
private DevExpress.XtraBars.BarButtonItem buttonQuickTranslate;
private DevExpress.XtraBars.BarButtonItem buttonRefresh;
private DevExpress.XtraBars.BarButtonItem buttonOptions;
private DevExpress.XtraBars.Ribbon.RibbonPage ribbonPage3;
private DevExpress.XtraBars.Ribbon.RibbonPageGroup ribbonPageGroup7;
private DevExpress.XtraBars.BarButtonItem buttonCreateNewProject;
private DevExpress.XtraBars.BarButtonItem buttonAutomaticallyAddFileGroupsToProject;
private DevExpress.XtraBars.BarButtonItem buttonAddFileGroupToProject;
private DevExpress.XtraBars.BarButtonItem buttonRemoveFileGroupFromProject;
private DevExpress.XtraBars.BarButtonItem buttonEditFileGroupSettings;
private DevExpress.XtraBars.BarButtonItem buttonAddFilesToFileGroup;
private DevExpress.XtraBars.BarButtonItem buttonRemoveFileFromGroup;
private DevExpress.XtraBars.BarButtonItem buttonEditProjectSettings;
private DevExpress.XtraBars.Ribbon.RibbonPage ribbonPage4;
private DevExpress.XtraBars.Ribbon.RibbonPageGroup ribbonPageGroup8;
private DevExpress.XtraBars.Ribbon.RibbonPageGroup ribbonPageGroup9;
private DevExpress.XtraBars.BarMdiChildrenListItem barMdiChildrenListItem1;
private DevExpress.XtraBars.BarMdiChildrenListItem barMdiChildrenListItem2;
private DevExpress.XtraBars.BarListItem barListItem1;
private DevExpress.XtraEditors.SplitContainerControl mainFormMainSplitContainer;
private DevExpress.XtraBars.BarButtonItem buttonUpdateAvailable;
private DevExpress.XtraBars.Ribbon.RibbonPageGroup updateRibbonPageGroup;
private DevExpress.XtraEditors.Repository.RepositoryItemHyperLinkEdit repositoryItemHyperLinkEdit1;
private DevExpress.XtraBars.BarButtonItem buttonOpenFileGroupFolder;
private DevExpress.XtraBars.BarStaticItem barStaticItem1;
private DevExpress.XtraBars.BarButtonItem buttonExport;
private DevExpress.XtraBars.BarButtonItem buttonImport;
private DevExpress.XtraBars.BarSubItem barSubRecentFiles;
private DevExpress.XtraBars.BarSubItem barSubRecentProjects;
private DevExpress.XtraBars.BarButtonItem buttonMoveDown;
private DevExpress.XtraBars.BarButtonItem buttonMoveUp;
private DevExpress.XtraBars.Ribbon.RibbonPageGroup ribbonPageGroup5;
private DevExpress.XtraBars.BarButtonItem buttonShowHideProjectPanel;
private DevExpress.XtraBars.BarButtonItem buttonCreateNewFile;
private DevExpress.XtraBars.BarButtonItem buttonCreateNewFiles;
private DevExpress.XtraBars.BarButtonItem resetLayoutButton;
private DevExpress.XtraBars.BarButtonItem buttonAddFromVisualStudio;
private DevExpress.XtraBars.BarButtonItem buttonConfigureLanguageColumns;
private DevExpress.XtraBars.BarButtonItem buttonReplace;
private DevExpress.XtraBars.Ribbon.RibbonPageGroup ribbonPageGroup10;
private System.Windows.Forms.Timer updateAvailableBlinkTimer;
private DevExpress.Utils.ImageCollection blinkImageCollection;
private DevExpress.XtraBars.Ribbon.RibbonPageGroup ribbonPageGroup11;
}
}
| |
// 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.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Text;
namespace System.IO
{
public sealed partial class DriveInfo
{
private static string NormalizeDriveName(string driveName)
{
if (driveName == null)
throw new ArgumentNullException("driveName");
Contract.EndContractBlock();
string name;
if (driveName.Length == 1)
name = driveName + ":\\";
else
{
// GetPathRoot does not check all invalid characters
if (PathInternal.HasIllegalCharacters(driveName))
throw new ArgumentException(SR.Format(SR.Arg_InvalidDriveChars, driveName), "driveName");
name = Path.GetPathRoot(driveName);
// Disallow null or empty drive letters and UNC paths
if (name == null || name.Length == 0 || name.StartsWith("\\\\", StringComparison.Ordinal))
throw new ArgumentException(SR.Arg_MustBeDriveLetterOrRootDir);
}
// We want to normalize to have a trailing backslash so we don't have two equivalent forms and
// because some Win32 API don't work without it.
if (name.Length == 2 && name[1] == ':')
{
name = name + "\\";
}
// Now verify that the drive letter could be a real drive name.
// On Windows this means it's between A and Z, ignoring case.
char letter = driveName[0];
if (!((letter >= 'A' && letter <= 'Z') || (letter >= 'a' && letter <= 'z')))
throw new ArgumentException(SR.Arg_MustBeDriveLetterOrRootDir);
return name;
}
public DriveType DriveType
{
[System.Security.SecuritySafeCritical]
get
{
// GetDriveType can't fail
return (DriveType)Interop.mincore.GetDriveType(Name);
}
}
public String DriveFormat
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
const int volNameLen = 50;
StringBuilder volumeName = new StringBuilder(volNameLen);
const int fileSystemNameLen = 50;
StringBuilder fileSystemName = new StringBuilder(fileSystemNameLen);
int serialNumber, maxFileNameLen, fileSystemFlags;
uint oldMode = Interop.mincore.SetErrorMode(Interop.mincore.SEM_FAILCRITICALERRORS);
try
{
bool r = Interop.mincore.GetVolumeInformation(Name, volumeName, volNameLen, out serialNumber, out maxFileNameLen, out fileSystemFlags, fileSystemName, fileSystemNameLen);
if (!r)
{
throw __Error.GetExceptionForLastWin32DriveError(Name);
}
}
finally
{
Interop.mincore.SetErrorMode(oldMode);
}
return fileSystemName.ToString();
}
}
public long AvailableFreeSpace
{
[System.Security.SecuritySafeCritical]
get
{
long userBytes, totalBytes, freeBytes;
uint oldMode = Interop.mincore.SetErrorMode(Interop.mincore.SEM_FAILCRITICALERRORS);
try
{
bool r = Interop.mincore.GetDiskFreeSpaceEx(Name, out userBytes, out totalBytes, out freeBytes);
if (!r)
throw __Error.GetExceptionForLastWin32DriveError(Name);
}
finally
{
Interop.mincore.SetErrorMode(oldMode);
}
return userBytes;
}
}
public long TotalFreeSpace
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
long userBytes, totalBytes, freeBytes;
uint oldMode = Interop.mincore.SetErrorMode(Interop.mincore.SEM_FAILCRITICALERRORS);
try
{
bool r = Interop.mincore.GetDiskFreeSpaceEx(Name, out userBytes, out totalBytes, out freeBytes);
if (!r)
throw __Error.GetExceptionForLastWin32DriveError(Name);
}
finally
{
Interop.mincore.SetErrorMode(oldMode);
}
return freeBytes;
}
}
public long TotalSize
{
[System.Security.SecuritySafeCritical]
get
{
// Don't cache this, to handle variable sized floppy drives
// or other various removable media drives.
long userBytes, totalBytes, freeBytes;
uint oldMode = Interop.mincore.SetErrorMode(Interop.mincore.SEM_FAILCRITICALERRORS);
try
{
bool r = Interop.mincore.GetDiskFreeSpaceEx(Name, out userBytes, out totalBytes, out freeBytes);
if (!r)
throw __Error.GetExceptionForLastWin32DriveError(Name);
}
finally
{
Interop.mincore.SetErrorMode(oldMode);
}
return totalBytes;
}
}
public static DriveInfo[] GetDrives()
{
int drives = Interop.mincore.GetLogicalDrives();
if (drives == 0)
throw Win32Marshal.GetExceptionForLastWin32Error();
// GetLogicalDrives returns a bitmask starting from
// position 0 "A" indicating whether a drive is present.
// Loop over each bit, creating a DriveInfo for each one
// that is set.
uint d = (uint)drives;
int count = 0;
while (d != 0)
{
if (((int)d & 1) != 0) count++;
d >>= 1;
}
DriveInfo[] result = new DriveInfo[count];
char[] root = new char[] { 'A', ':', '\\' };
d = (uint)drives;
count = 0;
while (d != 0)
{
if (((int)d & 1) != 0)
{
result[count++] = new DriveInfo(new String(root));
}
d >>= 1;
root[0]++;
}
return result;
}
// Null is a valid volume label.
public String VolumeLabel
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
// NTFS uses a limit of 32 characters for the volume label,
// as of Windows Server 2003.
const int volNameLen = 50;
StringBuilder volumeName = new StringBuilder(volNameLen);
const int fileSystemNameLen = 50;
StringBuilder fileSystemName = new StringBuilder(fileSystemNameLen);
int serialNumber, maxFileNameLen, fileSystemFlags;
uint oldMode = Interop.mincore.SetErrorMode(Interop.mincore.SEM_FAILCRITICALERRORS);
try
{
bool r = Interop.mincore.GetVolumeInformation(Name, volumeName, volNameLen, out serialNumber, out maxFileNameLen, out fileSystemFlags, fileSystemName, fileSystemNameLen);
if (!r)
{
int errorCode = Marshal.GetLastWin32Error();
// Win9x appears to return ERROR_INVALID_DATA when a
// drive doesn't exist.
if (errorCode == Interop.mincore.Errors.ERROR_INVALID_DATA)
errorCode = Interop.mincore.Errors.ERROR_INVALID_DRIVE;
throw __Error.GetExceptionForWin32DriveError(errorCode, Name);
}
}
finally
{
Interop.mincore.SetErrorMode(oldMode);
}
return volumeName.ToString();
}
[System.Security.SecuritySafeCritical] // auto-generated
set
{
uint oldMode = Interop.mincore.SetErrorMode(Interop.mincore.SEM_FAILCRITICALERRORS);
try
{
bool r = Interop.mincore.SetVolumeLabel(Name, value);
if (!r)
{
int errorCode = Marshal.GetLastWin32Error();
// Provide better message
if (errorCode == Interop.mincore.Errors.ERROR_ACCESS_DENIED)
throw new UnauthorizedAccessException(SR.InvalidOperation_SetVolumeLabelFailed);
throw __Error.GetExceptionForWin32DriveError(errorCode, Name);
}
}
finally
{
Interop.mincore.SetErrorMode(oldMode);
}
}
}
}
}
| |
using System;
using UnityEngine;
namespace FineGameDesign.Utils
{
[Serializable]
public sealed class PauseSystem : ASingleton<PauseSystem>
{
public enum State
{
None,
Begin,
End
}
public static event Action<State> onStateChanged;
public static event Action<float> onDeltaTime;
private State m_State = State.None;
[SerializeField]
private bool m_IsPaused;
public bool isPaused
{
get
{
return m_IsPaused;
}
set
{
if (value)
{
Pause();
}
else
{
Resume();
}
m_IsPaused = value;
}
}
public State state
{
get
{
return m_State;
}
set
{
if (m_State == value)
{
return;
}
m_State = value;
if (onStateChanged == null)
{
return;
}
onStateChanged(value);
}
}
[SerializeField]
[Tooltip("Scales time to zero when paused and back to one after resumed.")]
private bool m_ScaleTime = false;
public bool scaleTime
{
get { return m_ScaleTime; }
set { m_ScaleTime = value; }
}
[NonSerialized]
private float m_DeltaTime = 0f;
public float deltaTime
{
get { return m_DeltaTime; }
set { m_DeltaTime = value; }
}
private float m_PreviousTimeScale = 1f;
private bool m_IsVerbose = true;
/// <summary>
/// Avoids case on WebGL.
/// Scene reloads but no interaction until pause and resume again.
/// No problem in Unity Editor WebGL.
/// But in browser, some clicks and keypresses are ignored.
/// Pausing and resuming works around this.
/// </summary>
public void ResetWebGL()
{
Reset();
}
/// <summary>
/// Reenters current state.
/// Synchronizes pause flag and state.
/// </summary>
public void Reset()
{
if (m_IsPaused)
{
Resume();
Pause();
}
else
{
Resume();
}
}
public void Update(float deltaTime)
{
if (m_IsPaused)
{
deltaTime = 0f;
}
m_DeltaTime = deltaTime;
if (deltaTime == 0f)
return;
if (onDeltaTime == null)
return;
onDeltaTime(deltaTime);
}
public void Pause()
{
if (m_IsPaused)
{
return;
}
m_IsPaused = true;
if (m_ScaleTime)
{
m_PreviousTimeScale = Time.timeScale;
if (m_PreviousTimeScale <= 0f)
{
m_PreviousTimeScale = 1f;
}
if (m_IsVerbose)
{
DebugUtil.Log("PauseSystem.Pause: " + m_PreviousTimeScale + " time " + Time.timeScale);
}
Time.timeScale = 0f;
}
ChangeState(State.Begin);
}
public void Resume()
{
if (!m_IsPaused)
{
return;
}
m_IsPaused = false;
if (m_ScaleTime)
{
if (m_PreviousTimeScale <= 0f)
{
m_PreviousTimeScale = 1f;
}
if (m_IsVerbose)
{
DebugUtil.Log("PauseSystem.Resume: " + m_PreviousTimeScale + " time " + Time.timeScale);
}
Time.timeScale = m_PreviousTimeScale;
}
ChangeState(State.End);
}
/// <summary>
/// Guarantees state changed.
/// Otherwise, in Word Sizzle, animation did not play.
/// Somehow state can get out of sync with pause.
/// </summary>
private void ChangeState(State nextState)
{
if (m_State == nextState)
{
if (m_State == State.None)
{
m_State = State.Begin;
}
else
{
m_State = State.None;
}
}
state = nextState;
}
}
}
| |
/* ====================================================================
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.
==================================================================== */
/* ================================================================
* About NPOI
* Author: Tony Qu
* Author's email: tonyqus (at) gmail.com
* Author's Blog: tonyqus.wordpress.com.cn (wp.tonyqus.cn)
* HomePage: http://www.codeplex.com/npoi
* Contributors:
*
* ==============================================================*/
namespace NPOI.HPSF
{
using System;
using System.Collections;
/// <summary>
/// The <em>Variant</em> types as defined by Microsoft's COM. I
/// found this information in <a href="http://www.marin.clara.net/COM/variant_type_definitions.htm">
/// http://www.marin.clara.net/COM/variant_type_definitions.htm</a>.
/// In the variant types descriptions the following shortcuts are
/// used: <strong> [V]</strong> - may appear in a VARIANT,
/// <strong>[T]</strong> - may appear in a TYPEDESC,
/// <strong>[P]</strong> - may appear in an OLE property Set,
/// <strong>[S]</strong> - may appear in a Safe Array.
/// @author Rainer Klute ([email protected])
/// @since 2002-02-09
/// </summary>
internal class Variant
{
/**
* [V][P] Nothing, i.e. not a single byte of data.
*/
public const int VT_EMPTY = 0;
/**
* [V][P] SQL style Null.
*/
public const int VT_NULL = 1;
/**
* [V][T][P][S] 2 byte signed int.
*/
public const int VT_I2 = 2;
/**
* [V][T][P][S] 4 byte signed int.
*/
public const int VT_I4 = 3;
/**
* [V][T][P][S] 4 byte real.
*/
public const int VT_R4 = 4;
/**
* [V][T][P][S] 8 byte real.
*/
public const int VT_R8 = 5;
/**
* [V][T][P][S] currency. <span style="background-color:
* #ffff00">How long is this? How is it To be
* interpreted?</span>
*/
public const int VT_CY = 6;
/**
* [V][T][P][S] DateTime. <span style="background-color:
* #ffff00">How long is this? How is it To be
* interpreted?</span>
*/
public const int VT_DATE = 7;
/**
* [V][T][P][S] OLE Automation string. <span
* style="background-color: #ffff00">How long is this? How is it
* To be interpreted?</span>
*/
public const int VT_BSTR = 8;
/**
* [V][T][P][S] IDispatch *. <span style="background-color:
* #ffff00">How long is this? How is it To be
* interpreted?</span>
*/
public const int VT_DISPATCH = 9;
/**
* [V][T][S] SCODE. <span style="background-color: #ffff00">How
* long is this? How is it To be interpreted?</span>
*/
public const int VT_ERROR = 10;
/**
* [V][T][P][S] True=-1, False=0.
*/
public const int VT_BOOL = 11;
/**
* [V][T][P][S] VARIANT *. <span style="background-color:
* #ffff00">How long is this? How is it To be
* interpreted?</span>
*/
public const int VT_VARIANT = 12;
/**
* [V][T][S] IUnknown *. <span style="background-color:
* #ffff00">How long is this? How is it To be
* interpreted?</span>
*/
public const int VT_UNKNOWN = 13;
/**
* [V][T][S] 16 byte fixed point.
*/
public const int VT_DECIMAL = 14;
/**
* [T] signed char.
*/
public const int VT_I1 = 16;
/**
* [V][T][P][S] unsigned char.
*/
public const int VT_UI1 = 17;
/**
* [T][P] unsigned short.
*/
public const int VT_UI2 = 18;
/**
* [T][P] unsigned int.
*/
public const int VT_UI4 = 19;
/**
* [T][P] signed 64-bit int.
*/
public const int VT_I8 = 20;
/**
* [T][P] unsigned 64-bit int.
*/
public const int VT_UI8 = 21;
/**
* [T] signed machine int.
*/
public const int VT_INT = 22;
/**
* [T] unsigned machine int.
*/
public const int VT_UINT = 23;
/**
* [T] C style void.
*/
public const int VT_VOID = 24;
/**
* [T] Standard return type. <span style="background-color:
* #ffff00">How long is this? How is it To be
* interpreted?</span>
*/
public const int VT_HRESULT = 25;
/**
* [T] pointer type. <span style="background-color:
* #ffff00">How long is this? How is it To be
* interpreted?</span>
*/
public const int VT_PTR = 26;
/**
* [T] (use VT_ARRAY in VARIANT).
*/
public const int VT_SAFEARRAY = 27;
/**
* [T] C style array. <span style="background-color:
* #ffff00">How long is this? How is it To be
* interpreted?</span>
*/
public const int VT_CARRAY = 28;
/**
* [T] user defined type. <span style="background-color:
* #ffff00">How long is this? How is it To be
* interpreted?</span>
*/
public const int VT_USERDEFINED = 29;
/**
* [T][P] null terminated string.
*/
public const int VT_LPSTR = 30;
/**
* [T][P] wide (Unicode) null terminated string.
*/
public const int VT_LPWSTR = 31;
/**
* [P] FILETIME. The FILETIME structure holds a DateTime and time
* associated with a file. The structure identifies a 64-bit
* integer specifying the number of 100-nanosecond intervals which
* have passed since January 1, 1601. This 64-bit value is split
* into the two dwords stored in the structure.
*/
public const int VT_FILETIME = 64;
/**
* [P] Length prefixed bytes.
*/
public const int VT_BLOB = 65;
/**
* [P] Name of the stream follows.
*/
public const int VT_STREAM = 66;
/**
* [P] Name of the storage follows.
*/
public const int VT_STORAGE = 67;
/**
* [P] Stream Contains an object. <span
* style="background-color: #ffff00"> How long is this? How is it
* To be interpreted?</span>
*/
public const int VT_STREAMED_OBJECT = 68;
/**
* [P] Storage Contains an object. <span
* style="background-color: #ffff00"> How long is this? How is it
* To be interpreted?</span>
*/
public const int VT_STORED_OBJECT = 69;
/**
* [P] Blob Contains an object. <span style="background-color:
* #ffff00">How long is this? How is it To be
* interpreted?</span>
*/
public const int VT_BLOB_OBJECT = 70;
/**
* [P] Clipboard format. <span style="background-color:
* #ffff00">How long is this? How is it To be
* interpreted?</span>
*/
public const int VT_CF = 71;
/**
* [P] A Class ID.
*
* It consists of a 32 bit unsigned integer indicating the size
* of the structure, a 32 bit signed integer indicating (Clipboard
* Format Tag) indicating the type of data that it Contains, and
* then a byte array containing the data.
*
* The valid Clipboard Format Tags are:
*
* <ul>
* <li>{@link Thumbnail#CFTAG_WINDOWS}</li>
* <li>{@link Thumbnail#CFTAG_MACINTOSH}</li>
* <li>{@link Thumbnail#CFTAG_NODATA}</li>
* <li>{@link Thumbnail#CFTAG_FMTID}</li>
* </ul>
*
* <pre>typedef struct tagCLIPDATA {
* // cbSize is the size of the buffer pointed To
* // by pClipData, plus sizeof(ulClipFmt)
* ULONG cbSize;
* long ulClipFmt;
* BYTE* pClipData;
* } CLIPDATA;</pre>
*
* See <a
* href="msdn.microsoft.com/library/en-us/com/stgrstrc_0uwk.asp"
* tarGet="_blank">
* msdn.microsoft.com/library/en-us/com/stgrstrc_0uwk.asp</a>.
*/
public const int VT_CLSID = 72;
/**
* [P] simple counted array. <span style="background-color:
* #ffff00">How long is this? How is it To be
* interpreted?</span>
*/
public const int VT_VECTOR = 0x1000;
/**
* [V] SAFEARRAY*. <span style="background-color: #ffff00">How
* long is this? How is it To be interpreted?</span>
*/
public const int VT_ARRAY = 0x2000;
/**
* [V] void* for local use. <span style="background-color:
* #ffff00">How long is this? How is it To be
* interpreted?</span>
*/
public const int VT_BYREF = 0x4000;
/**
* FIXME (3): Document this!
*/
public const int VT_RESERVED = 0x8000;
/**
* FIXME (3): Document this!
*/
public const int VT_ILLEGAL = 0xFFFF;
/**
* FIXME (3): Document this!
*/
public const int VT_ILLEGALMASKED = 0xFFF;
/**
* FIXME (3): Document this!
*/
public const int VT_TYPEMASK = 0xFFF;
/**
* Maps the numbers denoting the variant types To their corresponding
* variant type names.
*/
private static IDictionary numberToName;
private static IDictionary numberToLength;
/**
* Denotes a variant type with a Length that is unknown To HPSF yet.
*/
public const int Length_UNKNOWN = -2;
/**
* Denotes a variant type with a variable Length.
*/
public const int Length_VARIABLE = -1;
/**
* Denotes a variant type with a Length of 0 bytes.
*/
public const int Length_0 = 0;
/**
* Denotes a variant type with a Length of 2 bytes.
*/
public const int Length_2 = 2;
/**
* Denotes a variant type with a Length of 4 bytes.
*/
public const int Length_4 = 4;
/**
* Denotes a variant type with a Length of 8 bytes.
*/
public const int Length_8 = 8;
static Variant()
{
/* Initialize the number-to-name map: */
Hashtable tm1 = new Hashtable();
tm1[0] = "VT_EMPTY";
tm1[1] = "VT_NULL";
tm1[2] = "VT_I2";
tm1[3] = "VT_I4";
tm1[4] = "VT_R4";
tm1[5] = "VT_R8";
tm1[6] = "VT_CY";
tm1[7] = "VT_DATE";
tm1[8] = "VT_BSTR";
tm1[9] = "VT_DISPATCH";
tm1[10] = "VT_ERROR";
tm1[11] = "VT_BOOL";
tm1[12] = "VT_VARIANT";
tm1[13] = "VT_UNKNOWN";
tm1[14] = "VT_DECIMAL";
tm1[16] = "VT_I1";
tm1[17] = "VT_UI1";
tm1[18] = "VT_UI2";
tm1[19] = "VT_UI4";
tm1[20] = "VT_I8";
tm1[21] = "VT_UI8";
tm1[22] = "VT_INT";
tm1[23] = "VT_UINT";
tm1[24] = "VT_VOID";
tm1[25] = "VT_HRESULT";
tm1[26] = "VT_PTR";
tm1[27] = "VT_SAFEARRAY";
tm1[28] = "VT_CARRAY";
tm1[29] = "VT_USERDEFINED";
tm1[30] = "VT_LPSTR";
tm1[31] = "VT_LPWSTR";
tm1[64] = "VT_FILETIME";
tm1[65] = "VT_BLOB";
tm1[66] = "VT_STREAM";
tm1[67] = "VT_STORAGE";
tm1[68] = "VT_STREAMED_OBJECT";
tm1[69] = "VT_STORED_OBJECT";
tm1[70] = "VT_BLOB_OBJECT";
tm1[71] = "VT_CF";
tm1[72] = "VT_CLSID";
numberToName = tm1;
/* Initialize the number-to-Length map: */
Hashtable tm2 = new Hashtable();
tm2[0] = Length_0;
tm2[1] = Length_UNKNOWN;
tm2[2] = Length_2;
tm2[3] = Length_4;
tm2[4] = Length_4;
tm2[5] = Length_8;
tm2[6] = Length_UNKNOWN;
tm2[7] = Length_UNKNOWN;
tm2[8] = Length_UNKNOWN;
tm2[9] = Length_UNKNOWN;
tm2[10] = Length_UNKNOWN;
tm2[11] = Length_UNKNOWN;
tm2[12] = Length_UNKNOWN;
tm2[13] = Length_UNKNOWN;
tm2[14] = Length_UNKNOWN;
tm2[16] = Length_UNKNOWN;
tm2[17] = Length_UNKNOWN;
tm2[18] = Length_UNKNOWN;
tm2[19] = Length_UNKNOWN;
tm2[20] = Length_UNKNOWN;
tm2[21] = Length_UNKNOWN;
tm2[22] = Length_UNKNOWN;
tm2[23] = Length_UNKNOWN;
tm2[24] = Length_UNKNOWN;
tm2[25] = Length_UNKNOWN;
tm2[26] = Length_UNKNOWN;
tm2[27] = Length_UNKNOWN;
tm2[28] = Length_UNKNOWN;
tm2[29] = Length_UNKNOWN;
tm2[30] = Length_VARIABLE;
tm2[31] = Length_UNKNOWN;
tm2[64] = Length_8;
tm2[65] = Length_UNKNOWN;
tm2[66] = Length_UNKNOWN;
tm2[67] = Length_UNKNOWN;
tm2[68] = Length_UNKNOWN;
tm2[69] = Length_UNKNOWN;
tm2[70] = Length_UNKNOWN;
tm2[71] = Length_UNKNOWN;
tm2[72] = Length_UNKNOWN;
numberToLength = tm2;
}
/// <summary>
/// Returns the variant type name associated with a variant type
/// number.
/// </summary>
/// <param name="variantType">The variant type number.</param>
/// <returns>The variant type name or the string "unknown variant type"</returns>
public static String GetVariantName(long variantType)
{
String name = (String)numberToName[variantType];
return name != null ? name : "unknown variant type";
}
/// <summary>
/// Returns a variant type's Length.
/// </summary>
/// <param name="variantType">The variant type number.</param>
/// <returns>The Length of the variant type's data in bytes. If the Length Is
/// variable, i.e. the Length of a string, -1 is returned. If HPSF does not
/// know the Length, -2 is returned. The latter usually indicates an
/// unsupported variant type.</returns>
public static int GetVariantLength(long variantType)
{
long key = (int)variantType;
if (numberToLength.Contains(key))
return -2;
long Length = (long)numberToLength[key];
return Convert.ToInt32(Length);
}
}
}
| |
// 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.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using Xunit;
namespace System.IO.Tests
{
public static partial class PathTests
{
[Theory]
[InlineData(null, null, null)]
[InlineData(null, "exe", null)]
[InlineData("", "", "")]
[InlineData("file.exe", null, "file")]
[InlineData("file.exe", "", "file.")]
[InlineData("file", "exe", "file.exe")]
[InlineData("file", ".exe", "file.exe")]
[InlineData("file.txt", "exe", "file.exe")]
[InlineData("file.txt", ".exe", "file.exe")]
[InlineData("file.txt.bin", "exe", "file.txt.exe")]
[InlineData("dir/file.t", "exe", "dir/file.exe")]
[InlineData("dir/file.exe", "t", "dir/file.t")]
[InlineData("dir/file", "exe", "dir/file.exe")]
public static void ChangeExtension(string path, string newExtension, string expected)
{
if (expected != null)
expected = expected.Replace('/', Path.DirectorySeparatorChar);
if (path != null)
path = path.Replace('/', Path.DirectorySeparatorChar);
Assert.Equal(expected, Path.ChangeExtension(path, newExtension));
}
[Theory]
[InlineData("")]
[InlineData(" ")]
[InlineData("\r\n")]
public static void GetDirectoryName_EmptyOrWhitespace_Throws(string path)
{
AssertExtensions.Throws<ArgumentException>("path", null, () => Path.GetDirectoryName(path));
}
[Theory]
[InlineData(null, null)]
[InlineData(".", "")]
[InlineData("..", "")]
[InlineData("baz", "")]
public static void GetDirectoryName(string path, string expected)
{
Assert.Equal(expected, Path.GetDirectoryName(path));
}
[Theory]
[InlineData(@"dir/baz", "dir")]
[InlineData(@"dir\baz", "dir")]
[InlineData(@"dir\baz\bar", @"dir\baz")]
[InlineData(@"dir\\baz", "dir")]
[InlineData(@" dir\baz", " dir")]
[InlineData(@" C:\dir\baz", @"C:\dir")]
[InlineData(@"..\..\files.txt", @"..\..")]
[InlineData(@"C:\", null)]
[InlineData(@"C:", null)]
[PlatformSpecific(TestPlatforms.Windows)] // Tests Windows-specific paths
public static void GetDirectoryName_Windows(string path, string expected)
{
Assert.Equal(expected, Path.GetDirectoryName(path));
}
[Theory]
[InlineData(@"dir/baz", @"dir")]
[InlineData(@"dir//baz", @"dir")]
[InlineData(@"dir\baz", @"")]
[InlineData(@"dir/baz/bar", @"dir/baz")]
[InlineData(@"../../files.txt", @"../..")]
[InlineData(@"/", null)]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Tests Unix-specific paths
public static void GetDirectoryName_Unix(string path, string expected)
{
Assert.Equal(expected, Path.GetDirectoryName(path));
}
[Fact]
public static void GetDirectoryName_CurrentDirectory()
{
string curDir = Directory.GetCurrentDirectory();
Assert.Equal(curDir, Path.GetDirectoryName(Path.Combine(curDir, "baz")));
Assert.Equal(null, Path.GetDirectoryName(Path.GetPathRoot(curDir)));
}
[PlatformSpecific(TestPlatforms.AnyUnix)] // Checks Unix-specific special characters in directory path
[Fact]
public static void GetDirectoryName_ControlCharacters_Unix()
{
Assert.Equal(new string('\t', 1), Path.GetDirectoryName(Path.Combine(new string('\t', 1), "file")));
Assert.Equal(new string('\b', 2), Path.GetDirectoryName(Path.Combine(new string('\b', 2), "fi le")));
Assert.Equal(new string('\v', 3), Path.GetDirectoryName(Path.Combine(new string('\v', 3), "fi\nle")));
Assert.Equal(new string('\n', 4), Path.GetDirectoryName(Path.Combine(new string('\n', 4), "fi\rle")));
}
[Theory]
[InlineData("file.exe", ".exe")]
[InlineData("file", "")]
[InlineData(null, null)]
[InlineData("file.", "")]
[InlineData("file.s", ".s")]
[InlineData("test/file", "")]
[InlineData("test/file.extension", ".extension")]
public static void GetExtension(string path, string expected)
{
if (path != null)
{
path = path.Replace('/', Path.DirectorySeparatorChar);
}
Assert.Equal(expected, Path.GetExtension(path));
Assert.Equal(!string.IsNullOrEmpty(expected), Path.HasExtension(path));
}
[PlatformSpecific(TestPlatforms.AnyUnix)] // Checks file extension behavior on Unix
[Theory]
[InlineData("file.e xe", ".e xe")]
[InlineData("file. ", ". ")]
[InlineData(" file. ", ". ")]
[InlineData(" file.extension", ".extension")]
[InlineData("file.exten\tsion", ".exten\tsion")]
public static void GetExtension_Unix(string path, string expected)
{
Assert.Equal(expected, Path.GetExtension(path));
Assert.Equal(!string.IsNullOrEmpty(expected), Path.HasExtension(path));
}
public static IEnumerable<object[]> GetFileName_TestData()
{
yield return new object[] { null, null };
yield return new object[] { ".", "." };
yield return new object[] { "..", ".." };
yield return new object[] { "file", "file" };
yield return new object[] { "file.", "file." };
yield return new object[] { "file.exe", "file.exe" };
yield return new object[] { Path.Combine("baz", "file.exe"), "file.exe" };
yield return new object[] { Path.Combine("bar", "baz", "file.exe"), "file.exe" };
yield return new object[] { Path.Combine("bar", "baz", "file.exe") + Path.DirectorySeparatorChar, "" };
}
[Theory]
[MemberData(nameof(GetFileName_TestData))]
public static void GetFileName(string path, string expected)
{
Assert.Equal(expected, Path.GetFileName(path));
}
[PlatformSpecific(TestPlatforms.AnyUnix)] // Tests Unix-specific valid file names
[Fact]
public static void GetFileName_Unix()
{
Assert.Equal(" . ", Path.GetFileName(" . "));
Assert.Equal(" .. ", Path.GetFileName(" .. "));
Assert.Equal("fi le", Path.GetFileName("fi le"));
Assert.Equal("fi le", Path.GetFileName("fi le"));
Assert.Equal("fi le", Path.GetFileName(Path.Combine("b \r\n ar", "fi le")));
}
public static IEnumerable<object[]> GetFileNameWithoutExtension_TestData()
{
yield return new object[] { null, null };
yield return new object[] { "", "" };
yield return new object[] { "file", "file" };
yield return new object[] { "file.exe", "file" };
yield return new object[] { Path.Combine("bar", "baz", "file.exe"), "file" };
yield return new object[] { Path.Combine("bar", "baz") + Path.DirectorySeparatorChar, "" };
}
[Theory]
[MemberData(nameof(GetFileNameWithoutExtension_TestData))]
public static void GetFileNameWithoutExtension(string path, string expected)
{
Assert.Equal(expected, Path.GetFileNameWithoutExtension(path));
}
[Fact]
public static void GetPathRoot()
{
Assert.Null(Path.GetPathRoot(null));
AssertExtensions.Throws<ArgumentException>("path", null, () => Path.GetPathRoot(string.Empty));
AssertExtensions.Throws<ArgumentException>("path", null, () => Path.GetPathRoot("\r\n"));
string cwd = Directory.GetCurrentDirectory();
Assert.Equal(cwd.Substring(0, cwd.IndexOf(Path.DirectorySeparatorChar) + 1), Path.GetPathRoot(cwd));
Assert.True(Path.IsPathRooted(cwd));
Assert.Equal(string.Empty, Path.GetPathRoot(@"file.exe"));
Assert.False(Path.IsPathRooted("file.exe"));
}
[PlatformSpecific(TestPlatforms.Windows)] // Tests UNC
[Theory]
[InlineData(@"\\test\unc\path\to\something", @"\\test\unc")]
[InlineData(@"\\a\b\c\d\e", @"\\a\b")]
[InlineData(@"\\a\b\", @"\\a\b")]
[InlineData(@"\\a\b", @"\\a\b")]
[InlineData(@"\\test\unc", @"\\test\unc")]
public static void GetPathRoot_Windows_UncAndExtended(string value, string expected)
{
Assert.True(Path.IsPathRooted(value));
Assert.Equal(expected, Path.GetPathRoot(value));
}
[PlatformSpecific(TestPlatforms.Windows)] // Tests UNC
[Theory]
[InlineData(@"\\?\UNC\test\unc", @"\\?\UNC", @"\\?\UNC\test\unc\path\to\something")]
[InlineData(@"\\?\UNC\test\unc", @"\\?\UNC", @"\\?\UNC\test\unc")]
[InlineData(@"\\?\UNC\a\b1", @"\\?\UNC", @"\\?\UNC\a\b1")]
[InlineData(@"\\?\UNC\a\b2", @"\\?\UNC", @"\\?\UNC\a\b2\")]
[InlineData(@"\\?\C:\", @"\\?\C:", @"\\?\C:\foo\bar.txt")]
public static void GetPathRoot_Windows_UncAndExtended_WithLegacySupport(string normalExpected, string legacyExpected, string value)
{
Assert.True(Path.IsPathRooted(value));
string expected = PathFeatures.IsUsingLegacyPathNormalization() ? legacyExpected : normalExpected;
Assert.Equal(expected, Path.GetPathRoot(value));
}
[PlatformSpecific(TestPlatforms.Windows)] // Tests Windows-specific path convention
[Theory]
[InlineData(@"C:", @"C:")]
[InlineData(@"C:\", @"C:\")]
[InlineData(@"C:\\", @"C:\")]
[InlineData(@"C://", @"C:\")]
[InlineData(@"C:\foo1", @"C:\")]
[InlineData(@"C:\\foo2", @"C:\")]
[InlineData(@"C://foo3", @"C:\")]
public static void GetPathRoot_Windows(string value, string expected)
{
Assert.True(Path.IsPathRooted(value));
Assert.Equal(expected, Path.GetPathRoot(value));
}
[PlatformSpecific(TestPlatforms.AnyUnix)] // Tests Unix-specific path convention
[Fact]
public static void GetPathRoot_Unix()
{
// slashes are normal filename characters
string uncPath = @"\\test\unc\path\to\something";
Assert.False(Path.IsPathRooted(uncPath));
Assert.Equal(string.Empty, Path.GetPathRoot(uncPath));
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData(" ")]
public static void IsPathRooted(string path)
{
Assert.False(Path.IsPathRooted(path));
}
// Testing invalid drive letters !(a-zA-Z)
[PlatformSpecific(TestPlatforms.Windows)]
[Theory]
[InlineData(@"@:\foo")] // 064 = @ 065 = A
[InlineData(@"[:\\")] // 091 = [ 090 = Z
[InlineData(@"`:\foo")] // 096 = ` 097 = a
[InlineData(@"{:\\")] // 123 = { 122 = z
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug fixed on Core where it would return true if the first char is not a drive letter followed by a VolumeSeparatorChar coreclr/10297")]
public static void IsPathRooted_Windows_Invalid(string value)
{
Assert.False(Path.IsPathRooted(value));
}
[Fact]
public static void GetRandomFileName()
{
char[] invalidChars = Path.GetInvalidFileNameChars();
var fileNames = new HashSet<string>();
for (int i = 0; i < 100; i++)
{
string s = Path.GetRandomFileName();
Assert.Equal(s.Length, 8 + 1 + 3);
Assert.Equal(s[8], '.');
Assert.Equal(-1, s.IndexOfAny(invalidChars));
Assert.True(fileNames.Add(s));
}
}
[Fact]
public static void GetInvalidPathChars()
{
Assert.NotNull(Path.GetInvalidPathChars());
Assert.NotSame(Path.GetInvalidPathChars(), Path.GetInvalidPathChars());
Assert.Equal((IEnumerable<char>)Path.GetInvalidPathChars(), Path.GetInvalidPathChars());
Assert.True(Path.GetInvalidPathChars().Length > 0);
Assert.All(Path.GetInvalidPathChars(), c =>
{
string bad = c.ToString();
AssertExtensions.Throws<ArgumentException>("path", null, () => Path.ChangeExtension(bad, "ok"));
AssertExtensions.Throws<ArgumentException>("path", null, () => Path.Combine(bad, "ok"));
AssertExtensions.Throws<ArgumentException>("path", null, () => Path.Combine("ok", "ok", bad));
AssertExtensions.Throws<ArgumentException>("path", null, () => Path.Combine("ok", "ok", bad, "ok"));
AssertExtensions.Throws<ArgumentException>("path", null, () => Path.Combine(bad, bad, bad, bad, bad));
AssertExtensions.Throws<ArgumentException>("path", null, () => Path.GetDirectoryName(bad));
AssertExtensions.Throws<ArgumentException>("path", null, () => Path.GetExtension(bad));
AssertExtensions.Throws<ArgumentException>("path", null, () => Path.GetFileName(bad));
AssertExtensions.Throws<ArgumentException>("path", null, () => Path.GetFileNameWithoutExtension(bad));
AssertExtensions.Throws<ArgumentException>(c == 124 ? null : "path", null, () => Path.GetFullPath(bad));
AssertExtensions.Throws<ArgumentException>("path", null, () => Path.GetPathRoot(bad));
AssertExtensions.Throws<ArgumentException>("path", null, () => Path.IsPathRooted(bad));
});
}
[Fact]
public static void GetInvalidFileNameChars()
{
Assert.NotNull(Path.GetInvalidFileNameChars());
Assert.NotSame(Path.GetInvalidFileNameChars(), Path.GetInvalidFileNameChars());
Assert.Equal((IEnumerable<char>)Path.GetInvalidFileNameChars(), Path.GetInvalidFileNameChars());
Assert.True(Path.GetInvalidFileNameChars().Length > 0);
}
[Fact]
[OuterLoop]
public static void GetInvalidFileNameChars_OtherCharsValid()
{
string curDir = Directory.GetCurrentDirectory();
var invalidChars = new HashSet<char>(Path.GetInvalidFileNameChars());
for (int i = 0; i < char.MaxValue; i++)
{
char c = (char)i;
if (!invalidChars.Contains(c))
{
string name = "file" + c + ".txt";
Assert.Equal(Path.Combine(curDir, name), Path.GetFullPath(name));
}
}
}
[Fact]
public static void GetTempPath_Default()
{
string tmpPath = Path.GetTempPath();
Assert.False(string.IsNullOrEmpty(tmpPath));
Assert.Equal(tmpPath, Path.GetTempPath());
Assert.Equal(Path.DirectorySeparatorChar, tmpPath[tmpPath.Length - 1]);
Assert.True(Directory.Exists(tmpPath));
}
[PlatformSpecific(TestPlatforms.Windows)] // Sets environment vars with Windows-specific paths
[Theory]
[InlineData(@"C:\Users\someuser\AppData\Local\Temp\", @"C:\Users\someuser\AppData\Local\Temp")]
[InlineData(@"C:\Users\someuser\AppData\Local\Temp\", @"C:\Users\someuser\AppData\Local\Temp\")]
[InlineData(@"C:\", @"C:\")]
[InlineData(@"C:\tmp\", @"C:\tmp")]
[InlineData(@"C:\tmp\", @"C:\tmp\")]
public static void GetTempPath_SetEnvVar_Windows(string expected, string newTempPath)
{
GetTempPath_SetEnvVar("TMP", expected, newTempPath);
}
[PlatformSpecific(TestPlatforms.AnyUnix)] // Sets environment vars with Unix-specific paths
[Theory]
[InlineData("/tmp/", "/tmp")]
[InlineData("/tmp/", "/tmp/")]
[InlineData("/", "/")]
[InlineData("/var/tmp/", "/var/tmp")]
[InlineData("/var/tmp/", "/var/tmp/")]
[InlineData("~/", "~")]
[InlineData("~/", "~/")]
[InlineData(".tmp/", ".tmp")]
[InlineData("./tmp/", "./tmp")]
[InlineData("/home/someuser/sometempdir/", "/home/someuser/sometempdir/")]
[InlineData("/home/someuser/some tempdir/", "/home/someuser/some tempdir/")]
[InlineData("/tmp/", null)]
public static void GetTempPath_SetEnvVar_Unix(string expected, string newTempPath)
{
GetTempPath_SetEnvVar("TMPDIR", expected, newTempPath);
}
private static void GetTempPath_SetEnvVar(string envVar, string expected, string newTempPath)
{
string original = Path.GetTempPath();
Assert.NotNull(original);
try
{
Environment.SetEnvironmentVariable(envVar, newTempPath);
Assert.Equal(
Path.GetFullPath(expected),
Path.GetFullPath(Path.GetTempPath()));
}
finally
{
Environment.SetEnvironmentVariable(envVar, original);
Assert.Equal(original, Path.GetTempPath());
}
}
[Fact]
public static void GetTempFileName()
{
string tmpFile = Path.GetTempFileName();
try
{
Assert.True(File.Exists(tmpFile));
Assert.Equal(".tmp", Path.GetExtension(tmpFile), ignoreCase: true, ignoreLineEndingDifferences: false, ignoreWhiteSpaceDifferences: false);
Assert.Equal(-1, tmpFile.IndexOfAny(Path.GetInvalidPathChars()));
using (FileStream fs = File.OpenRead(tmpFile))
{
Assert.Equal(0, fs.Length);
}
Assert.Equal(Path.Combine(Path.GetTempPath(), Path.GetFileName(tmpFile)), tmpFile);
}
finally
{
File.Delete(tmpFile);
}
}
[Fact]
public static void GetFullPath_InvalidArgs()
{
Assert.Throws<ArgumentNullException>(() => Path.GetFullPath(null));
AssertExtensions.Throws<ArgumentException>("path", null, () => Path.GetFullPath(string.Empty));
}
public static IEnumerable<object[]> GetFullPath_BasicExpansions_TestData()
{
string curDir = Directory.GetCurrentDirectory();
yield return new object[] { curDir, curDir }; // Current directory => current directory
yield return new object[] { ".", curDir }; // "." => current directory
yield return new object[] { "..", Path.GetDirectoryName(curDir) }; // "." => up a directory
yield return new object[] { Path.Combine(curDir, ".", ".", ".", ".", "."), curDir }; // "dir/./././." => "dir"
yield return new object[] { curDir + new string(Path.DirectorySeparatorChar, 3) + ".", curDir }; // "dir///." => "dir"
yield return new object[] { Path.Combine(curDir, "..", Path.GetFileName(curDir), ".", "..", Path.GetFileName(curDir)), curDir }; // "dir/../dir/./../dir" => "dir"
yield return new object[] { Path.Combine(Path.GetPathRoot(curDir), "somedir", ".."), Path.GetPathRoot(curDir) }; // "C:\somedir\.." => "C:\"
yield return new object[] { Path.Combine(Path.GetPathRoot(curDir), "."), Path.GetPathRoot(curDir) }; // "C:\." => "C:\"
yield return new object[] { Path.Combine(Path.GetPathRoot(curDir), "..", "..", "..", ".."), Path.GetPathRoot(curDir) }; // "C:\..\..\..\.." => "C:\"
yield return new object[] { Path.GetPathRoot(curDir) + new string(Path.DirectorySeparatorChar, 3), Path.GetPathRoot(curDir) }; // "C:\\\" => "C:\"
// Path longer than MaxPath that normalizes down to less than MaxPath
const int Iters = 10000;
var longPath = new StringBuilder(curDir, curDir.Length + (Iters * 2));
for (int i = 0; i < 10000; i++)
{
longPath.Append(Path.DirectorySeparatorChar).Append('.');
}
yield return new object[] { longPath.ToString(), curDir };
}
[Theory]
[MemberData(nameof(GetFullPath_BasicExpansions_TestData))]
public static void GetFullPath_BasicExpansions(string path, string expected)
{
Assert.Equal(expected, Path.GetFullPath(path));
}
[PlatformSpecific(TestPlatforms.AnyUnix)] // Tests whitespace in paths on Unix
[Fact]
public static void GetFullPath_Unix_Whitespace()
{
string curDir = Directory.GetCurrentDirectory();
Assert.Equal("/ / ", Path.GetFullPath("/ // "));
Assert.Equal(Path.Combine(curDir, " "), Path.GetFullPath(" "));
Assert.Equal(Path.Combine(curDir, "\r\n"), Path.GetFullPath("\r\n"));
}
[PlatformSpecific(TestPlatforms.AnyUnix)] // Tests URIs as valid file names
[Theory]
[InlineData("http://www.microsoft.com")]
[InlineData("file://somefile")]
public static void GetFullPath_Unix_URIsAsFileNames(string uriAsFileName)
{
// URIs are valid filenames, though the multiple slashes will be consolidated in GetFullPath
Assert.Equal(
Path.Combine(Directory.GetCurrentDirectory(), uriAsFileName.Replace("//", "/")),
Path.GetFullPath(uriAsFileName));
}
[PlatformSpecific(TestPlatforms.Windows)] // Checks normalized long path (> MaxPath) on Windows
[Fact]
public static void GetFullPath_Windows_NormalizedLongPathTooLong()
{
// Try out a long path that normalizes down to more than MaxPath
string curDir = Directory.GetCurrentDirectory();
const int Iters = 260;
var longPath = new StringBuilder(curDir, curDir.Length + (Iters * 4));
for (int i = 0; i < Iters; i++)
{
longPath.Append(Path.DirectorySeparatorChar).Append('a').Append(Path.DirectorySeparatorChar).Append('.');
}
if (PathFeatures.AreAllLongPathsAvailable())
{
// Now no longer throws unless over ~32K
Assert.NotNull(Path.GetFullPath(longPath.ToString()));
}
else
{
Assert.Throws<PathTooLongException>(() => Path.GetFullPath(longPath.ToString()));
}
}
[PlatformSpecific(TestPlatforms.Windows)] // Tests Windows-specific invalid paths
[Fact]
public static void GetFullPath_Windows_AlternateDataStreamsNotSupported()
{
// Throws via our invalid colon filtering
Assert.Throws<NotSupportedException>(() => Path.GetFullPath(@"bad:path"));
Assert.Throws<NotSupportedException>(() => Path.GetFullPath(@"C:\some\bad:path"));
}
[PlatformSpecific(TestPlatforms.Windows)] // Tests Windows-specific invalid paths
[Theory]
[InlineData("http://www.microsoft.com")]
[InlineData("file://www.microsoft.com")]
public static void GetFullPath_Windows_URIFormatNotSupported(string path)
{
// Throws via our invalid colon filtering
if (!PathFeatures.IsUsingLegacyPathNormalization())
{
Assert.Throws<NotSupportedException>(() => Path.GetFullPath(path));
}
}
[PlatformSpecific(TestPlatforms.Windows)] // Tests Windows-specific invalid paths
[Theory]
[InlineData(@"bad::$DATA")]
[InlineData(@"C :")]
[InlineData(@"C :\somedir")]
public static void GetFullPath_Windows_NotSupportedExceptionPaths(string path)
{
// Old path normalization throws ArgumentException, new one throws NotSupportedException
if (!PathFeatures.IsUsingLegacyPathNormalization())
{
Assert.Throws<NotSupportedException>(() => Path.GetFullPath(path));
}
else
{
AssertExtensions.Throws<ArgumentException>(null, () => Path.GetFullPath(path));
}
}
[PlatformSpecific(TestPlatforms.Windows)] // Tests legitimate Windows paths that are now allowed
[Theory]
[InlineData(@"C:...")]
[InlineData(@"C:...\somedir")]
[InlineData(@"\.. .\")]
[InlineData(@"\. .\")]
[InlineData(@"\ .\")]
public static void GetFullPath_Windows_LegacyArgumentExceptionPaths(string path)
{
if (PathFeatures.IsUsingLegacyPathNormalization())
{
// We didn't allow these paths on < 4.6.2
AssertExtensions.Throws<ArgumentException>(null, () => Path.GetFullPath(path));
}
else
{
// These paths are legitimate Windows paths that can be created without extended syntax.
// We now allow them through.
Path.GetFullPath(path);
}
}
[PlatformSpecific(TestPlatforms.Windows)] // Tests MaxPathNotTooLong on Windows
[Fact]
public static void GetFullPath_Windows_MaxPathNotTooLong()
{
string value = @"C:\" + new string('a', 255) + @"\";
if (PathFeatures.AreAllLongPathsAvailable())
{
// Shouldn't throw anymore
Path.GetFullPath(value);
}
else
{
Assert.Throws<PathTooLongException>(() => Path.GetFullPath(value));
}
}
[PlatformSpecific(TestPlatforms.Windows)] // Tests PathTooLong on Windows
[Fact]
public static void GetFullPath_Windows_PathTooLong()
{
Assert.Throws<PathTooLongException>(() => Path.GetFullPath(@"C:\" + new string('a', short.MaxValue) + @"\"));
}
[PlatformSpecific(TestPlatforms.Windows)] // Tests Windows-specific paths
[Theory]
[InlineData(@"C:\", @"C:\")]
[InlineData(@"C:\.", @"C:\")]
[InlineData(@"C:\..", @"C:\")]
[InlineData(@"C:\..\..", @"C:\")]
[InlineData(@"C:\A\..", @"C:\")]
[InlineData(@"C:\..\..\A\..", @"C:\")]
public static void GetFullPath_Windows_RelativeRoot(string path, string expected)
{
Assert.Equal(Path.GetFullPath(path), expected);
}
[PlatformSpecific(TestPlatforms.Windows)] // Tests legitimate strage windows paths that are now allowed
[Fact]
public static void GetFullPath_Windows_StrangeButLegalPaths()
{
// These are legal and creatable without using extended syntax if you use a trailing slash
// (such as "md ...\"). We used to filter these out, but now allow them to prevent apps from
// being blocked when they hit these paths.
string curDir = Directory.GetCurrentDirectory();
if (PathFeatures.IsUsingLegacyPathNormalization())
{
// Legacy path Path.GetFullePath() ignores . when there is less or more that two, when there is .. in the path it returns one directory up.
Assert.Equal(
Path.GetFullPath(curDir + Path.DirectorySeparatorChar),
Path.GetFullPath(curDir + Path.DirectorySeparatorChar + ". " + Path.DirectorySeparatorChar));
Assert.Equal(
Path.GetFullPath(Path.GetDirectoryName(curDir) + Path.DirectorySeparatorChar),
Path.GetFullPath(curDir + Path.DirectorySeparatorChar + "..." + Path.DirectorySeparatorChar));
Assert.Equal(
Path.GetFullPath(Path.GetDirectoryName(curDir) + Path.DirectorySeparatorChar),
Path.GetFullPath(curDir + Path.DirectorySeparatorChar + ".. " + Path.DirectorySeparatorChar));
}
else
{
Assert.NotEqual(
Path.GetFullPath(curDir + Path.DirectorySeparatorChar),
Path.GetFullPath(curDir + Path.DirectorySeparatorChar + ". " + Path.DirectorySeparatorChar));
Assert.NotEqual(
Path.GetFullPath(Path.GetDirectoryName(curDir) + Path.DirectorySeparatorChar),
Path.GetFullPath(curDir + Path.DirectorySeparatorChar + "..." + Path.DirectorySeparatorChar));
Assert.NotEqual(
Path.GetFullPath(Path.GetDirectoryName(curDir) + Path.DirectorySeparatorChar),
Path.GetFullPath(curDir + Path.DirectorySeparatorChar + ".. " + Path.DirectorySeparatorChar));
}
}
[PlatformSpecific(TestPlatforms.Windows)] // Tests Windows-specific paths
[Theory]
[InlineData(@"\\?\C:\ ")]
[InlineData(@"\\?\C:\ \ ")]
[InlineData(@"\\?\C:\ .")]
[InlineData(@"\\?\C:\ ..")]
[InlineData(@"\\?\C:\...")]
[InlineData(@"\\?\GLOBALROOT\")]
[InlineData(@"\\?\")]
[InlineData(@"\\?\.")]
[InlineData(@"\\?\..")]
[InlineData(@"\\?\\")]
[InlineData(@"\\?\C:\\")]
[InlineData(@"\\?\C:\|")]
[InlineData(@"\\?\C:\.")]
[InlineData(@"\\?\C:\..")]
[InlineData(@"\\?\C:\Foo1\.")]
[InlineData(@"\\?\C:\Foo2\..")]
[InlineData(@"\\?\UNC\")]
[InlineData(@"\\?\UNC\server1")]
[InlineData(@"\\?\UNC\server2\")]
[InlineData(@"\\?\UNC\server3\\")]
[InlineData(@"\\?\UNC\server4\..")]
[InlineData(@"\\?\UNC\server5\share\.")]
[InlineData(@"\\?\UNC\server6\share\..")]
[InlineData(@"\\?\UNC\a\b\\")]
[InlineData(@"\\.\")]
[InlineData(@"\\.\.")]
[InlineData(@"\\.\..")]
[InlineData(@"\\.\\")]
[InlineData(@"\\.\C:\\")]
[InlineData(@"\\.\C:\|")]
[InlineData(@"\\.\C:\.")]
[InlineData(@"\\.\C:\..")]
[InlineData(@"\\.\C:\Foo1\.")]
[InlineData(@"\\.\C:\Foo2\..")]
public static void GetFullPath_Windows_ValidExtendedPaths(string path)
{
if (PathFeatures.IsUsingLegacyPathNormalization())
{
// Legacy Path doesn't support any of these paths.
AssertExtensions.ThrowsAny<ArgumentException, NotSupportedException>(() => Path.GetFullPath(path));
return;
}
// None of these should throw
if (path.StartsWith(@"\\?\"))
{
Assert.Equal(path, Path.GetFullPath(path));
}
else
{
Path.GetFullPath(path);
}
}
[PlatformSpecific(TestPlatforms.Windows)] // Tests Windows-specific paths
[Theory]
[InlineData(@"\\.\UNC\")]
[InlineData(@"\\.\UNC\LOCALHOST")]
[InlineData(@"\\.\UNC\localHOST\")]
[InlineData(@"\\.\UNC\LOcaLHOST\\")]
[InlineData(@"\\.\UNC\lOCALHOST\..")]
[InlineData(@"\\.\UNC\LOCALhost\share\.")]
[InlineData(@"\\.\UNC\loCALHOST\share\..")]
[InlineData(@"\\.\UNC\a\b\\")]
public static void GetFullPath_Windows_ValidLegacy_ValidExtendedPaths(string path)
{
// should not throw
Path.GetFullPath(path);
}
[PlatformSpecific(TestPlatforms.Windows)] // Tests valid paths based on UNC
[Theory]
// https://github.com/dotnet/corefx/issues/11965
[InlineData(@"\\LOCALHOST\share\test.txt.~SS", @"\\LOCALHOST\share\test.txt.~SS")]
[InlineData(@"\\LOCALHOST\share1", @"\\LOCALHOST\share1")]
[InlineData(@"\\LOCALHOST\share2", @" \\LOCALHOST\share2")]
[InlineData(@"\\LOCALHOST\share3\dir", @"\\LOCALHOST\share3\dir")]
[InlineData(@"\\LOCALHOST\share4", @"\\LOCALHOST\share4\.")]
[InlineData(@"\\LOCALHOST\share5", @"\\LOCALHOST\share5\..")]
[InlineData(@"\\LOCALHOST\share6\", @"\\LOCALHOST\share6\ ")]
[InlineData(@"\\LOCALHOST\ share7\", @"\\LOCALHOST\ share7\")]
[InlineData(@"\\?\UNC\LOCALHOST\share8\test.txt.~SS", @"\\?\UNC\LOCALHOST\share8\test.txt.~SS")]
[InlineData(@"\\?\UNC\LOCALHOST\share9", @"\\?\UNC\LOCALHOST\share9")]
[InlineData(@"\\?\UNC\LOCALHOST\shareA\dir", @"\\?\UNC\LOCALHOST\shareA\dir")]
[InlineData(@"\\?\UNC\LOCALHOST\shareB\. ", @"\\?\UNC\LOCALHOST\shareB\. ")]
[InlineData(@"\\?\UNC\LOCALHOST\shareC\.. ", @"\\?\UNC\LOCALHOST\shareC\.. ")]
[InlineData(@"\\?\UNC\LOCALHOST\shareD\ ", @"\\?\UNC\LOCALHOST\shareD\ ")]
[InlineData(@"\\.\UNC\LOCALHOST\ shareE\", @"\\.\UNC\LOCALHOST\ shareE\")]
[InlineData(@"\\.\UNC\LOCALHOST\shareF\test.txt.~SS", @"\\.\UNC\LOCALHOST\shareF\test.txt.~SS")]
[InlineData(@"\\.\UNC\LOCALHOST\shareG", @"\\.\UNC\LOCALHOST\shareG")]
[InlineData(@"\\.\UNC\LOCALHOST\shareH\dir", @"\\.\UNC\LOCALHOST\shareH\dir")]
[InlineData(@"\\.\UNC\LOCALHOST\shareK\", @"\\.\UNC\LOCALHOST\shareK\ ")]
[InlineData(@"\\.\UNC\LOCALHOST\ shareL\", @"\\.\UNC\LOCALHOST\ shareL\")]
public static void GetFullPath_Windows_UNC_Valid(string expected, string input)
{
if (input.StartsWith(@"\\?\") && PathFeatures.IsUsingLegacyPathNormalization())
{
AssertExtensions.Throws<ArgumentException>(null, () => Path.GetFullPath(input));
}
else
{
Assert.Equal(expected, Path.GetFullPath(input));
}
}
[PlatformSpecific(TestPlatforms.Windows)] // Tests valid paths based on UNC
[Theory]
[InlineData(@"\\.\UNC\LOCALHOST\shareI\", @"\\.\UNC\LOCALHOST\shareI", @"\\.\UNC\LOCALHOST\shareI\. ")]
[InlineData(@"\\.\UNC\LOCALHOST\shareJ\", @"\\.\UNC\LOCALHOST", @"\\.\UNC\LOCALHOST\shareJ\.. ")]
public static void GetFullPath_Windows_UNC_Valid_LegacyPathSupport(string normalExpected, string legacyExpected, string input)
{
string expected = PathFeatures.IsUsingLegacyPathNormalization() ? legacyExpected : normalExpected;
Assert.Equal(expected, Path.GetFullPath(input));
}
[PlatformSpecific(TestPlatforms.Windows)] // Tests invalid paths based on UNC
[Theory]
[InlineData(@"\\")]
[InlineData(@"\\LOCALHOST")]
[InlineData(@"\\LOCALHOST\")]
[InlineData(@"\\LOCALHOST\\")]
[InlineData(@"\\LOCALHOST\..")]
public static void GetFullPath_Windows_UNC_Invalid(string invalidPath)
{
AssertExtensions.Throws<ArgumentException>(null, () => Path.GetFullPath(invalidPath));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Uses P/Invokes to get short path name
public static void GetFullPath_Windows_83Paths()
{
// Create a temporary file name with a name longer than 8.3 such that it'll need to be shortened.
string tempFilePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N") + ".txt");
File.Create(tempFilePath).Dispose();
try
{
// Get its short name
var sb = new StringBuilder(260);
if (GetShortPathName(tempFilePath, sb, sb.Capacity) > 0) // only proceed if we could successfully create the short name
{
string shortName = sb.ToString();
// Make sure the shortened name expands back to the original one
// Sometimes shortening or GetFullPath is changing the casing of "temp" on some test machines: normalize both sides
tempFilePath = Regex.Replace(tempFilePath, @"\\temp\\", @"\TEMP\", RegexOptions.IgnoreCase);
shortName = Regex.Replace(Path.GetFullPath(shortName), @"\\temp\\", @"\TEMP\", RegexOptions.IgnoreCase);
Assert.Equal(tempFilePath, shortName);
// Should work with device paths that aren't well-formed extended syntax
if (!PathFeatures.IsUsingLegacyPathNormalization())
{
Assert.Equal(@"\\.\" + tempFilePath, Path.GetFullPath(@"\\.\" + shortName));
Assert.Equal(@"\\?\" + tempFilePath, Path.GetFullPath(@"//?/" + shortName));
// Shouldn't mess with well-formed extended syntax
Assert.Equal(@"\\?\" + shortName, Path.GetFullPath(@"\\?\" + shortName));
}
// Validate case where short name doesn't expand to a real file
string invalidShortName = @"S:\DOESNT~1\USERNA~1.RED\LOCALS~1\Temp\bg3ylpzp";
Assert.Equal(invalidShortName, Path.GetFullPath(invalidShortName));
// Same thing, but with a long path that normalizes down to a short enough one
const int Iters = 1000;
var shortLongName = new StringBuilder(invalidShortName, invalidShortName.Length + (Iters * 2));
for (int i = 0; i < Iters; i++)
{
shortLongName.Append(Path.DirectorySeparatorChar).Append('.');
}
Assert.Equal(invalidShortName, Path.GetFullPath(shortLongName.ToString()));
}
}
finally
{
File.Delete(tempFilePath);
}
}
[PlatformSpecific(TestPlatforms.Windows)] // Tests Windows-specific invalid paths
[Theory]
[InlineData('*')]
[InlineData('?')]
public static void GetFullPath_Windows_Wildcards(char wildcard)
{
AssertExtensions.Throws<ArgumentException>("path", null, () => Path.GetFullPath("test" + wildcard + "ing"));
}
// Windows-only P/Invoke to create 8.3 short names from long names
[DllImport("kernel32.dll", EntryPoint = "GetShortPathNameW" ,CharSet = CharSet.Unicode)]
private static extern uint GetShortPathName(string lpszLongPath, StringBuilder lpszShortPath, int cchBuffer);
[Fact]
public static void InvalidPathChars_MatchesGetInvalidPathChars()
{
#pragma warning disable 0618
Assert.NotNull(Path.InvalidPathChars);
Assert.Equal(Path.GetInvalidPathChars(), Path.InvalidPathChars);
Assert.Same(Path.InvalidPathChars, Path.InvalidPathChars);
#pragma warning restore 0618
}
}
}
| |
using MacroDiagnostics;
using MacroExceptions;
using MacroGuards;
using MacroSln;
using System.IO;
using System.Linq;
using System;
using System.Collections.Generic;
using MacroIO;
using MacroSystem;
using System.Text.RegularExpressions;
using System.Diagnostics;
namespace
produce
{
public class
DotnetModule : Module
{
static
DotnetModule()
{
CanBuildNetFramework = false;
BuildNetFrameworkUsingMSBuild = false;
//
// On Windows we can always build for .NET Frameworks
//
if (EnvironmentExtensions.IsWindows)
{
CanBuildNetFramework = true;
}
//
// On UNIX we can build for .NET Frameworks using Mono, which we assume is available if a standalone `msbuild` is
// present
//
else
{
if (ProcessExtensions.ExecuteAny(false, false, null, "msbuild", "/version") == 0)
{
CanBuildNetFramework = true;
BuildNetFrameworkUsingMSBuild = true;
}
}
}
static bool CanBuildNetFramework;
static bool BuildNetFrameworkUsingMSBuild;
public override void
Attach(ProduceRepository repository, Graph graph)
{
Guard.NotNull(repository, nameof(repository));
Guard.NotNull(graph, nameof(graph));
var restore = graph.Command("restore");
var build = graph.Command("build");
var clean = graph.Command("clean");
var package = graph.Command("package");
var publish = graph.Command("publish");
// Solution paths
// TODO Use patterns e.g. **/*.sln once supported
var dotnetSlnPaths = graph.List("dotnet-sln-paths",
Path.Combine(repository.Path, ".nugit", repository.Name + ".sln"),
Path.Combine(repository.Path, repository.Name + ".sln"));
// Solution files
var dotnetSlnFiles = graph.FileSet("dotnet-sln-files");
graph.Dependency(dotnetSlnPaths, dotnetSlnFiles);
// Primary solution path
var dotnetSlnPath = graph.List("dotnet-sln-path", _ =>
dotnetSlnFiles.Files.Take(1)
.Select(f => f.Path));
graph.Dependency(dotnetSlnFiles, dotnetSlnPath);
// Primary solution file
var dotnetSlnFile = graph.FileSet("dotnet-sln-file");
graph.Dependency(dotnetSlnPath, dotnetSlnFile);
// Project paths
var dotnetProjPaths = graph.List("dotnet-proj-paths", _ =>
dotnetSlnFile.Files.Take(1)
.Select(f => f.Path)
.Select(p => new VisualStudioSolution(p))
.SelectMany(sln => FindLocalBuildableProjects(repository, sln))
.Select(r => r.AbsoluteLocation));
graph.Dependency(dotnetSlnFile, dotnetProjPaths);
// Project files
var dotnetProjFiles = graph.FileSet("dotnet-proj-files");
graph.Dependency(dotnetProjPaths, dotnetProjFiles);
// Primary project path
var dotnetProjPath = graph.List("dotnet-proj-path", _ =>
dotnetProjFiles.Files
.Select(f => f.Path)
.Where(p =>
string.Equals(
Path.GetFileNameWithoutExtension(p),
repository.Name,
StringComparison.OrdinalIgnoreCase))
.Take(1));
graph.Dependency(dotnetProjFiles, dotnetProjPath);
// Primary project file
var dotnetProjFile = graph.FileSet("dotnet-proj-file");
graph.Dependency(dotnetProjPath, dotnetProjFile);
// Path to .nupkg output directory
var nupkgDir = repository.GetWorkSubdirectory("nupkg");
// Path to .nupkg file
var nupkgFilePath = graph.List("dotnet-nupkg-path", _ => {
if (!Directory.Exists(nupkgDir)) return new string[0];
return
Directory.EnumerateFiles(nupkgDir, "*.nupkg")
.Select(f => Path.Combine(nupkgDir, f))
.Take(1);
});
// .nupkg file
var nupkgFile = graph.FileSet("dotnet-nupkg-file");
graph.Dependency(nupkgFilePath, nupkgFile);
// Restore
var dotnetRestore = graph.Command("dotnet-restore", _ =>
Restore(repository, dotnetSlnFile.Files.SingleOrDefault()?.Path));
graph.Dependency(dotnetProjFiles, dotnetRestore); // Should be all projects in sln, not just local?
graph.Dependency(dotnetRestore, restore);
// Build
var dotnetBuild = graph.Command("dotnet-build", _ =>
Build(repository, dotnetSlnFile.Files.SingleOrDefault()?.Path));
graph.Dependency(dotnetProjFiles, dotnetBuild);
graph.Dependency(dotnetBuild, build);
// Pack
var dotnetPack = graph.Command("dotnet-pack", _ =>
Pack(
repository,
dotnetSlnFile.Files.SingleOrDefault()?.Path,
dotnetProjFile.Files.SingleOrDefault()?.Path,
nupkgDir));
graph.Dependency(dotnetProjFile, dotnetPack);
graph.Dependency(dotnetPack, package);
// NuGet Push
var dotnetNugetPush = graph.Command("dotnet-nuget-push", _ =>
NugetPush(repository, nupkgFile.Files.SingleOrDefault()?.Path));
graph.Dependency(nupkgFile, dotnetNugetPush);
graph.Dependency(dotnetNugetPush, publish);
// Clean
var dotnetClean = graph.Command("dotnet-clean", _ =>
Clean(repository, dotnetSlnFile.Files.SingleOrDefault()?.Path));
graph.Dependency(dotnetSlnFile, dotnetClean);
graph.Dependency(dotnetClean, clean);
}
static void
Restore(ProduceRepository repository, string slnPath)
{
if (slnPath == null) return;
var sln = new VisualStudioSolution(slnPath);
using (LogicalOperation.Start("Restoring NuGet packages"))
Dotnet(repository, "restore", sln);
}
static void
Build(ProduceRepository repository, string slnPath)
{
if (slnPath == null) return;
var sln = new VisualStudioSolution(slnPath);
var projs = FindLocalBuildableProjects(repository, sln);
var frameworksByProj =
projs.ToDictionary(p => p, p => p.GetProject().AllTargetFrameworks.ToList());
var allFrameworks =
frameworksByProj.Values
.SelectMany(list => list)
.Distinct();
foreach (var framework in allFrameworks)
{
var projsTargetingThisFramework = projs.Where(p => frameworksByProj[p].Contains(framework)).ToList();
Build(repository, sln, projsTargetingThisFramework, framework);
}
}
static void
Build(
ProduceRepository repository,
VisualStudioSolution sln,
IList<VisualStudioSolutionProjectReference> projs,
string framework)
{
var properties = new Dictionary<string,String>() {
{ "TargetFramework", framework },
};
var targets = projs.Select(p => $"{p.MSBuildTargetName}:Publish");
using (LogicalOperation.Start($"Building .NET for {framework}"))
{
var isNetFramework = Regex.IsMatch(framework, @"^net\d+$");
if (isNetFramework && !CanBuildNetFramework)
{
Trace.TraceInformation("This system can't build for .NET Framework");
return;
}
if (isNetFramework && BuildNetFrameworkUsingMSBuild)
{
MSBuild(repository, sln, properties, targets);
return;
}
DotnetMSBuild(repository, sln, properties, targets);
}
}
static void
Pack(ProduceRepository repository, string slnPath, string projPath, string nupkgDir)
{
if (slnPath == null) return;
if (projPath == null) return;
Guard.Required(nupkgDir, nameof(nupkgDir));
if (!Path.IsPathRooted(nupkgDir))
throw new ArgumentException("nupkgDir must be an absolute path", nameof(nupkgDir));
var sln = new VisualStudioSolution(slnPath);
var proj = sln.ProjectReferences.Single(p => p.AbsoluteLocation == projPath);
var properties = new Dictionary<string,string>() {
{ "PackageOutputPath", nupkgDir },
};
var targets = new[]{ $"{proj.MSBuildTargetName}:Pack" };
using (LogicalOperation.Start("Building nupkg"))
{
if (Directory.Exists(nupkgDir)) Directory.Delete(nupkgDir, true);
Directory.CreateDirectory(nupkgDir);
DotnetMSBuild(repository, sln, properties, targets);
}
}
static void
NugetPush(ProduceRepository repository, string nupkgPath)
{
Guard.NotNull(repository, nameof(repository));
if (nupkgPath == null) return;
using (LogicalOperation.Start("Publishing nupkg"))
{
Dotnet(repository, "nuget", "push", nupkgPath, "-s", "https://api.nuget.org/v3/index.json");
}
}
static void
Clean(ProduceRepository repository, string slnPath)
{
if (slnPath == null) return;
var sln = new VisualStudioSolution(slnPath);
var projs = FindLocalBuildableProjects(repository, sln);
var targets = projs.Select(p => $"{p.MSBuildTargetName}:Clean");
using (LogicalOperation.Start("Cleaning .NET artifacts"))
DotnetMSBuild(repository, sln, targets);
}
static IEnumerable<VisualStudioSolutionProjectReference>
FindLocalBuildableProjects(ProduceRepository repository, VisualStudioSolution sln) =>
sln.ProjectReferences
.Where(r =>
r.TypeId == VisualStudioProjectTypeIds.CSharp ||
r.TypeId == VisualStudioProjectTypeIds.CSharpNew)
.Where(r => PathExtensions.IsDescendantOf(r.AbsoluteLocation, repository.Path))
.ToList();
static void
DotnetMSBuild(
ProduceRepository repository,
VisualStudioSolution sln,
string target)
{
DotnetMSBuild(repository, sln, new []{ target });
}
static void
DotnetMSBuild(
ProduceRepository repository,
VisualStudioSolution sln,
IEnumerable<string> targets)
{
var properties = new Dictionary<string,string>();
DotnetMSBuild(repository, sln, properties, targets);
}
static void
DotnetMSBuild(
ProduceRepository repository,
VisualStudioSolution sln,
IDictionary<string,string> properties,
IEnumerable<string> targets)
{
Guard.NotNull(repository, nameof(repository));
Guard.NotNull(sln, nameof(sln));
Guard.NotNull(properties, nameof(properties));
Guard.NotNull(targets, nameof(targets));
var args = new List<string>() {
"/nr:false",
};
args.AddRange(properties.Select(p => $"/p:{p.Key}=\"{p.Value}\""));
args.AddRange(targets.Select(t => $"/t:{t}"));
Dotnet(repository, "msbuild", sln, args.ToArray());
}
static void
MSBuild(
ProduceRepository repository,
VisualStudioSolution sln,
IDictionary<string,string> properties,
IEnumerable<string> targets)
{
Guard.NotNull(repository, nameof(repository));
Guard.NotNull(sln, nameof(sln));
Guard.NotNull(properties, nameof(properties));
Guard.NotNull(targets, nameof(targets));
var args = new List<string>() {
"/nr:false",
"/v:m",
};
args.AddRange(properties.Select(p => $"/p:{p.Key}=\"{p.Value}\""));
args.AddRange(targets.Select(t => $"/t:{t}"));
if (ProcessExtensions.ExecuteAny(true, true, repository.Path, "msbuild", args.ToArray()) != 0)
throw new UserException("Failed");
}
static void
Dotnet(ProduceRepository repository, string command, VisualStudioSolution sln, params string[] args)
{
Guard.NotNull(repository, nameof(repository));
Guard.Required(command, nameof(command));
Guard.NotNull(sln, nameof(sln));
var dotnetArgs = new List<string>() {
command, sln.Path
};
dotnetArgs.AddRange(args);
Dotnet(repository, dotnetArgs.ToArray());
}
static void
Dotnet(ProduceRepository repository, params string[] args)
{
Guard.NotNull(repository, nameof(repository));
if (ProcessExtensions.ExecuteAny(true, true, repository.Path, "dotnet", args.ToArray()) != 0)
throw new UserException("Failed");
}
}
}
| |
using System;
using System.IO;
using Pidgin.TokenStreams;
using Pidgin.Configuration;
using Xunit;
using System.Numerics;
namespace Pidgin.Tests
{
public class ParseStateTests
{
[Fact]
public void TestEmptyInput()
{
var input = "";
var state = new ParseState<char>(CharDefaultConfiguration.Instance, ToStream(input));
Assert.Equal(SourcePosDelta.Zero, state.ComputeSourcePosDelta());
Assert.False(state.HasCurrent);
}
[Fact]
public void TestAdvance()
{
var input = "foo";
var state = new ParseState<char>(CharDefaultConfiguration.Instance, ToStream(input));
Consume('f', ref state);
Consume('o', ref state);
Consume('o', ref state);
Assert.False(state.HasCurrent);
}
[Fact]
public void TestDiscardChunk()
{
var input = ('f' + new string('o', ChunkSize)); // Length == ChunkSize + 1
var state = new ParseState<char>(CharDefaultConfiguration.Instance, ToStream(input));
Consume('f', ref state);
Consume(new string('o', ChunkSize), ref state);
Assert.False(state.HasCurrent);
Assert.Equal(new SourcePosDelta(0, input.Length), state.ComputeSourcePosDelta());
}
[Fact]
public void TestSaveWholeChunkAligned()
{
// grows buffer on final iteration of loop
//
// |----|----|
// foooo
// ^----
AlignedChunkTest(ChunkSize);
}
[Fact]
public void TestSaveWholeChunkUnaligned()
{
// grows buffer on final iteration of loop
//
// |----|----|
// faoooo
// ^----
UnalignedChunkTest(ChunkSize);
}
[Fact]
public void TestSaveMoreThanWholeChunkAligned()
{
// grows buffer on penultimate iteration of loop
//
// |----|----|
// fooooo
// ^-----
AlignedChunkTest(ChunkSize + 1);
}
[Fact]
public void TestSaveMoreThanWholeChunkUnaligned()
{
// grows buffer on penultimate iteration of loop
//
// |----|----|
// faoooo
// ^----
UnalignedChunkTest(ChunkSize + 1);
}
[Fact]
public void TestSaveLessThanWholeChunkAligned()
{
// does not grow buffer
//
// |----|----|
// fooooo
// ^-----
AlignedChunkTest(ChunkSize - 1);
}
[Fact]
public void TestSaveLessThanWholeChunkUnaligned()
{
// does not grow buffer
//
// |----|----|
// fooooo
// ^-----
UnalignedChunkTest(ChunkSize - 1);
}
[Fact]
public void TestComputeSourcePos_Default()
{
{
var input = "a\n\nb";
var state = new ParseState<char>(DefaultConfiguration<char>.Instance, input.AsSpan());
state.Advance(input.Length);
Assert.Equal(new SourcePosDelta(0, 4), state.ComputeSourcePosDelta());
}
}
[Fact]
public void TestComputeSourcePos_CharDefault()
{
var input = "a\n\nb" // a partial chunk containing multiple newlines
+ "\n" + new string('a', Vector<short>.Count - 2) + "\n" // multiple whole chunks with multiple newlines
+ "\n" + new string('a', Vector<short>.Count - 2) + "\n" // ...
+ "\t" + new string('a', Vector<short>.Count * 2 - 2) + "\t" // multiple whole chunks with tabs and no newlines
+ "aa"; // a partial chunk with no newlines
{
var state = new ParseState<char>(CharDefaultConfiguration.Instance, input.AsSpan());
state.Advance(input.Length);
Assert.Equal(new SourcePosDelta(6, Vector<short>.Count * 2 + 8), state.ComputeSourcePosDelta());
}
{
var state = new ParseState<char>(CharDefaultConfiguration.Instance, input.AsSpan());
state.Advance(1);
state.ComputeSourcePosDelta();
state.Advance(input.Length - 1);
Assert.Equal(new SourcePosDelta(6, Vector<short>.Count * 2 + 8), state.ComputeSourcePosDelta());
}
}
private static void AlignedChunkTest(int inputLength)
{
var input = ('f' + new string('o', inputLength - 1));
var state = new ParseState<char>(CharDefaultConfiguration.Instance, ToStream(input));
state.PushBookmark();
Consume('f', ref state);
Consume(new string('o', inputLength - 1), ref state);
Assert.False(state.HasCurrent);
Assert.Equal(new SourcePosDelta(0, inputLength), state.ComputeSourcePosDelta());
state.Rewind();
Assert.Equal(SourcePosDelta.Zero, state.ComputeSourcePosDelta());
Consume('f', ref state);
}
private static void UnalignedChunkTest(int inputLength)
{
var input = ("fa" + new string('o', inputLength - 2));
var state = new ParseState<char>(CharDefaultConfiguration.Instance, ToStream(input));
Consume('f', ref state);
state.PushBookmark();
Consume('a' + new string('o', inputLength - 2), ref state);
Assert.False(state.HasCurrent);
Assert.Equal(new SourcePosDelta(0, inputLength), state.ComputeSourcePosDelta());
state.Rewind();
Assert.Equal(SourcePosDelta.OneCol, state.ComputeSourcePosDelta());
Consume('a', ref state);
}
private static void Consume(char expected, ref ParseState<char> state)
{
var oldCols = state.ComputeSourcePosDelta().Cols;
Assert.True(state.HasCurrent);
Assert.Equal(expected, state.Current);
state.Advance();
Assert.Equal(oldCols + 1, state.ComputeSourcePosDelta().Cols);
}
private static void Consume(string expected, ref ParseState<char> state)
{
var oldCols = state.ComputeSourcePosDelta().Cols;
AssertEqual(expected.AsSpan(), state.LookAhead(expected.Length));
state.Advance(expected.Length);
Assert.Equal(oldCols + expected.Length, state.ComputeSourcePosDelta().Cols);
}
private static void AssertEqual(ReadOnlySpan<char> expected, ReadOnlySpan<char> actual)
{
Assert.Equal(expected.Length, actual.Length);
for (var i = 0; i < expected.Length; i++)
{
Assert.Equal(expected[i], actual[i]);
}
}
private static ITokenStream<char> ToStream(string input)
=> new ReaderTokenStream(new StringReader(input));
private static int ChunkSize => ToStream("").ChunkSizeHint;
}
}
| |
--- src/mscorlib/src/System/Security/securestring.cs.orig 2016-04-23 08:46:00.000000000 -0400
+++ src/mscorlib/src/System/Security/securestring.cs 2016-04-23 19:21:25.880641000 -0400
@@ -2,7 +2,9 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Security {
+#if WIN32
using System.Security.Cryptography;
+#endif
using System.Runtime.InteropServices;
#if FEATURE_CORRUPTING_EXCEPTIONS
using System.Runtime.ExceptionServices;
@@ -25,10 +27,17 @@
private bool m_encrypted;
static bool supportedOnCurrentPlatform = EncryptionSupported();
-
+#if WIN32
const int BlockSize = (int)Win32Native.CRYPTPROTECTMEMORY_BLOCK_SIZE /2; // a char is two bytes
+#else
+ const int BlockSize = 1024;
+#endif
const int MaxLength = 65536;
+#if WIN32
const uint ProtectionScope = Win32Native.CRYPTPROTECTMEMORY_SAME_PROCESS;
+#else
+ const uint ProtectionScope = 0x0;
+#endif
[System.Security.SecuritySafeCritical] // auto-generated
static SecureString()
@@ -38,6 +47,7 @@
[System.Security.SecurityCritical] // auto-generated
unsafe static bool EncryptionSupported() {
// check if the enrypt/decrypt function is supported on current OS
+#if WIN32
bool supported = true;
try {
Win32Native.SystemFunction041(
@@ -49,6 +59,9 @@
supported = false;
}
return supported;
+#else
+ return false;
+#endif
}
[System.Security.SecurityCritical] // auto-generated
@@ -398,7 +411,7 @@
RuntimeHelpers.PrepareConstrainedRegions();
try {
m_buffer.AcquirePointer(ref bufferPtr);
-
+#if WIN32
return Win32Native.WideCharToMultiByte(
CP_ACP,
flgs,
@@ -408,6 +421,9 @@
0,
IntPtr.Zero,
new IntPtr((void*)&DefaultCharUsed));
+#else
+ return m_buffer.Length;
+#endif
}
finally {
if (bufferPtr != null)
@@ -427,7 +443,7 @@
RuntimeHelpers.PrepareConstrainedRegions();
try {
m_buffer.AcquirePointer(ref bufferPtr);
-
+#if WIN32
Win32Native.WideCharToMultiByte(
CP_ACP,
flgs,
@@ -439,6 +455,7 @@
new IntPtr((void*)&DefaultCharUsed));
*(ansiStrPtr + byteCount - 1) = (byte)0;
+#endif
}
finally {
if (bufferPtr != null)
@@ -448,7 +465,8 @@
[System.Security.SecurityCritical] // auto-generated
[ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
- private void ProtectMemory() {
+ private void ProtectMemory() {
+#if WIN32
Contract.Assert(!m_buffer.IsInvalid && m_buffer.Length != 0, "Invalid buffer!");
Contract.Assert(m_buffer.Length % BlockSize == 0, "buffer length must be multiple of blocksize!");
@@ -470,7 +488,8 @@
#endif
}
m_encrypted = true;
- }
+ }
+#endif
}
[System.Security.SecurityCritical] // auto-generated
@@ -489,6 +508,7 @@
RuntimeHelpers.PrepareConstrainedRegions();
try {
RuntimeHelpers.PrepareConstrainedRegions();
+#if WIN32
try {
}
finally {
@@ -498,7 +518,7 @@
if (ptr == IntPtr.Zero) {
throw new OutOfMemoryException();
}
-
+#endif
UnProtectMemory();
m_buffer.AcquirePointer(ref bufferPtr);
Buffer.Memcpy((byte*) ptr.ToPointer(), bufferPtr, length *2);
@@ -511,11 +531,13 @@
finally {
ProtectMemory();
if( result == IntPtr.Zero) {
+#if WIN32
// If we failed for any reason, free the new buffer
if (ptr != IntPtr.Zero) {
Win32Native.ZeroMemory(ptr, (UIntPtr)(length * 2));
Win32Native.SysFreeString(ptr);
}
+#endif
}
if (bufferPtr != null)
m_buffer.ReleasePointer();
@@ -570,7 +592,9 @@
if( result == IntPtr.Zero) {
// If we failed for any reason, free the new buffer
if (ptr != IntPtr.Zero) {
+#if WIN32
Win32Native.ZeroMemory(ptr, (UIntPtr)(length * 2));
+#endif
if( allocateFromHeap) {
Marshal.FreeHGlobal(ptr);
}
@@ -633,7 +657,9 @@
if( result == IntPtr.Zero) {
// If we failed for any reason, free the new buffer
if (ptr != IntPtr.Zero) {
+#if WIN32
Win32Native.ZeroMemory(ptr, (UIntPtr)byteCount);
+#endif
if( allocateFromHeap) {
Marshal.FreeHGlobal(ptr);
}
@@ -650,6 +676,7 @@
[System.Security.SecurityCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private void UnProtectMemory() {
+#if WIN32
Contract.Assert(!m_buffer.IsInvalid && m_buffer.Length != 0, "Invalid buffer!");
Contract.Assert(m_buffer.Length % BlockSize == 0, "buffer length must be multiple of blocksize!");
@@ -675,6 +702,7 @@
m_encrypted = false;
}
}
+#endif
}
}
@@ -697,8 +725,10 @@
[System.Security.SecurityCritical]
override protected bool ReleaseHandle()
{
+#if WIN32
Win32Native.ZeroMemory(handle, (UIntPtr) (Win32Native.SysStringLen(handle) * 2));
Win32Native.SysFreeString(handle);
+#endif
return true;
}
@@ -706,6 +736,7 @@
internal unsafe void ClearBuffer() {
byte* bufferPtr = null;
RuntimeHelpers.PrepareConstrainedRegions();
+#if WIN32
try
{
AcquirePointer(ref bufferPtr);
@@ -716,12 +747,13 @@
if (bufferPtr != null)
ReleasePointer();
}
+#endif
}
internal unsafe int Length {
get {
- return (int) Win32Native.SysStringLen(this);
+ return 0; // (int) Win32Native.SysStringLen(this);
}
}
@@ -730,12 +762,14 @@
RuntimeHelpers.PrepareConstrainedRegions();
try
{
+#if WIN32
source.AcquirePointer(ref sourcePtr);
target.AcquirePointer(ref targetPtr);
Contract.Assert(Win32Native.SysStringLen((IntPtr)targetPtr) >= Win32Native.SysStringLen((IntPtr)sourcePtr), "Target buffer is not large enough!");
Buffer.Memcpy(targetPtr, sourcePtr, (int) Win32Native.SysStringLen((IntPtr)sourcePtr) * 2);
+#endif
}
finally
{
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using IronPython.Runtime;
using IronPython.Runtime.Exceptions;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
using Microsoft.Scripting;
using Microsoft.Scripting.Actions;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
[assembly: PythonModule("_weakref", typeof(IronPython.Modules.PythonWeakRef))]
namespace IronPython.Modules {
public static partial class PythonWeakRef {
public const string __doc__ = "Provides support for creating weak references and proxies to objects";
/// <summary>
/// Wrapper provided for backwards compatibility.
/// </summary>
internal static IWeakReferenceable ConvertToWeakReferenceable(PythonContext context, object obj) {
return context.ConvertToWeakReferenceable(obj);
}
public static int getweakrefcount(CodeContext context, object @object) {
return @ref.GetWeakRefCount(context.LanguageContext, @object);
}
public static List getweakrefs(CodeContext context, object @object) {
return @ref.GetWeakRefs(context.LanguageContext, @object);
}
public static object proxy(CodeContext context, object @object) {
return proxy(context, @object, null);
}
public static object proxy(CodeContext context, object @object, object callback) {
if (PythonOps.IsCallable(context, @object)) {
return weakcallableproxy.MakeNew(context, @object, callback);
} else {
return weakproxy.MakeNew(context, @object, callback);
}
}
public static void _remove_dead_weakref(CodeContext context, PythonDictionary dict, object key) => dict.TryRemoveValue(key, out _);
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
public static readonly PythonType CallableProxyType = DynamicHelpers.GetPythonTypeFromType(typeof(weakcallableproxy));
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
public static readonly PythonType ProxyType = DynamicHelpers.GetPythonTypeFromType(typeof(weakproxy));
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
public static readonly PythonType ReferenceType = DynamicHelpers.GetPythonTypeFromType(typeof(@ref));
[PythonType]
public class @ref : IStructuralEquatable
{
private CodeContext _context;
private WeakHandle _target;
private long _targetId;
private int _hashVal;
private bool _fHasHash;
#region Python Constructors
public static object __new__(CodeContext context, PythonType cls, object @object) {
IWeakReferenceable iwr = ConvertToWeakReferenceable(context.LanguageContext, @object);
if (cls == DynamicHelpers.GetPythonTypeFromType(typeof(@ref))) {
WeakRefTracker wrt = iwr.GetWeakRef();
if (wrt != null) {
for (int i = 0; i < wrt.HandlerCount; i++) {
if (wrt.GetHandlerCallback(i) == null && wrt.GetWeakRef(i) is @ref) {
return wrt.GetWeakRef(i);
}
}
}
return new @ref(context, @object);
} else {
return cls.CreateInstance(context, @object);
}
}
public static object __new__(CodeContext context, PythonType cls, object @object, object callback) {
if (callback == null) return __new__(context, cls, @object);
if (cls == DynamicHelpers.GetPythonTypeFromType(typeof(@ref))) {
return new @ref(context, @object, callback);
} else {
return cls.CreateInstance(context, @object, callback);
}
}
public void __init__(CodeContext context, object ob, object callback=null) {
_context = context;
WeakRefTracker wrt = WeakRefHelpers.InitializeWeakRef(_context.LanguageContext, this, ob, callback);
_target = new WeakHandle(ob, false);
_targetId = wrt.TargetId;
}
#endregion
#region Constructors
public @ref(CodeContext context, object @object, object callback=null) {
// the work is actually done on the call to __init__
}
#endregion
#region Finalizer
~@ref() {
IWeakReferenceable iwr;
if (_context.LanguageContext.TryConvertToWeakReferenceable(_target.Target, out iwr))
{
WeakRefTracker wrt = iwr.GetWeakRef();
if (wrt != null) {
// weak reference being finalized before target object,
// we don't want to run the callback when the object is
// finalized.
wrt.RemoveHandler(this);
}
}
_target.Free();
}
#endregion
#region Static helpers
internal static int GetWeakRefCount(PythonContext context, object o) {
IWeakReferenceable iwr;
if (context.TryConvertToWeakReferenceable(o, out iwr)) {
WeakRefTracker wrt = iwr.GetWeakRef();
if (wrt != null) return wrt.HandlerCount;
}
return 0;
}
internal static List GetWeakRefs(PythonContext context, object o) {
List l = new List();
IWeakReferenceable iwr;
if (context.TryConvertToWeakReferenceable(o, out iwr)) {
WeakRefTracker wrt = iwr.GetWeakRef();
if (wrt != null) {
for (int i = 0; i < wrt.HandlerCount; i++) {
l.AddNoLock(wrt.GetWeakRef(i));
}
}
}
return l;
}
#endregion
[SpecialName]
public object Call(CodeContext context) {
object res = _target.Target;
GC.KeepAlive(this);
return res;
}
[return: MaybeNotImplemented]
public static NotImplementedType operator >(@ref self, object other) {
return PythonOps.NotImplemented;
}
[return: MaybeNotImplemented]
public static NotImplementedType operator <(@ref self, object other) {
return PythonOps.NotImplemented;
}
[return: MaybeNotImplemented]
public static NotImplementedType operator <=(@ref self, object other) {
return PythonOps.NotImplemented;
}
[return: MaybeNotImplemented]
public static NotImplementedType operator >=(@ref self, object other) {
return PythonOps.NotImplemented;
}
#region IStructuralEquatable Members
/// <summary>
/// Special hash function because IStructuralEquatable.GetHashCode is not allowed to throw.
/// </summary>
public int __hash__(CodeContext/*!*/ context) {
if (!_fHasHash) {
object refObj = _target.Target;
if (refObj == null) throw PythonOps.TypeError("weak object has gone away");
_hashVal = context.LanguageContext.EqualityComparerNonGeneric.GetHashCode(refObj);
_fHasHash = true;
}
GC.KeepAlive(this);
return _hashVal;
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) {
if (!_fHasHash) {
object refObj = _target.Target;
_hashVal = comparer.GetHashCode(refObj);
_fHasHash = true;
}
GC.KeepAlive(this);
return _hashVal;
}
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) {
return EqualsWorker(other, comparer);
}
private bool EqualsWorker(object other, IEqualityComparer comparer) {
if (object.ReferenceEquals(this, other)) {
return true;
}
bool fResult = false;
@ref wr = other as @ref;
if (wr != null) {
object ourTarget = _target.Target;
object itsTarget = wr._target.Target;
if (ourTarget != null && itsTarget != null) {
fResult = RefEquals(ourTarget, itsTarget, comparer);
} else {
fResult = (_targetId == wr._targetId);
}
}
GC.KeepAlive(this);
return fResult;
}
/// <summary>
/// Special equals because none of the special cases in Ops.Equals
/// are applicable here, and the reference equality check breaks some tests.
/// </summary>
private static bool RefEquals(object x, object y, IEqualityComparer comparer) {
CodeContext context;
if (comparer != null && comparer is PythonContext.PythonEqualityComparer) {
context = ((PythonContext.PythonEqualityComparer)comparer).Context.SharedContext;
} else {
context = DefaultContext.Default;
}
object ret;
if (PythonTypeOps.TryInvokeBinaryOperator(context, x, y, "__eq__", out ret) &&
ret != NotImplementedType.Value) {
return (bool)ret;
}
if (PythonTypeOps.TryInvokeBinaryOperator(context, y, x, "__eq__", out ret) &&
ret != NotImplementedType.Value) {
return (bool)ret;
}
if (comparer != null) {
return comparer.Equals(x, y);
}
return x.Equals(y);
}
#endregion
}
[PythonType, DynamicBaseTypeAttribute, PythonHidden]
public sealed partial class weakproxy : IPythonObject, ICodeFormattable, IProxyObject, IPythonMembersList, IStructuralEquatable
{
private readonly WeakHandle _target;
private readonly CodeContext/*!*/ _context;
#region Python Constructors
internal static object MakeNew(CodeContext/*!*/ context, object @object, object callback) {
IWeakReferenceable iwr = ConvertToWeakReferenceable(context.LanguageContext, @object);
if (callback == null) {
WeakRefTracker wrt = iwr.GetWeakRef();
if (wrt != null) {
for (int i = 0; i < wrt.HandlerCount; i++) {
if (wrt.GetHandlerCallback(i) == null && wrt.GetWeakRef(i) is weakproxy) {
return wrt.GetWeakRef(i);
}
}
}
}
return new weakproxy(context, @object, callback);
}
#endregion
#region Constructors
private weakproxy(CodeContext/*!*/ context, object target, object callback) {
WeakRefHelpers.InitializeWeakRef(context.LanguageContext, this, target, callback);
_target = new WeakHandle(target, false);
_context = context;
}
#endregion
#region Finalizer
~weakproxy() {
// remove our self from the chain...
IWeakReferenceable iwr;
if (_context.LanguageContext.TryConvertToWeakReferenceable(_target.Target, out iwr)) {
WeakRefTracker wrt = iwr.GetWeakRef();
wrt.RemoveHandler(this);
}
_target.Free();
}
#endregion
#region private members
/// <summary>
/// gets the object or throws a reference exception
/// </summary>
private object GetObject() {
object res;
if (!TryGetObject(out res)) {
throw PythonOps.ReferenceError("weakly referenced object no longer exists");
}
return res;
}
private bool TryGetObject(out object result) {
result = _target.Target;
if (result == null) return false;
GC.KeepAlive(this);
return true;
}
#endregion
#region IPythonObject Members
PythonDictionary IPythonObject.Dict {
get {
IPythonObject sdo = GetObject() as IPythonObject;
if (sdo != null) {
return sdo.Dict;
}
return null;
}
}
PythonDictionary IPythonObject.SetDict(PythonDictionary dict) {
return (GetObject() as IPythonObject).SetDict(dict);
}
bool IPythonObject.ReplaceDict(PythonDictionary dict) {
return (GetObject() as IPythonObject).ReplaceDict(dict);
}
void IPythonObject.SetPythonType(PythonType newType) {
(GetObject() as IPythonObject).SetPythonType(newType);
}
PythonType IPythonObject.PythonType {
get {
return DynamicHelpers.GetPythonTypeFromType(typeof(weakproxy));
}
}
object[] IPythonObject.GetSlots() { return null; }
object[] IPythonObject.GetSlotsCreate() { return null; }
#endregion
#region object overloads
public override string ToString() {
return PythonOps.ToString(GetObject());
}
#endregion
#region ICodeFormattable Members
public string/*!*/ __repr__(CodeContext/*!*/ context) {
object obj = _target.Target;
GC.KeepAlive(this);
return String.Format("<weakproxy at {0} to {1} at {2}>",
IdDispenser.GetId(this),
PythonOps.GetPythonTypeName(obj),
IdDispenser.GetId(obj));
}
#endregion
#region Custom member access
[SpecialName]
public object GetCustomMember(CodeContext/*!*/ context, string name) {
object value, o = GetObject();
if (PythonOps.TryGetBoundAttr(context, o, name, out value)) {
return value;
}
return OperationFailed.Value;
}
[SpecialName]
public void SetMember(CodeContext/*!*/ context, string name, object value) {
object o = GetObject();
PythonOps.SetAttr(context, o, name, value);
}
[SpecialName]
public void DeleteMember(CodeContext/*!*/ context, string name) {
object o = GetObject();
PythonOps.DeleteAttr(context, o, name);
}
IList<string> IMembersList.GetMemberNames() {
return PythonOps.GetStringMemberList(this);
}
IList<object> IPythonMembersList.GetMemberNames(CodeContext/*!*/ context) {
object o;
if (!TryGetObject(out o)) {
// if we've been disconnected return an empty list
return new List();
}
return PythonOps.GetAttrNames(context, o);
}
#endregion
#region IProxyObject Members
object IProxyObject.Target {
get { return GetObject(); }
}
#endregion
#region IStructuralEquatable Members
public const object __hash__ = null;
private bool EqualsWorker(weakproxy other) {
return PythonOps.EqualRetBool(_context, GetObject(), other.GetObject());
}
/// <summary>
/// Special equality function because IStructuralEquatable.Equals is not allowed to throw.
/// </summary>
[return: MaybeNotImplemented]
public object __eq__(object other) {
if (!(other is weakproxy)) return NotImplementedType.Value;
return ScriptingRuntimeHelpers.BooleanToObject(EqualsWorker((weakproxy)other));
}
[return: MaybeNotImplemented]
public object __ne__(object other) {
if (!(other is weakproxy)) return NotImplementedType.Value;
return ScriptingRuntimeHelpers.BooleanToObject(!EqualsWorker((weakproxy)other));
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) {
object obj;
if (TryGetObject(out obj)) {
return comparer.GetHashCode(obj);
}
return comparer.GetHashCode(null);
}
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) {
object obj;
if (!TryGetObject(out obj)) {
obj = null;
}
weakproxy wrp = other as weakproxy;
if (wrp != null) {
object otherObj;
if (!TryGetObject(out otherObj)) {
otherObj = null;
}
return comparer.Equals(obj, otherObj);
}
return comparer.Equals(obj, other);
}
#endregion
public object __nonzero__() {
return Converter.ConvertToBoolean(GetObject());
}
public static explicit operator bool(weakproxy self) {
return Converter.ConvertToBoolean(self.GetObject());
}
}
[PythonType, DynamicBaseTypeAttribute, PythonHidden]
public sealed partial class weakcallableproxy :
IPythonObject,
ICodeFormattable,
IProxyObject,
IStructuralEquatable,
IPythonMembersList {
private WeakHandle _target;
private readonly CodeContext/*!*/ _context;
#region Python Constructors
internal static object MakeNew(CodeContext/*!*/ context, object @object, object callback) {
IWeakReferenceable iwr = ConvertToWeakReferenceable(context.LanguageContext, @object);
if (callback == null) {
WeakRefTracker wrt = iwr.GetWeakRef();
if (wrt != null) {
for (int i = 0; i < wrt.HandlerCount; i++) {
if (wrt.GetHandlerCallback(i) == null &&
wrt.GetWeakRef(i) is weakcallableproxy) {
return wrt.GetWeakRef(i);
}
}
}
}
return new weakcallableproxy(context, @object, callback);
}
#endregion
#region Constructors
private weakcallableproxy(CodeContext context, object target, object callback) {
WeakRefHelpers.InitializeWeakRef(context.LanguageContext, this, target, callback);
_target = new WeakHandle(target, false);
_context = context;
}
#endregion
#region Finalizer
~weakcallableproxy() {
// remove our self from the chain...
IWeakReferenceable iwr;
if (_context.LanguageContext.TryConvertToWeakReferenceable(_target.Target, out iwr))
{
WeakRefTracker wrt = iwr.GetWeakRef();
wrt.RemoveHandler(this);
}
_target.Free();
}
#endregion
#region private members
/// <summary>
/// gets the object or throws a reference exception
/// </summary>
private object GetObject() {
object res;
if (!TryGetObject(out res)) {
throw PythonOps.ReferenceError("weakly referenced object no longer exists");
}
return res;
}
private bool TryGetObject(out object result) {
try {
result = _target.Target;
if (result == null) return false;
GC.KeepAlive(this);
return true;
} catch (InvalidOperationException) {
result = null;
return false;
}
}
#endregion
#region IPythonObject Members
PythonDictionary IPythonObject.Dict {
get {
return (GetObject() as IPythonObject).Dict;
}
}
PythonDictionary IPythonObject.SetDict(PythonDictionary dict) {
return (GetObject() as IPythonObject).SetDict(dict);
}
bool IPythonObject.ReplaceDict(PythonDictionary dict) {
return (GetObject() as IPythonObject).ReplaceDict(dict);
}
void IPythonObject.SetPythonType(PythonType newType) {
(GetObject() as IPythonObject).SetPythonType(newType);
}
PythonType IPythonObject.PythonType {
get {
return DynamicHelpers.GetPythonTypeFromType(typeof(weakcallableproxy));
}
}
object[] IPythonObject.GetSlots() { return null; }
object[] IPythonObject.GetSlotsCreate() { return null; }
#endregion
#region object overloads
public override string ToString() {
return PythonOps.ToString(GetObject());
}
#endregion
#region ICodeFormattable Members
public string/*!*/ __repr__(CodeContext/*!*/ context) {
object obj = _target.Target;
GC.KeepAlive(this);
return String.Format("<weakproxy at {0} to {1} at {2}>",
IdDispenser.GetId(this),
PythonOps.GetPythonTypeName(obj),
IdDispenser.GetId(obj));
}
#endregion
[SpecialName]
public object Call(CodeContext/*!*/ context, params object[] args) {
return context.LanguageContext.CallSplat(GetObject(), args);
}
[SpecialName]
public object Call(CodeContext/*!*/ context, [ParamDictionary]IDictionary<object, object> dict, params object[] args) {
return PythonCalls.CallWithKeywordArgs(context, GetObject(), args, dict);
}
#region Custom members access
[SpecialName]
public object GetCustomMember(CodeContext/*!*/ context, string name) {
object o = GetObject();
object value;
if (PythonOps.TryGetBoundAttr(context, o, name, out value)) {
return value;
}
return OperationFailed.Value;
}
[SpecialName]
public void SetMember(CodeContext/*!*/ context, string name, object value) {
object o = GetObject();
PythonOps.SetAttr(context, o, name, value);
}
[SpecialName]
public void DeleteMember(CodeContext/*!*/ context, string name) {
object o = GetObject();
PythonOps.DeleteAttr(context, o, name);
}
IList<string> IMembersList.GetMemberNames() {
return PythonOps.GetStringMemberList(this);
}
IList<object> IPythonMembersList.GetMemberNames(CodeContext/*!*/ context) {
object o;
if (!TryGetObject(out o)) {
// if we've been disconnected return an empty list
return new List();
}
return PythonOps.GetAttrNames(context, o);
}
#endregion
#region IProxyObject Members
object IProxyObject.Target {
get { return GetObject(); }
}
#endregion
#region IStructuralEquatable Members
public const object __hash__ = null;
/// <summary>
/// Special equality function because IStructuralEquatable.Equals is not allowed to throw.
/// </summary>
public bool __eq__(object other) {
weakcallableproxy wrp = other as weakcallableproxy;
if (wrp != null) return GetObject().Equals(wrp.GetObject());
return PythonOps.EqualRetBool(_context, GetObject(), other);
}
public bool __ne__(object other) {
return !__eq__(other);
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) {
object obj;
if (TryGetObject(out obj)) {
return comparer.GetHashCode(obj);
}
return comparer.GetHashCode(null);
}
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) {
object obj;
if (!TryGetObject(out obj)) {
obj = null;
}
weakcallableproxy wrp = other as weakcallableproxy;
if (wrp != null) {
object otherObj;
if (!TryGetObject(out otherObj)) {
otherObj = null;
}
return comparer.Equals(obj, otherObj);
}
return comparer.Equals(obj, other);
}
#endregion
public object __nonzero__() {
return Converter.ConvertToBoolean(GetObject());
}
}
private static class WeakRefHelpers {
public static WeakRefTracker InitializeWeakRef(PythonContext context, object self, object target, object callback) {
IWeakReferenceable iwr = ConvertToWeakReferenceable(context, target);
WeakRefTracker wrt = iwr.GetWeakRef();
if (wrt == null) {
if (!iwr.SetWeakRef(wrt = new WeakRefTracker(iwr)))
throw PythonOps.TypeError("cannot create weak reference to '{0}' object", PythonOps.GetPythonTypeName(target));
}
if (callback != null || !wrt.Contains(callback, self)) {
wrt.ChainCallback(callback, self);
}
return wrt;
}
}
}
[PythonType("wrapper_descriptor")]
internal class SlotWrapper : PythonTypeSlot, ICodeFormattable {
private readonly string _name;
private readonly PythonType _type;
public SlotWrapper(string slotName, PythonType targetType) {
_name = slotName;
_type = targetType;
}
#region ICodeFormattable Members
public virtual string/*!*/ __repr__(CodeContext/*!*/ context) {
return String.Format("<slot wrapper {0} of {1} objects>",
PythonOps.Repr(context, _name),
PythonOps.Repr(context, _type.Name));
}
#endregion
#region PythonTypeSlot Overrides
internal override bool TryGetValue(CodeContext context, object instance, PythonType owner, out object value) {
if (instance == null) {
value = this;
return true;
}
IProxyObject proxy = instance as IProxyObject;
if (proxy == null)
throw PythonOps.TypeError("descriptor for {0} object doesn't apply to {1} object",
PythonOps.Repr(context, _type.Name),
PythonOps.Repr(context, PythonTypeOps.GetName(instance)));
if (!DynamicHelpers.GetPythonType(proxy.Target).TryGetBoundMember(context, proxy.Target, _name, out value))
return false;
value = new GenericMethodWrapper(_name, proxy);
return true;
}
#endregion
}
[PythonType("method-wrapper")]
public class GenericMethodWrapper {
private readonly string name;
private readonly IProxyObject target;
public GenericMethodWrapper(string methodName, IProxyObject proxyTarget) {
name = methodName;
target = proxyTarget;
}
[SpecialName]
public object Call(CodeContext context, params object[] args) {
return PythonOps.Invoke(context, target.Target, name, args);
}
[SpecialName]
public object Call(CodeContext context, [ParamDictionary]IDictionary<object, object> dict, params object[] args) {
object targetMethod;
if (!DynamicHelpers.GetPythonType(target.Target).TryGetBoundMember(context, target.Target, name, out targetMethod))
throw PythonOps.AttributeError("type {0} has no attribute {1}",
DynamicHelpers.GetPythonType(target.Target),
name);
return PythonCalls.CallWithKeywordArgs(context, targetMethod, args, dict);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Linq;
using Xunit;
namespace System.Data.SqlClient.Tests
{
public partial class SqlConnectionTest
{
private static readonly string[] s_retrieveStatisticsKeys =
{
"BuffersReceived",
"BuffersSent",
"BytesReceived",
"BytesSent",
"CursorOpens",
"IduCount",
"IduRows",
"PreparedExecs",
"Prepares",
"SelectCount",
"SelectRows",
"ServerRoundtrips",
"SumResultSets",
"Transactions",
"UnpreparedExecs",
"ConnectionTime",
"ExecutionTime",
"NetworkServerTime"
};
[Fact]
public void RetrieveStatistics_Success()
{
var connection = new SqlConnection();
IDictionary d = connection.RetrieveStatistics();
Assert.NotNull(d);
Assert.NotSame(d, connection.RetrieveStatistics());
}
[Fact]
public void RetrieveStatistics_ExpectedKeysInDictionary_Success()
{
IDictionary d = new SqlConnection().RetrieveStatistics();
Assert.NotEmpty(d);
Assert.Equal(s_retrieveStatisticsKeys.Length, d.Count);
Assert.NotEmpty(d.Keys);
Assert.Equal(s_retrieveStatisticsKeys.Length, d.Keys.Count);
Assert.NotEmpty(d.Values);
Assert.Equal(s_retrieveStatisticsKeys.Length, d.Values.Count);
foreach (string key in s_retrieveStatisticsKeys)
{
Assert.True(d.Contains(key));
object value = d[key];
Assert.NotNull(value);
Assert.IsType<long>(value);
Assert.Equal(0L, value);
}
}
[Fact]
public void RetrieveStatistics_UnexpectedKeysNotInDictionary_Success()
{
IDictionary d = new SqlConnection().RetrieveStatistics();
Assert.False(d.Contains("Foo"));
Assert.Null(d["Foo"]);
}
[Fact]
public void RetrieveStatistics_IsSynchronized_Success()
{
IDictionary d = new SqlConnection().RetrieveStatistics();
Assert.False(d.IsSynchronized);
}
[Fact]
public void RetrieveStatistics_SyncRoot_Success()
{
IDictionary d = new SqlConnection().RetrieveStatistics();
Assert.NotNull(d.SyncRoot);
Assert.Same(d.SyncRoot, d.SyncRoot);
}
[Fact]
public void RetrieveStatistics_IsFixedSize_Success()
{
IDictionary d = new SqlConnection().RetrieveStatistics();
Assert.False(d.IsFixedSize);
}
[Fact]
public void RetrieveStatistics_IsReadOnly_Success()
{
IDictionary d = new SqlConnection().RetrieveStatistics();
Assert.False(d.IsReadOnly);
}
public static readonly object[][] RetrieveStatisticsKeyValueData =
{
new object[] { "Foo", 100L },
new object[] { "Foo", null },
new object[] { "Blah", "Blah" },
new object[] { 100, "Value" }
};
[Theory]
[MemberData(nameof(RetrieveStatisticsKeyValueData))]
public void RetrieveStatistics_Add_Success(object key, object value)
{
IDictionary d = new SqlConnection().RetrieveStatistics();
d.Add(key, value);
Assert.True(d.Contains(key));
object v = d[key];
Assert.Same(value, v);
}
[Fact]
public void RetrieveStatistics_Add_ExistingKey_Throws()
{
IDictionary d = new SqlConnection().RetrieveStatistics();
string key = s_retrieveStatisticsKeys[0];
AssertExtensions.Throws<ArgumentException>(null, () => d.Add(key, 100L));
}
[Fact]
public void RetrieveStatistics_Add_NullKey_Throws()
{
IDictionary d = new SqlConnection().RetrieveStatistics();
AssertExtensions.Throws<ArgumentNullException>("key", () => d.Add(null, 100L));
}
[Theory]
[MemberData(nameof(RetrieveStatisticsKeyValueData))]
public void RetrieveStatistics_Setter_Success(object key, object value)
{
IDictionary d = new SqlConnection().RetrieveStatistics();
d[key] = value;
Assert.True(d.Contains(key));
object v = d[key];
Assert.Same(value, v);
}
[Fact]
public void RetrieveStatistics_Setter_ExistingKey_Success()
{
IDictionary d = new SqlConnection().RetrieveStatistics();
string key = s_retrieveStatisticsKeys[0];
d[key] = 100L;
Assert.Equal(100L, d[key]);
}
[Fact]
public void RetrieveStatistics_Setter_NullKey_Throws()
{
IDictionary d = new SqlConnection().RetrieveStatistics();
AssertExtensions.Throws<ArgumentNullException>("key", () => d[null] = 100L);
}
[Fact]
public void RetrieveStatistics_Clear_Success()
{
IDictionary d = new SqlConnection().RetrieveStatistics();
d.Clear();
Assert.Empty(d);
Assert.Equal(0, d.Count);
Assert.Empty(d.Keys);
Assert.Equal(0, d.Keys.Count);
Assert.Empty(d.Values);
Assert.Equal(0, d.Values.Count);
}
[Fact]
public void RetrieveStatistics_Remove_ExistingKey_Success()
{
IDictionary d = new SqlConnection().RetrieveStatistics();
string key = s_retrieveStatisticsKeys[0];
Assert.Equal(s_retrieveStatisticsKeys.Length, d.Count);
Assert.Equal(s_retrieveStatisticsKeys.Length, d.Keys.Count);
Assert.Equal(s_retrieveStatisticsKeys.Length, d.Values.Count);
Assert.True(d.Contains(key));
Assert.NotNull(d[key]);
d.Remove(key);
Assert.Equal(s_retrieveStatisticsKeys.Length - 1, d.Count);
Assert.Equal(s_retrieveStatisticsKeys.Length - 1, d.Keys.Count);
Assert.Equal(s_retrieveStatisticsKeys.Length - 1, d.Values.Count);
Assert.False(d.Contains(key));
Assert.Null(d[key]);
}
[Fact]
public void RetrieveStatistics_Remove_NonExistentKey_Success()
{
IDictionary d = new SqlConnection().RetrieveStatistics();
const string key = "Foo";
Assert.Equal(s_retrieveStatisticsKeys.Length, d.Count);
Assert.Equal(s_retrieveStatisticsKeys.Length, d.Keys.Count);
Assert.Equal(s_retrieveStatisticsKeys.Length, d.Values.Count);
Assert.False(d.Contains(key));
Assert.Null(d[key]);
d.Remove(key);
Assert.Equal(s_retrieveStatisticsKeys.Length, d.Count);
Assert.Equal(s_retrieveStatisticsKeys.Length, d.Keys.Count);
Assert.Equal(s_retrieveStatisticsKeys.Length, d.Values.Count);
Assert.False(d.Contains(key));
Assert.Null(d[key]);
}
[Fact]
public void RetrieveStatistics_Remove_NullKey_Throws()
{
IDictionary d = new SqlConnection().RetrieveStatistics();
AssertExtensions.Throws<ArgumentNullException>("key", () => d.Remove(null));
}
[Fact]
public void RetrieveStatistics_Contains_NullKey_Throws()
{
IDictionary d = new SqlConnection().RetrieveStatistics();
AssertExtensions.Throws<ArgumentNullException>("key", () => d.Contains(null));
}
[Fact]
public void RetrieveStatistics_CopyTo_Success()
{
IDictionary d = new SqlConnection().RetrieveStatistics();
DictionaryEntry[] destination = new DictionaryEntry[d.Count];
d.CopyTo(destination, 0);
int i = 0;
foreach (DictionaryEntry entry in d)
{
Assert.Equal(entry, destination[i]);
i++;
}
}
[Fact]
public void RetrieveStatistics_CopyTo_Throws()
{
IDictionary d = new SqlConnection().RetrieveStatistics();
AssertExtensions.Throws<ArgumentNullException>("array", () => d.CopyTo(null, 0));
AssertExtensions.Throws<ArgumentNullException>("array", () => d.CopyTo(null, -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("arrayIndex", () => d.CopyTo(new DictionaryEntry[20], -1));
AssertExtensions.Throws<ArgumentException>(null, () => d.CopyTo(new DictionaryEntry[20], 18));
AssertExtensions.Throws<ArgumentException>(null, () => d.CopyTo(new DictionaryEntry[20], 1000));
AssertExtensions.Throws<ArgumentException>(null, () => d.CopyTo(new DictionaryEntry[4, 3], 0));
Assert.Throws<InvalidCastException>(() => d.CopyTo(new string[20], 0));
}
[Fact]
public void RetrieveStatistics_IDictionary_GetEnumerator_Success()
{
IDictionary d = new SqlConnection().RetrieveStatistics();
IDictionaryEnumerator e = d.GetEnumerator();
Assert.NotNull(e);
Assert.NotSame(e, d.GetEnumerator());
for (int i = 0; i < 2; i++)
{
Assert.Throws<InvalidOperationException>(() => e.Current);
foreach (string ignored in s_retrieveStatisticsKeys)
{
Assert.True(e.MoveNext());
Assert.NotNull(e.Current);
Assert.IsType<DictionaryEntry>(e.Current);
Assert.NotNull(e.Entry.Key);
Assert.IsType<string>(e.Entry.Key);
Assert.NotNull(e.Entry.Value);
Assert.IsType<long>(e.Entry.Value);
Assert.Equal(e.Current, e.Entry);
Assert.Same(e.Key, e.Entry.Key);
Assert.Same(e.Value, e.Entry.Value);
Assert.Contains(e.Entry.Key, s_retrieveStatisticsKeys);
}
Assert.False(e.MoveNext());
Assert.False(e.MoveNext());
Assert.False(e.MoveNext());
Assert.Throws<InvalidOperationException>(() => e.Current);
e.Reset();
}
}
[Fact]
public void RetrieveStatistics_IEnumerable_GetEnumerator_Success()
{
// Treat the result as IEnumerable instead of IDictionary.
IEnumerable d = new SqlConnection().RetrieveStatistics();
IEnumerator e = d.GetEnumerator();
Assert.NotNull(e);
Assert.NotSame(e, d.GetEnumerator());
for (int i = 0; i < 2; i++)
{
Assert.Throws<InvalidOperationException>(() => e.Current);
foreach (string ignored in s_retrieveStatisticsKeys)
{
Assert.True(e.MoveNext());
Assert.NotNull(e.Current);
// Verify the IEnumerable.GetEnumerator enumerator is yielding DictionaryEntry entries,
// not KeyValuePair entries.
Assert.IsType<DictionaryEntry>(e.Current);
DictionaryEntry entry = (DictionaryEntry)e.Current;
Assert.NotNull(entry.Key);
Assert.IsType<string>(entry.Key);
Assert.NotNull(entry.Value);
Assert.IsType<long>(entry.Value);
Assert.Contains(entry.Key, s_retrieveStatisticsKeys);
}
Assert.False(e.MoveNext());
Assert.False(e.MoveNext());
Assert.False(e.MoveNext());
Assert.Throws<InvalidOperationException>(() => e.Current);
e.Reset();
}
}
[Fact]
public void RetrieveStatistics_GetEnumerator_ModifyCollection_Throws()
{
IDictionary d = new SqlConnection().RetrieveStatistics();
IDictionaryEnumerator e = d.GetEnumerator();
d.Add("Foo", 0L);
Assert.Throws<InvalidOperationException>(() => e.MoveNext());
Assert.Throws<InvalidOperationException>(() => e.Reset());
}
[Fact]
public void RetrieveStatistics_Keys_Success()
{
IDictionary d = new SqlConnection().RetrieveStatistics();
Assert.NotNull(d.Keys);
Assert.Same(d.Keys, d.Keys);
}
[Fact]
public void RetrieveStatistics_Keys_IsSynchronized_Success()
{
IDictionary d = new SqlConnection().RetrieveStatistics();
ICollection c = d.Keys;
Assert.False(c.IsSynchronized);
}
[Fact]
public void RetrieveStatistics_Keys_SyncRoot_Success()
{
IDictionary d = new SqlConnection().RetrieveStatistics();
ICollection c = d.Keys;
Assert.NotNull(c.SyncRoot);
Assert.Same(c.SyncRoot, c.SyncRoot);
}
[Fact]
public void RetrieveStatistics_Keys_CopyTo_ObjectArray_Success()
{
IDictionary d = new SqlConnection().RetrieveStatistics();
ICollection c = d.Keys;
object[] destination = new object[c.Count];
c.CopyTo(destination, 0);
Assert.Equal(c.Cast<object>().ToArray(), destination);
}
[Fact]
public void RetrieveStatistics_Keys_CopyTo_StringArray_Success()
{
IDictionary d = new SqlConnection().RetrieveStatistics();
ICollection c = d.Keys;
string[] destination = new string[c.Count];
c.CopyTo(destination, 0);
Assert.Equal(c.Cast<string>().ToArray(), destination);
}
[Fact]
public void RetrieveStatistics_Keys_CopyTo_Throws()
{
IDictionary d = new SqlConnection().RetrieveStatistics();
ICollection c = d.Keys;
AssertExtensions.Throws<ArgumentNullException>("array", () => c.CopyTo(null, 0));
AssertExtensions.Throws<ArgumentNullException>("array", () => c.CopyTo(null, -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("arrayIndex", () => c.CopyTo(new string[20], -1));
AssertExtensions.Throws<ArgumentException>(null, () => c.CopyTo(new string[20], 18));
AssertExtensions.Throws<ArgumentException>(null, () => c.CopyTo(new string[20], 1000));
AssertExtensions.Throws<ArgumentException>(null, () => c.CopyTo(new string[4, 3], 0));
Assert.Throws<InvalidCastException>(() => c.CopyTo(new Version[20], 0));
}
[Fact]
public void RetrieveStatistics_Keys_GetEnumerator_Success()
{
IDictionary d = new SqlConnection().RetrieveStatistics();
ICollection c = d.Keys;
IEnumerator e = c.GetEnumerator();
Assert.NotNull(e);
Assert.NotSame(e, c.GetEnumerator());
for (int i = 0; i < 2; i++)
{
Assert.Throws<InvalidOperationException>(() => e.Current);
foreach (string ignored in s_retrieveStatisticsKeys)
{
Assert.True(e.MoveNext());
Assert.NotNull(e.Current);
Assert.Contains(e.Current, s_retrieveStatisticsKeys);
}
Assert.False(e.MoveNext());
Assert.False(e.MoveNext());
Assert.False(e.MoveNext());
Assert.Throws<InvalidOperationException>(() => e.Current);
e.Reset();
}
}
[Fact]
public void RetrieveStatistics_Keys_GetEnumerator_ModifyCollection_Throws()
{
IDictionary d = new SqlConnection().RetrieveStatistics();
ICollection c = d.Keys;
IEnumerator e = c.GetEnumerator();
d.Add("Foo", 0L);
Assert.Throws<InvalidOperationException>(() => e.MoveNext());
Assert.Throws<InvalidOperationException>(() => e.Reset());
}
[Fact]
public void RetrieveStatistics_Values_Success()
{
IDictionary d = new SqlConnection().RetrieveStatistics();
Assert.NotNull(d.Values);
Assert.Same(d.Values, d.Values);
}
[Fact]
public void RetrieveStatistics_Values_IsSynchronized_Success()
{
IDictionary d = new SqlConnection().RetrieveStatistics();
ICollection c = d.Values;
Assert.False(c.IsSynchronized);
}
[Fact]
public void RetrieveStatistics_Values_SyncRoot_Success()
{
IDictionary d = new SqlConnection().RetrieveStatistics();
ICollection c = d.Values;
Assert.NotNull(c.SyncRoot);
Assert.Same(c.SyncRoot, c.SyncRoot);
}
[Fact]
public void RetrieveStatistics_Values_CopyTo_ObjectArray_Success()
{
IDictionary d = new SqlConnection().RetrieveStatistics();
ICollection c = d.Values;
object[] destination = new object[c.Count];
c.CopyTo(destination, 0);
Assert.Equal(c.Cast<object>().ToArray(), destination);
}
[Fact]
public void RetrieveStatistics_Values_CopyTo_Int64Array_Success()
{
IDictionary d = new SqlConnection().RetrieveStatistics();
ICollection c = d.Values;
long[] destination = new long[c.Count];
c.CopyTo(destination, 0);
Assert.Equal(c.Cast<long>().ToArray(), destination);
}
[Fact]
public void RetrieveStatistics_Values_CopyTo_Throws()
{
IDictionary d = new SqlConnection().RetrieveStatistics();
ICollection c = d.Values;
AssertExtensions.Throws<ArgumentNullException>("array", () => c.CopyTo(null, 0));
AssertExtensions.Throws<ArgumentNullException>("array", () => c.CopyTo(null, -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("arrayIndex", () => c.CopyTo(new long[20], -1));
AssertExtensions.Throws<ArgumentException>(null, () => c.CopyTo(new long[20], 18));
AssertExtensions.Throws<ArgumentException>(null, () => c.CopyTo(new long[20], 1000));
AssertExtensions.Throws<ArgumentException>(null, () => c.CopyTo(new long[4, 3], 0));
Assert.Throws<InvalidCastException>(() => c.CopyTo(new Version[20], 0));
}
[Fact]
public void RetrieveStatistics_Values_GetEnumerator_Success()
{
IDictionary d = new SqlConnection().RetrieveStatistics();
ICollection c = d.Values;
IEnumerator e = c.GetEnumerator();
Assert.NotNull(e);
Assert.NotSame(e, c.GetEnumerator());
for (int i = 0; i < 2; i++)
{
Assert.Throws<InvalidOperationException>(() => e.Current);
foreach (string ignored in s_retrieveStatisticsKeys)
{
Assert.True(e.MoveNext());
Assert.NotNull(e.Current);
Assert.Equal(0L, e.Current);
}
Assert.False(e.MoveNext());
Assert.False(e.MoveNext());
Assert.False(e.MoveNext());
Assert.Throws<InvalidOperationException>(() => e.Current);
e.Reset();
}
}
[Fact]
public void RetrieveStatistics_Values_GetEnumerator_ModifyCollection_Throws()
{
IDictionary d = new SqlConnection().RetrieveStatistics();
ICollection c = d.Values;
IEnumerator e = c.GetEnumerator();
d.Add("Foo", 0L);
Assert.Throws<InvalidOperationException>(() => e.MoveNext());
Assert.Throws<InvalidOperationException>(() => e.Reset());
}
}
}
| |
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
// ReSharper disable once CheckNamespace
namespace Fluent
{
using Fluent.Internal;
/// <summary>
/// Represent panel with ribbon group.
/// It is automatically adjusting size of controls
/// </summary>
public class RibbonGroupsContainer : Panel, IScrollInfo
{
#region Reduce Order
/// <summary>
/// Gets or sets reduce order of group in the ribbon panel.
/// It must be enumerated with comma from the first to reduce to
/// the last to reduce (use Control.Name as group name in the enum).
/// Enclose in parentheses as (Control.Name) to reduce/enlarge
/// scalable elements in the given group
/// </summary>
public string ReduceOrder
{
get { return (string)this.GetValue(ReduceOrderProperty); }
set { this.SetValue(ReduceOrderProperty, value); }
}
/// <summary>
/// Using a DependencyProperty as the backing store for ReduceOrder.
/// This enables animation, styling, binding, etc...
/// </summary>
public static readonly DependencyProperty ReduceOrderProperty =
DependencyProperty.Register(nameof(ReduceOrder), typeof(string), typeof(RibbonGroupsContainer), new PropertyMetadata(ReduceOrderPropertyChanged));
// handles ReduseOrder property changed
private static void ReduceOrderPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var ribbonPanel = (RibbonGroupsContainer)d;
ribbonPanel.reduceOrder = ((string)e.NewValue).Split(new [] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
ribbonPanel.reduceOrderIndex = ribbonPanel.reduceOrder.Length - 1;
ribbonPanel.InvalidateMeasure();
ribbonPanel.InvalidateArrange();
}
#endregion
#region Fields
private string[] reduceOrder = new string[0];
private int reduceOrderIndex;
#endregion
#region Initialization
/// <summary>
/// Default constructor
/// </summary>
public RibbonGroupsContainer()
{
this.Focusable = false;
}
#endregion
#region Layout Overridings
/// <summary>
/// Returns a collection of the panel's UIElements.
/// </summary>
/// <param name="logicalParent">The logical parent of the collection to be created.</param>
/// <returns>Returns an ordered collection of elements that have the specified logical parent.</returns>
protected override UIElementCollection CreateUIElementCollection(FrameworkElement logicalParent)
{
return new UIElementCollection(this, /*Parent as FrameworkElement*/this);
}
/// <summary>
/// Measures all of the RibbonGroupBox, and resize them appropriately
/// to fit within the available room
/// </summary>
/// <param name="availableSize">The available size that this element can give to child elements.</param>
/// <returns>The size that the groups container determines it needs during
/// layout, based on its calculations of child element sizes.
/// </returns>
protected override Size MeasureOverride(Size availableSize)
{
var desiredSize = this.GetChildrenDesiredSizeIntermediate();
if (this.reduceOrder.Length == 0)
{
this.VerifyScrollData(availableSize.Width, desiredSize.Width);
return desiredSize;
}
// If we have more available space - try to expand groups
while (desiredSize.Width <= availableSize.Width)
{
var hasMoreVariants = this.reduceOrderIndex < this.reduceOrder.Length - 1;
if (hasMoreVariants == false)
{
break;
}
// Increase size of another item
this.reduceOrderIndex++;
this.IncreaseGroupBoxSize(this.reduceOrder[this.reduceOrderIndex]);
desiredSize = this.GetChildrenDesiredSizeIntermediate();
}
// If not enough space - go to next variant
while (desiredSize.Width > availableSize.Width)
{
var hasMoreVariants = this.reduceOrderIndex >= 0;
if (hasMoreVariants == false)
{
break;
}
// Decrease size of another item
this.DecreaseGroupBoxSize(this.reduceOrder[this.reduceOrderIndex]);
this.reduceOrderIndex--;
desiredSize = this.GetChildrenDesiredSizeIntermediate();
}
// Set find values
foreach (var item in this.InternalChildren)
{
var groupBox = item as RibbonGroupBox;
if (groupBox == null)
{
continue;
}
if (groupBox.State != groupBox.StateIntermediate
|| groupBox.Scale != groupBox.ScaleIntermediate)
{
groupBox.SuppressCacheReseting = true;
groupBox.State = groupBox.StateIntermediate;
groupBox.Scale = groupBox.ScaleIntermediate;
groupBox.InvalidateLayout();
groupBox.Measure(new Size(double.PositiveInfinity, availableSize.Height));
groupBox.SuppressCacheReseting = false;
}
// Something wrong with cache?
if (groupBox.DesiredSizeIntermediate != groupBox.DesiredSize)
{
// Reset cache and reinvoke masure
groupBox.ClearCache();
return this.MeasureOverride(availableSize);
}
}
this.VerifyScrollData(availableSize.Width, desiredSize.Width);
return desiredSize;
}
private Size GetChildrenDesiredSizeIntermediate()
{
double width = 0;
double height = 0;
foreach (UIElement child in this.InternalChildren)
{
var groupBox = child as RibbonGroupBox;
if (groupBox == null)
{
continue;
}
var desiredSize = groupBox.DesiredSizeIntermediate;
width += desiredSize.Width;
height = Math.Max(height, desiredSize.Height);
}
return new Size(width, height);
}
// Increase size of the item
private void IncreaseGroupBoxSize(string name)
{
var groupBox = this.FindGroup(name);
var scale = name.StartsWith("(", StringComparison.OrdinalIgnoreCase);
if (groupBox == null)
{
return;
}
if (scale)
{
groupBox.ScaleIntermediate++;
}
else
{
groupBox.StateIntermediate = groupBox.StateIntermediate != RibbonGroupBoxState.Large
? groupBox.StateIntermediate - 1
: RibbonGroupBoxState.Large;
}
}
// Decrease size of the item
private void DecreaseGroupBoxSize(string name)
{
var groupBox = this.FindGroup(name);
var scale = name.StartsWith("(", StringComparison.OrdinalIgnoreCase);
if (groupBox == null)
{
return;
}
if (scale)
{
groupBox.ScaleIntermediate--;
}
else
{
groupBox.StateIntermediate = groupBox.StateIntermediate != RibbonGroupBoxState.Collapsed
? groupBox.StateIntermediate + 1
: groupBox.StateIntermediate;
}
}
private RibbonGroupBox FindGroup(string name)
{
if (name.StartsWith("(", StringComparison.OrdinalIgnoreCase))
{
name = name.Substring(1, name.Length - 2);
}
foreach (FrameworkElement child in this.InternalChildren)
{
if (child.Name == name)
{
return child as RibbonGroupBox;
}
}
return null;
}
/// <summary>
/// When overridden in a derived class, positions child elements and determines
/// a size for a System.Windows.FrameworkElement derived class.
/// </summary>
/// <param name="finalSize">The final area within the parent that this element should use to arrange itself and its children.</param>
/// <returns>The actual size used.</returns>
protected override Size ArrangeOverride(Size finalSize)
{
var finalRect = new Rect(finalSize)
{
X = -this.HorizontalOffset
};
foreach (UIElement item in this.InternalChildren)
{
finalRect.Width = item.DesiredSize.Width;
finalRect.Height = Math.Max(finalSize.Height, item.DesiredSize.Height);
item.Arrange(finalRect);
finalRect.X += item.DesiredSize.Width;
}
return finalSize;
}
#endregion
#region IScrollInfo Members
/// <summary>
/// Gets or sets a System.Windows.Controls.ScrollViewer element that controls scrolling behavior.
/// </summary>
public ScrollViewer ScrollOwner
{
get { return this.ScrollData.ScrollOwner; }
set { this.ScrollData.ScrollOwner = value; }
}
/// <summary>
/// Sets the amount of horizontal offset.
/// </summary>
/// <param name="offset">The degree to which content is horizontally offset from the containing viewport.</param>
public void SetHorizontalOffset(double offset)
{
var newValue = CoerceOffset(ValidateInputOffset(offset, "HorizontalOffset"), this.scrollData.ExtentWidth, this.scrollData.ViewportWidth);
if (DoubleUtil.AreClose(this.ScrollData.OffsetX, newValue) == false)
{
this.scrollData.OffsetX = newValue;
this.InvalidateArrange();
}
}
/// <summary>
/// Gets the horizontal size of the extent.
/// </summary>
public double ExtentWidth
{
get { return this.ScrollData.ExtentWidth; }
}
/// <summary>
/// Gets the horizontal offset of the scrolled content.
/// </summary>
public double HorizontalOffset
{
get { return this.ScrollData.OffsetX; }
}
/// <summary>
/// Gets the horizontal size of the viewport for this content.
/// </summary>
public double ViewportWidth
{
get { return this.ScrollData.ViewportWidth; }
}
/// <summary>
/// Scrolls left within content by one logical unit.
/// </summary>
public void LineLeft()
{
this.SetHorizontalOffset(this.HorizontalOffset - 16.0);
}
/// <summary>
/// Scrolls right within content by one logical unit.
/// </summary>
public void LineRight()
{
this.SetHorizontalOffset(this.HorizontalOffset + 16.0);
}
/// <summary>
/// Forces content to scroll until the coordinate space of a System.Windows.Media.Visual object is visible.
/// This is optimized for horizontal scrolling only
/// </summary>
/// <param name="visual">A System.Windows.Media.Visual that becomes visible.</param>
/// <param name="rectangle">A bounding rectangle that identifies the coordinate space to make visible.</param>
/// <returns>A System.Windows.Rect that is visible.</returns>
public Rect MakeVisible(Visual visual, Rect rectangle)
{
// We can only work on visuals that are us or children.
// An empty rect has no size or position. We can't meaningfully use it.
if (rectangle.IsEmpty
|| visual == null
|| ReferenceEquals(visual, this)
|| !this.IsAncestorOf(visual))
{
return Rect.Empty;
}
// Compute the child's rect relative to (0,0) in our coordinate space.
var childTransform = visual.TransformToAncestor(this);
rectangle = childTransform.TransformBounds(rectangle);
// Initialize the viewport
var viewport = new Rect(this.HorizontalOffset, rectangle.Top, this.ViewportWidth, rectangle.Height);
rectangle.X += viewport.X;
// Compute the offsets required to minimally scroll the child maximally into view.
var minX = ComputeScrollOffsetWithMinimalScroll(viewport.Left, viewport.Right, rectangle.Left, rectangle.Right);
// We have computed the scrolling offsets; scroll to them.
this.SetHorizontalOffset(minX);
// Compute the visible rectangle of the child relative to the viewport.
viewport.X = minX;
rectangle.Intersect(viewport);
rectangle.X -= viewport.X;
// Return the rectangle
return rectangle;
}
private static double ComputeScrollOffsetWithMinimalScroll(
double topView,
double bottomView,
double topChild,
double bottomChild)
{
// # CHILD POSITION CHILD SIZE SCROLL REMEDY
// 1 Above viewport <= viewport Down Align top edge of child & viewport
// 2 Above viewport > viewport Down Align bottom edge of child & viewport
// 3 Below viewport <= viewport Up Align bottom edge of child & viewport
// 4 Below viewport > viewport Up Align top edge of child & viewport
// 5 Entirely within viewport NA No scroll.
// 6 Spanning viewport NA No scroll.
//
// Note: "Above viewport" = childTop above viewportTop, childBottom above viewportBottom
// "Below viewport" = childTop below viewportTop, childBottom below viewportBottom
// These child thus may overlap with the viewport, but will scroll the same direction
/*bool fAbove = DoubleUtil.LessThan(topChild, topView) && DoubleUtil.LessThan(bottomChild, bottomView);
bool fBelow = DoubleUtil.GreaterThan(bottomChild, bottomView) && DoubleUtil.GreaterThan(topChild, topView);*/
var fAbove = (topChild < topView) && (bottomChild < bottomView);
var fBelow = (bottomChild > bottomView) && (topChild > topView);
var fLarger = bottomChild - topChild > bottomView - topView;
// Handle Cases: 1 & 4 above
if ((fAbove && !fLarger)
|| (fBelow && fLarger))
{
return topChild;
}
// Handle Cases: 2 & 3 above
if (fAbove || fBelow)
{
return bottomChild - (bottomView - topView);
}
// Handle cases: 5 & 6 above.
return topView;
}
/// <summary>
/// Not implemented
/// </summary>
public void MouseWheelDown()
{
}
/// <summary>
/// Not implemented
/// </summary>
public void MouseWheelLeft()
{
}
/// <summary>
/// Not implemented
/// </summary>
public void MouseWheelRight()
{
}
/// <summary>
/// Not implemented
/// </summary>
public void MouseWheelUp()
{
}
/// <summary>
/// Not implemented
/// </summary>
public void LineDown()
{
}
/// <summary>
/// Not implemented
/// </summary>
public void LineUp()
{
}
/// <summary>
/// Not implemented
/// </summary>
public void PageDown()
{
}
/// <summary>
/// Not implemented
/// </summary>
public void PageLeft()
{
}
/// <summary>
/// Not implemented
/// </summary>
public void PageRight()
{
}
/// <summary>
/// Not implemented
/// </summary>
public void PageUp()
{
}
/// <summary>
/// Not implemented
/// </summary>
/// <param name="offset"></param>
public void SetVerticalOffset(double offset)
{
}
/// <summary>
/// Gets or sets a value that indicates whether scrolling on the vertical axis is possible.
/// </summary>
public bool CanVerticallyScroll
{
get { return false; }
set { }
}
/// <summary>
/// Gets or sets a value that indicates whether scrolling on the horizontal axis is possible.
/// </summary>
public bool CanHorizontallyScroll
{
get { return true; }
set { }
}
/// <summary>
/// Not implemented
/// </summary>
public double ExtentHeight
{
get { return 0.0; }
}
/// <summary>
/// Not implemented
/// </summary>
public double VerticalOffset
{
get { return 0.0; }
}
/// <summary>
/// Not implemented
/// </summary>
public double ViewportHeight
{
get { return 0.0; }
}
// Gets scroll data info
private ScrollData ScrollData
{
get
{
return this.scrollData ?? (this.scrollData = new ScrollData());
}
}
// Scroll data info
private ScrollData scrollData;
// Validates input offset
private static double ValidateInputOffset(double offset, string parameterName)
{
if (double.IsNaN(offset))
{
throw new ArgumentOutOfRangeException(parameterName);
}
return Math.Max(0.0, offset);
}
// Verifies scrolling data using the passed viewport and extent as newly computed values.
// Checks the X/Y offset and coerces them into the range [0, Extent - ViewportSize]
// If extent, viewport, or the newly coerced offsets are different than the existing offset,
// cachces are updated and InvalidateScrollInfo() is called.
private void VerifyScrollData(double viewportWidth, double extentWidth)
{
var isValid = true;
if (double.IsInfinity(viewportWidth))
{
viewportWidth = extentWidth;
}
var offsetX = CoerceOffset(this.ScrollData.OffsetX, extentWidth, viewportWidth);
isValid &= DoubleUtil.AreClose(viewportWidth, this.ScrollData.ViewportWidth);
isValid &= DoubleUtil.AreClose(extentWidth, this.ScrollData.ExtentWidth);
isValid &= DoubleUtil.AreClose(this.ScrollData.OffsetX, offsetX);
this.ScrollData.ViewportWidth = viewportWidth;
this.ScrollData.ExtentWidth = extentWidth;
this.ScrollData.OffsetX = offsetX;
if (isValid == false)
{
this.ScrollOwner?.InvalidateScrollInfo();
}
}
// Returns an offset coerced into the [0, Extent - Viewport] range.
private static double CoerceOffset(double offset, double extent, double viewport)
{
if (offset > extent - viewport)
{
offset = extent - viewport;
}
if (offset < 0)
{
offset = 0;
}
return offset;
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Editor.UnitTests.Semantics;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Semantics
{
public class SpeculationAnalyzerTests : SpeculationAnalyzerTestsBase
{
[WpfFact]
public void SpeculationAnalyzerDifferentOverloads()
{
Test(@"
class Program
{
void Vain(int arg = 3) { }
void Vain(string arg) { }
void Main()
{
[|Vain(5)|];
}
} ", "Vain(string.Empty)", true);
}
[WpfFact, WorkItem(672396)]
public void SpeculationAnalyzerExtensionMethodExplicitInvocation()
{
Test(@"
static class Program
{
public static void Vain(this int arg) { }
static void Main()
{
[|5.Vain()|];
}
} ", "Vain(5)", false);
}
[WpfFact]
public void SpeculationAnalyzerImplicitBaseClassConversion()
{
Test(@"
using System;
class Program
{
void Main()
{
Exception ex = [|(Exception)new InvalidOperationException()|];
}
} ", "new InvalidOperationException()", false);
}
[WpfFact]
public void SpeculationAnalyzerImplicitNumericConversion()
{
Test(@"
class Program
{
void Main()
{
long i = [|(long)5|];
}
} ", "5", false);
}
[WpfFact]
public void SpeculationAnalyzerImplicitUserConversion()
{
Test(@"
class From
{
public static implicit operator To(From from) { return new To(); }
}
class To { }
class Program
{
void Main()
{
To to = [|(To)new From()|];
}
} ", "new From()", true);
}
[WpfFact]
public void SpeculationAnalyzerExplicitConversion()
{
Test(@"
using System;
class Program
{
void Main()
{
Exception ex1 = new InvalidOperationException();
var ex2 = [|(InvalidOperationException)ex1|];
}
} ", "ex1", true);
}
[WpfFact]
public void SpeculationAnalyzerArrayImplementingNonGenericInterface()
{
Test(@"
using System.Collections;
class Program
{
void Main()
{
var a = new[] { 1, 2, 3 };
[|((IEnumerable)a).GetEnumerator()|];
}
} ", "a.GetEnumerator()", false);
}
[WpfFact]
public void SpeculationAnalyzerVirtualMethodWithBaseConversion()
{
Test(@"
using System;
using System.IO;
class Program
{
void Main()
{
var s = new MemoryStream();
[|((Stream)s).Flush()|];
}
} ", "s.Flush()", false);
}
[WpfFact]
public void SpeculationAnalyzerNonVirtualMethodImplementingInterface()
{
Test(@"
using System;
class Class : IComparable
{
public int CompareTo(object other) { return 1; }
}
class Program
{
static void Main()
{
var c = new Class();
[|((IComparable)c).CompareTo(null)|];
}
} ", "c.CompareTo(null)", true);
}
[WpfFact]
public void SpeculationAnalyzerSealedClassImplementingInterface()
{
Test(@"
using System;
sealed class Class : IComparable
{
public int CompareTo(object other) { return 1; }
}
class Program
{
static void Main()
{
var c = new Class();
[|((IComparable)c).CompareTo(null)|];
}
} ", "c.CompareTo(null)", false);
}
[WpfFact]
public void SpeculationAnalyzerValueTypeImplementingInterface()
{
Test(@"
using System;
class Program
{
void Main()
{
decimal d = 5;
[|((IComparable<decimal>)d).CompareTo(6)|];
}
} ", "d.CompareTo(6)", false);
}
[WpfFact]
public void SpeculationAnalyzerBinaryExpressionIntVsLong()
{
Test(@"
class Program
{
void Main()
{
var r = [|1+1L|];
}
} ", "1+1", true);
}
[WpfFact]
public void SpeculationAnalyzerQueryExpressionSelectType()
{
Test(@"
using System.Linq;
class Program
{
static void Main(string[] args)
{
var items = [|from i in Enumerable.Range(0, 3) select (long)i|];
}
} ", "from i in Enumerable.Range(0, 3) select i", true);
}
[WpfFact]
public void SpeculationAnalyzerQueryExpressionFromType()
{
Test(@"
using System.Linq;
class Program
{
static void Main(string[] args)
{
var items = [|from i in new long[0] select i|];
}
} ", "from i in new int[0] select i", true);
}
[WpfFact]
public void SpeculationAnalyzerQueryExpressionGroupByType()
{
Test(@"
using System.Linq;
class Program
{
static void Main(string[] args)
{
var items = [|from i in Enumerable.Range(0, 3) group (long)i by i|];
}
} ", "from i in Enumerable.Range(0, 3) group i by i", true);
}
[WpfFact]
public void SpeculationAnalyzerQueryExpressionOrderByType()
{
Test(@"
using System.Linq;
class Program
{
static void Main(string[] args)
{
var items = from i in Enumerable.Range(0, 3) orderby [|(long)i|] select i;
}
} ", "i", true);
}
[WpfFact]
public void SpeculationAnalyzerDifferentAttributeConstructors()
{
Test(@"
using System;
class AnAttribute : Attribute
{
public AnAttribute(string a, long b) { }
public AnAttribute(int a, int b) { }
}
class Program
{
[An([|""5""|], 6)]
static void Main() { }
} ", "5", false, "6");
// Note: the answer should have been that the replacement does change semantics (true),
// however to have enough context one must analyze AttributeSyntax instead of separate ExpressionSyntaxes it contains,
// which is not supported in SpeculationAnalyzer, but possible with GetSpeculativeSemanticModel API
}
[WpfFact]
public void SpeculationAnalyzerCollectionInitializers()
{
Test(@"
using System.Collections;
class Collection : IEnumerable
{
public IEnumerator GetEnumerator() { return null; }
public void Add(string s) { }
public void Add(int i) { }
void Main()
{
var c = new Collection { [|""5""|] };
}
} ", "5", true);
}
[WpfFact, WorkItem(1088815)]
public void SpeculationAnalyzerBrokenCode()
{
Test(@"
public interface IRogueAction
{
public string Name { get; private set; }
protected IRogueAction(string name)
{
[|this.Name|] = name;
}
} ", "Name", semanticChanges: false, isBrokenCode: true);
}
protected override SyntaxTree Parse(string text)
{
return SyntaxFactory.ParseSyntaxTree(text);
}
protected override bool IsExpressionNode(SyntaxNode node)
{
return node is ExpressionSyntax;
}
protected override Compilation CreateCompilation(SyntaxTree tree)
{
return CSharpCompilation.Create(
CompilationName,
new[] { tree },
References,
TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(new[] { KeyValuePair.Create("CS0219", ReportDiagnostic.Suppress) }));
}
protected override bool CompilationSucceeded(Compilation compilation, Stream temporaryStream)
{
var langCompilation = compilation;
Func<Diagnostic, bool> isProblem = d => d.Severity >= DiagnosticSeverity.Warning;
return !langCompilation.GetDiagnostics().Any(isProblem) &&
!langCompilation.Emit(temporaryStream).Diagnostics.Any(isProblem);
}
protected override bool ReplacementChangesSemantics(SyntaxNode initialNode, SyntaxNode replacementNode, SemanticModel initialModel)
{
return new SpeculationAnalyzer((ExpressionSyntax)initialNode, (ExpressionSyntax)replacementNode, initialModel, CancellationToken.None).ReplacementChangesSemantics();
}
}
}
| |
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using JetBrains.Annotations;
using Magic.Net.Data;
using Magic.Serialization;
namespace Magic.Net
{
internal sealed class DataPackageHandler : IDataPackageHandler
{
#region Fields
private readonly _ISender _hub;
private readonly ISerializeFormatterCollection _formatterCollection;
private readonly IServiceProvider _serviceProvider;
private Action<object> _commandResult;
#endregion Fields
public DataPackageHandler([NotNull] _ISender hub, [NotNull] IServiceProvider serviceProvider, [NotNull] ISerializeFormatterCollection formatterCollection)
{
if (hub == null) throw new ArgumentNullException("hub");
if (serviceProvider == null) throw new ArgumentNullException("serviceProvider");
if (formatterCollection == null) throw new ArgumentNullException("formatterCollection");
_hub = hub;
_formatterCollection = formatterCollection;
_serviceProvider = serviceProvider;
}
public event Action<object> CommandResult
{
add { _commandResult += value; }
remove { _commandResult += value; }
}
private void HandelReceivedCommandCallBack([NotNull] object state)
{
Trace.WriteLine("HandelReceivedCommandCallBack " + ((RequestState) state).Connetion.RemoteAddress);
InvokeCommand((RequestState) state);
}
private void InvokeCommand([NotNull] RequestState requestState)
{
if (requestState == null) throw new ArgumentNullException("requestState");
var command = (NetCommand) requestState.Package.Data;
object serviceInstance = _serviceProvider.GetService(command.ServiceType);
HubRemoteService hubRemoteService = serviceInstance as HubRemoteService;
if (hubRemoteService != null)
{
hubRemoteService.Connection = requestState.Connetion;
}
object result;
try
{
Trace.WriteLine(string.Format("InvokeCommand {0}.{1}", command.ServiceType.FullName, command.MethodName.Name));
result = command.MethodName.Invoke(serviceInstance, command.ParameterValues);
}
catch (Exception ex)
{
result = ex;
}
// ReSharper disable once OperatorIsCanBeUsed
if (result != null && result.GetType() == typeof (void))
{
result = null;
}
var commandResult = new NetCommandResult(command.Id, result);
var serializeFormat = requestState.Connetion.DefaultSerializeFormat;
var serializeFormatter = _formatterCollection.GetFormatter(serializeFormat);
byte[] buffer = serializeFormatter.Serialize(commandResult);
var package =
new NetDataPackage(
NetDataPackageHeader.CreateNetDataPackageHeader(DataPackageContentType.NetCommandResult, serializeFormat), buffer,
0, buffer.Length);
requestState.Connetion.Send(package.DataSegments().ToArray());
}
internal sealed class CommandResultAwait
{
public CommandResultAwait(Guid id, IDataPackageHandler packageHandler)
{
_id = id;
_packageHandler = packageHandler;
packageHandler.CommandResult += OnCommandResult;
}
public Guid Id
{
get { return _id; }
}
public WaitHandle WaitHandle
{
get { return _onResultEvent.WaitHandle; }
}
public object Result { get; private set; }
private void OnCommandResult(object result)
{
Result = result;
_onResultEvent.Set();
_packageHandler.CommandResult -= OnCommandResult;
}
#region Fields
private readonly Guid _id;
private readonly IDataPackageHandler _packageHandler;
private readonly ManualResetEventSlim _onResultEvent = new ManualResetEventSlim(false);
#endregion Fields
}
#region Implementation of IDataPackageHandler
public void ReceiveCommand([NotNull] RequestState requestState)
{
if (requestState == null) throw new ArgumentNullException("requestState");
while (!ThreadPool.QueueUserWorkItem(HandelReceivedCommandCallBack, requestState))
{
Trace.WriteLine("ThreadPool.QueueUserWorkItem unsuccessful");
Thread.Sleep(50);
}
}
public void ReceiveCommandStream([NotNull] RequestState request)
{
switch (request.Package.PackageContentType)
{
case DataPackageContentType.NetCommand:
ReceiveCommand(request);
break;
case DataPackageContentType.NetCommandResult:
ReceiveCommandResult(request);
break;
case DataPackageContentType.NetObjectStreamInitialize:
InitializeNewObjectStream(request);
break;
case DataPackageContentType.NetObjectStreamData:
HandelNetObjectStreamData(request);
break;
case DataPackageContentType.NetObjectStreamClose:
break;
case DataPackageContentType.ConnectionMetaData:
break;
default:
throw new ArgumentOutOfRangeException();
}
}
private void InitializeNewObjectStream(RequestState request)
{
ObjectStreamInfo info = request.Package.Data as ObjectStreamInfo;
if (info != null && info.State == ObjectStreamState.Creating)
{
//ObjectStream objectStream = _objectStreamManager.Create(request.Connetion.RemoteAddress, info.StreamId);
//info.State = ObjectStreamState.Established;
//ISerializeFormatter serializeFormatter = _objectStreamManager.FormatterCollection.GetFormatter(request.Package.SerializeFormat);
//byte[] bytes = serializeFormatter.Serialize(info);
//NetDataPackage package = new NetDataPackage(NetDataPackageHeader.CreateNetDataPackageHeader(DataPackageContentType.NetObjectStreamInitialize,
// request.Package.SerializeFormat), bytes, 0, bytes.Length);
//request.Connetion.Send(package.DataSegments().ToArray());
}
}
private void HandelNetObjectStreamData(RequestState requestState)
{
NetObjectStreamData streamData = requestState.Package.Data as NetObjectStreamData;
if (streamData != null)
{
ObjectStream objectStream =
_hub.ObjectStreamManager.GetObjectStream(
requestState.Connetion.RemoteAddress.AddPath(streamData.Id.ToString()));
if (objectStream != null)
{
objectStream.Push(streamData.Data);
return;
}
}
Console.Error.WriteLine("Drop " + typeof(NetObjectStreamData) + ", " + typeof(ObjectStream) +" not found.");
}
private void ReceiveCommandResult(RequestState requestState)
{
NetCommandResult commandResult = (NetCommandResult) requestState.Package.Data;
if (_commandResult == null) return;
Delegate[] delegates = _commandResult.GetInvocationList()
.Where(
s => s.Target is CommandResultAwait && ((CommandResultAwait) s.Target).Id == commandResult.CommandId).ToArray();
if (delegates.Length == 0)
{
Debug.WriteLine("DataPackageHandler.ReceiveCommandResult CommandId {0} not found.", commandResult.CommandId);
return;
}
foreach (var subscriber in delegates)
{
CommandResultAwait com = subscriber.Target as CommandResultAwait;
if (com != null && com.Id == commandResult.CommandId)
{
subscriber.DynamicInvoke(commandResult.Result);
}
}
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using BTDB.Collections;
using BTDB.FieldHandler;
using BTDB.IL;
using BTDB.ODBLayer;
using BTDB.StreamLayer;
namespace BTDB.EventStoreLayer;
public class TupleTypeDescriptor : ITypeDescriptor, IPersistTypeDescriptor
{
Type? _type;
StructList<ITypeDescriptor> _itemDescriptors;
Type[]? _itemTypes;
readonly ITypeDescriptorCallbacks _typeSerializers;
string? _name;
public TupleTypeDescriptor(ITypeDescriptorCallbacks typeSerializers, Type type)
{
_typeSerializers = typeSerializers;
_type = type;
}
public TupleTypeDescriptor(ITypeDescriptorCallbacks typeSerializers, ref SpanReader reader,
DescriptorReader nestedDescriptorReader)
{
_typeSerializers = typeSerializers;
var fieldCount = reader.ReadVUInt32();
while (fieldCount-- > 0)
{
_itemDescriptors.Add(nestedDescriptorReader(ref reader));
}
}
TupleTypeDescriptor(ITypeDescriptorCallbacks typeSerializers, ITypeDescriptor[] typeDescriptors)
{
_typeSerializers = typeSerializers;
_itemDescriptors.AddRange(typeDescriptors);
}
public bool Equals(ITypeDescriptor other)
{
return Equals(other, new HashSet<ITypeDescriptor>(ReferenceEqualityComparer<ITypeDescriptor>.Instance));
}
public string Name => _name ??= CreateName();
string CreateName()
{
var sb = new StringBuilder();
sb.Append("Tuple<");
var first = true;
foreach (var itemDescriptor in _itemDescriptors)
{
if (first) first = false;
else
sb.Append(',');
sb.Append(itemDescriptor.Name);
}
sb.Append('>');
return sb.ToString();
}
public bool FinishBuildFromType(ITypeDescriptorFactory factory)
{
_itemTypes = _type!.GetGenericArguments();
_itemDescriptors.Clear();
foreach (var itemType in _itemTypes)
{
var descriptor = factory.Create(itemType);
if (descriptor != null)
{
_itemDescriptors.Add(descriptor);
}
else
{
return false;
}
}
return true;
}
public void BuildHumanReadableFullName(StringBuilder text, HashSet<ITypeDescriptor> stack, uint indent)
{
text.Append("Tuple<");
var first = true;
foreach (var descriptor in _itemDescriptors)
{
if (first) first = false;
else
text.Append(',');
descriptor.BuildHumanReadableFullName(text, stack, indent);
}
text.Append('>');
}
public bool Equals(ITypeDescriptor other, HashSet<ITypeDescriptor> stack)
{
var o = other as TupleTypeDescriptor;
if (o == null) return false;
if (_itemDescriptors.Count != o._itemDescriptors.Count) return false;
for (var i = 0; i < _itemDescriptors.Count; i++)
{
if (!_itemDescriptors[i].Equals(o._itemDescriptors[i], stack)) return false;
}
return true;
}
public Type? GetPreferredType()
{
if (_itemTypes == null)
{
_itemTypes = new Type[_itemDescriptors.Count];
var i = 0;
foreach (var descriptor in _itemDescriptors)
{
_itemTypes[i++] = descriptor.GetPreferredType()!;
}
}
return _type ??= TupleFieldHandler.ValueTupleTypes[_itemTypes.Length - 1].MakeGenericType(_itemTypes);
}
public Type? GetPreferredType(Type targetType)
{
var targetItemTypes = targetType.GetGenericArguments();
for (var i = 0; i < targetItemTypes.Length; i++)
{
targetItemTypes[i] = _itemDescriptors[i].GetPreferredType(targetItemTypes[i]!)!;
}
return targetType.IsValueType
? TupleFieldHandler.ValueTupleTypes[targetItemTypes.Length - 1].MakeGenericType(targetItemTypes)
: TupleFieldHandler.TupleTypes[targetItemTypes.Length - 1].MakeGenericType(targetItemTypes);
}
public bool AnyOpNeedsCtx()
{
return !_itemDescriptors.All(p => p.StoredInline) ||
_itemDescriptors.Any(p => p.AnyOpNeedsCtx());
}
public void GenerateLoad(IILGen ilGenerator, Action<IILGen> pushReader, Action<IILGen> pushCtx,
Action<IILGen> pushDescriptor, Type targetType)
{
if (targetType == typeof(object))
{
var resultLoc = ilGenerator.DeclareLocal(typeof(DynamicTuple), "result");
ilGenerator
.Do(pushDescriptor)
.Castclass(typeof(TupleTypeDescriptor))
.Newobj(typeof(DynamicTuple).GetConstructor(new[] { typeof(TupleTypeDescriptor) })!)
.Stloc(resultLoc);
var idx = 0;
foreach (var descriptor in _itemDescriptors)
{
var idxForCapture = idx;
ilGenerator.Ldloc(resultLoc);
ilGenerator.LdcI4(idx);
descriptor.GenerateLoadEx(ilGenerator, pushReader, pushCtx,
il =>
il.Do(pushDescriptor)
.LdcI4(idxForCapture)
.Callvirt(() => default(ITypeDescriptor).NestedType(0)), typeof(object),
_typeSerializers.ConvertorGenerator);
ilGenerator.Callvirt(() => default(DynamicTuple).SetFieldByIdxFast(0, null));
idx++;
}
ilGenerator
.Ldloc(resultLoc)
.Castclass(typeof(object));
}
else
{
var genericArguments = targetType.GetGenericArguments();
var valueType = TupleFieldHandler.ValueTupleTypes[genericArguments.Length - 1]
.MakeGenericType(genericArguments);
var localResult = ilGenerator.DeclareLocal(valueType);
ilGenerator
.Ldloca(localResult)
.InitObj(valueType);
for (var i = 0; i < genericArguments.Length; i++)
{
if (i >= _itemDescriptors.Count) break;
if (!_typeSerializers.IsSafeToLoad(genericArguments[i]))
{
_itemDescriptors[i].GenerateSkipEx(ilGenerator, pushReader, pushCtx);
continue;
}
ilGenerator.Ldloca(localResult);
_itemDescriptors[i].GenerateLoadEx(ilGenerator, pushReader, pushCtx,
il => il.Do(pushDescriptor).LdcI4(i)
.Callvirt(() => default(ITypeDescriptor).NestedType(0)),
genericArguments[i], _typeSerializers.ConvertorGenerator);
ilGenerator
.Stfld(valueType.GetField(TupleFieldHandler.TupleFieldName[i])!);
}
for (var i = genericArguments.Length; i < _itemDescriptors.Count; i++)
{
_itemDescriptors[i].GenerateSkipEx(ilGenerator, pushReader, pushCtx);
}
if (targetType.IsValueType)
{
ilGenerator.Ldloc(localResult);
}
else
{
for (var i = 0; i < genericArguments.Length; i++)
{
ilGenerator.Ldloca(localResult).Ldfld(valueType.GetField(TupleFieldHandler.TupleFieldName[i])!);
}
ilGenerator.Newobj(targetType.GetConstructor(genericArguments)!);
}
}
}
public void GenerateSkip(IILGen ilGenerator, Action<IILGen> pushReader, Action<IILGen> pushCtx)
{
foreach (var descriptor in _itemDescriptors)
{
descriptor.GenerateSkipEx(ilGenerator, pushReader, pushCtx);
}
}
public class DynamicTuple : IDynamicMetaObjectProvider, IKnowDescriptor,
IEnumerable<object>
{
readonly TupleTypeDescriptor _ownerDescriptor;
readonly object[] _fieldValues;
public DynamicTuple(TupleTypeDescriptor ownerDescriptor)
{
_ownerDescriptor = ownerDescriptor;
_fieldValues = new object[_ownerDescriptor._itemDescriptors.Count];
}
DynamicMetaObject IDynamicMetaObjectProvider.GetMetaObject(Expression parameter)
{
return new DynamicDictionaryMetaObject(parameter, this);
}
public void SetFieldByIdxFast(int idx, object value)
{
_fieldValues[idx] = value;
}
public void SetFieldByIdx(int idx, string fieldName, TupleTypeDescriptor descriptor, object value)
{
if (_ownerDescriptor == descriptor)
{
if (idx < 0)
ThrowMemberAccessException(fieldName);
_fieldValues[idx] = value;
return;
}
var realIndex = _ownerDescriptor.FindFieldIndexWithThrow(fieldName);
_fieldValues[realIndex] = value;
}
public object GetFieldByIdx(int idx, string fieldName, TupleTypeDescriptor descriptor)
{
if (_ownerDescriptor == descriptor)
{
if (idx < 0)
ThrowMemberAccessException(fieldName);
return _fieldValues[idx];
}
var realIndex = _ownerDescriptor.FindFieldIndexWithThrow(fieldName);
return _fieldValues[realIndex];
}
internal void ThrowMemberAccessException(string fieldName)
{
throw new MemberAccessException($"{_ownerDescriptor.Name} does not have member {fieldName}");
}
class DynamicDictionaryMetaObject : DynamicMetaObject
{
internal DynamicDictionaryMetaObject(Expression parameter, DynamicTuple value)
: base(parameter, BindingRestrictions.Empty, value)
{
}
public override DynamicMetaObject BindSetMember(SetMemberBinder binder, DynamicMetaObject value)
{
var descriptor = ((DynamicTuple)Value)!._ownerDescriptor;
var idx = TupleFieldHandler.TupleFieldName.IndexOf(binder.Name);
return new(Expression.Call(Expression.Convert(Expression, LimitType),
typeof(DynamicTuple).GetMethod(nameof(SetFieldByIdx))!,
Expression.Constant(idx),
Expression.Constant(binder.Name),
Expression.Constant(descriptor),
Expression.Convert(value.Expression, typeof(object))),
BindingRestrictions.GetTypeRestriction(Expression, LimitType));
}
public override DynamicMetaObject BindGetMember(GetMemberBinder binder)
{
var descriptor = ((DynamicTuple)Value)!._ownerDescriptor;
var idx = TupleFieldHandler.TupleFieldName.IndexOf(binder.Name);
return new(Expression.Call(Expression.Convert(Expression, LimitType),
typeof(DynamicTuple).GetMethod(nameof(GetFieldByIdx))!,
Expression.Constant(idx),
Expression.Constant(binder.Name),
Expression.Constant(descriptor)),
BindingRestrictions.GetTypeRestriction(Expression, LimitType));
}
public override IEnumerable<string> GetDynamicMemberNames()
{
var descriptor = ((DynamicTuple)Value)!._ownerDescriptor;
return TupleFieldHandler.TupleFieldName.Take((int)descriptor._itemDescriptors.Count);
}
}
public IEnumerator<object> GetEnumerator()
{
foreach (var value in _fieldValues)
{
yield return value;
}
}
public override string ToString()
{
var sb = new StringBuilder();
var idx = 0;
sb.Append('(');
foreach (var item in _fieldValues)
{
if (idx > 0) sb.Append(", ");
sb.AppendJsonLike(item);
idx++;
}
sb.Append(')');
return sb.ToString();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public ITypeDescriptor GetDescriptor()
{
return _ownerDescriptor;
}
}
int FindFieldIndexWithThrow(string fieldName)
{
var idx = TupleFieldHandler.TupleFieldName.IndexOf(fieldName);
if (idx < 0 || idx >= _itemDescriptors.Count)
throw new MemberAccessException($"{Name} does not have member {fieldName}");
return idx;
}
public ITypeNewDescriptorGenerator? BuildNewDescriptorGenerator()
{
if (_itemDescriptors.All(d => d.Sealed)) return null;
return new TypeNewDescriptorGenerator(this);
}
class TypeNewDescriptorGenerator : ITypeNewDescriptorGenerator
{
readonly TupleTypeDescriptor _objectTypeDescriptor;
public TypeNewDescriptorGenerator(TupleTypeDescriptor objectTypeDescriptor)
{
_objectTypeDescriptor = objectTypeDescriptor;
}
public void GenerateTypeIterator(IILGen ilGenerator, Action<IILGen> pushObj, Action<IILGen> pushCtx,
Type type)
{
var idx = -1;
foreach (var descriptor in _objectTypeDescriptor._itemDescriptors)
{
idx++;
if (descriptor.Sealed) continue;
ilGenerator
.Do(pushCtx)
.Do(pushObj);
if (type.IsValueType)
{
ilGenerator.Ldfld(type.GetField(TupleFieldHandler.TupleFieldName[idx])!);
}
else
{
ilGenerator.Callvirt(type.GetProperty(TupleFieldHandler.TupleFieldName[idx])!.GetGetMethod()!);
}
ilGenerator.Callvirt(typeof(IDescriptorSerializerLiteContext).GetMethod(
nameof(IDescriptorSerializerLiteContext.StoreNewDescriptors))!);
}
}
}
public ITypeDescriptor? NestedType(int index)
{
return index < _itemDescriptors.Count ? _itemDescriptors[index] : null;
}
public void MapNestedTypes(Func<ITypeDescriptor, ITypeDescriptor> map)
{
for (var index = 0; index < _itemDescriptors.Count; index++)
{
_itemDescriptors[index] = map(_itemDescriptors[index]);
}
}
public bool Sealed => _itemDescriptors.All(d => d.Sealed);
public bool StoredInline => true;
public bool LoadNeedsHelpWithConversion => false;
public void ClearMappingToType()
{
_itemTypes = null;
_type = null;
}
public bool ContainsField(string name)
{
return (uint)TupleFieldHandler.TupleFieldName.IndexOf(name) < _itemDescriptors.Count;
}
public IEnumerable<KeyValuePair<string, ITypeDescriptor>> Fields => _itemDescriptors.Select((d, i) =>
new KeyValuePair<string, ITypeDescriptor>(TupleFieldHandler.TupleFieldName[i], d));
public void Persist(ref SpanWriter writer, DescriptorWriter nestedDescriptorWriter)
{
writer.WriteVUInt32(_itemDescriptors.Count);
foreach (var descriptor in _itemDescriptors)
{
nestedDescriptorWriter(ref writer, descriptor);
}
}
public void GenerateSave(IILGen ilGenerator, Action<IILGen> pushWriter, Action<IILGen> pushCtx,
Action<IILGen> pushValue, Type valueType)
{
var locValue = ilGenerator.DeclareLocal(valueType, "value");
ilGenerator
.Do(pushValue)
.Stloc(locValue);
var itemTypes = valueType.GetGenericArguments();
var idx = -1;
foreach (var typeDescriptor in _itemDescriptors)
{
idx++;
if (valueType.IsValueType)
{
typeDescriptor.GenerateSaveEx(ilGenerator, pushWriter, pushCtx,
il => il.Ldloc(locValue).Ldfld(valueType.GetField(TupleFieldHandler.TupleFieldName[idx])),
itemTypes[idx]);
}
else
{
typeDescriptor.GenerateSaveEx(ilGenerator, pushWriter, pushCtx,
il => il.Ldloc(locValue).Callvirt(valueType.GetProperty(TupleFieldHandler.TupleFieldName[idx])
.GetGetMethod()), itemTypes[idx]);
}
}
}
public ITypeDescriptor CloneAndMapNestedTypes(ITypeDescriptorCallbacks typeSerializers,
Func<ITypeDescriptor, ITypeDescriptor> map)
{
var tds = new ITypeDescriptor[_itemDescriptors.Count];
for (var i = 0; i < _itemDescriptors.Count; i++)
{
tds[i] = map(_itemDescriptors[i]);
}
if (typeSerializers == _typeSerializers && tds.SequenceEqual(_itemDescriptors))
return this;
var res = new TupleTypeDescriptor(typeSerializers, tds);
return res;
}
}
| |
#if !UNITY_WINRT || UNITY_EDITOR || (UNITY_WP8 && !UNITY_WP_8_1)
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Newtonsoft.Json.Utilities;
using Newtonsoft.Json.Linq;
using System.Globalization;
namespace Newtonsoft.Json
{
/// <summary>
/// Specifies the state of the <see cref="JsonWriter"/>.
/// </summary>
public enum WriteState
{
/// <summary>
/// An exception has been thrown, which has left the <see cref="JsonWriter"/> in an invalid state.
/// You may call the <see cref="JsonWriter.Close"/> method to put the <see cref="JsonWriter"/> in the <c>Closed</c> state.
/// Any other <see cref="JsonWriter"/> method calls results in an <see cref="InvalidOperationException"/> being thrown.
/// </summary>
Error,
/// <summary>
/// The <see cref="JsonWriter.Close"/> method has been called.
/// </summary>
Closed,
/// <summary>
/// An object is being written.
/// </summary>
Object,
/// <summary>
/// A array is being written.
/// </summary>
Array,
/// <summary>
/// A constructor is being written.
/// </summary>
Constructor,
/// <summary>
/// A property is being written.
/// </summary>
Property,
/// <summary>
/// A write method has not been called.
/// </summary>
Start
}
/// <summary>
/// Specifies formatting options for the <see cref="JsonTextWriter"/>.
/// </summary>
public enum Formatting
{
/// <summary>
/// No special formatting is applied. This is the default.
/// </summary>
None,
/// <summary>
/// Causes child objects to be indented according to the <see cref="JsonTextWriter.Indentation"/> and <see cref="JsonTextWriter.IndentChar"/> settings.
/// </summary>
Indented
}
/// <summary>
/// Represents a writer that provides a fast, non-cached, forward-only way of generating Json data.
/// </summary>
public abstract class JsonWriter : IDisposable
{
private enum State
{
Start,
Property,
ObjectStart,
Object,
ArrayStart,
Array,
ConstructorStart,
Constructor,
Bytes,
Closed,
Error
}
// array that gives a new state based on the current state an the token being written
private static readonly State[][] stateArray = new[] {
// Start PropertyName ObjectStart Object ArrayStart Array ConstructorStart Constructor Closed Error
//
/* None */new[]{ State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error },
/* StartObject */new[]{ State.ObjectStart, State.ObjectStart, State.Error, State.Error, State.ObjectStart, State.ObjectStart, State.ObjectStart, State.ObjectStart, State.Error, State.Error },
/* StartArray */new[]{ State.ArrayStart, State.ArrayStart, State.Error, State.Error, State.ArrayStart, State.ArrayStart, State.ArrayStart, State.ArrayStart, State.Error, State.Error },
/* StartConstructor */new[]{ State.ConstructorStart, State.ConstructorStart, State.Error, State.Error, State.ConstructorStart, State.ConstructorStart, State.ConstructorStart, State.ConstructorStart, State.Error, State.Error },
/* StartProperty */new[]{ State.Property, State.Error, State.Property, State.Property, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error },
/* Comment */new[]{ State.Start, State.Property, State.ObjectStart, State.Object, State.ArrayStart, State.Array, State.Constructor, State.Constructor, State.Error, State.Error },
/* Raw */new[]{ State.Start, State.Property, State.ObjectStart, State.Object, State.ArrayStart, State.Array, State.Constructor, State.Constructor, State.Error, State.Error },
/* Value */new[]{ State.Start, State.Object, State.Error, State.Error, State.Array, State.Array, State.Constructor, State.Constructor, State.Error, State.Error },
};
private int _top;
private readonly List<JTokenType> _stack;
private State _currentState;
private Formatting _formatting;
/// <summary>
/// Gets or sets a value indicating whether the underlying stream or
/// <see cref="TextReader"/> should be closed when the writer is closed.
/// </summary>
/// <value>
/// true to close the underlying stream or <see cref="TextReader"/> when
/// the writer is closed; otherwise false. The default is true.
/// </value>
public bool CloseOutput { get; set; }
/// <summary>
/// Gets the top.
/// </summary>
/// <value>The top.</value>
protected internal int Top
{
get { return _top; }
}
/// <summary>
/// Gets the state of the writer.
/// </summary>
public WriteState WriteState
{
get
{
switch (_currentState)
{
case State.Error:
return WriteState.Error;
case State.Closed:
return WriteState.Closed;
case State.Object:
case State.ObjectStart:
return WriteState.Object;
case State.Array:
case State.ArrayStart:
return WriteState.Array;
case State.Constructor:
case State.ConstructorStart:
return WriteState.Constructor;
case State.Property:
return WriteState.Property;
case State.Start:
return WriteState.Start;
default:
throw new JsonWriterException("Invalid state: " + _currentState);
}
}
}
/// <summary>
/// Indicates how the output is formatted.
/// </summary>
public Formatting Formatting
{
get { return _formatting; }
set { _formatting = value; }
}
/// <summary>
/// Creates an instance of the <c>JsonWriter</c> class.
/// </summary>
protected JsonWriter()
{
_stack = new List<JTokenType>(8);
_stack.Add(JTokenType.None);
_currentState = State.Start;
_formatting = Formatting.None;
CloseOutput = true;
}
private void Push(JTokenType value)
{
_top++;
if (_stack.Count <= _top)
_stack.Add(value);
else
_stack[_top] = value;
}
private JTokenType Pop()
{
JTokenType value = Peek();
_top--;
return value;
}
private JTokenType Peek()
{
return _stack[_top];
}
/// <summary>
/// Flushes whatever is in the buffer to the underlying streams and also flushes the underlying stream.
/// </summary>
public abstract void Flush();
/// <summary>
/// Closes this stream and the underlying stream.
/// </summary>
public virtual void Close()
{
AutoCompleteAll();
}
/// <summary>
/// Writes the beginning of a Json object.
/// </summary>
public virtual void WriteStartObject()
{
AutoComplete(JsonToken.StartObject);
Push(JTokenType.Object);
}
/// <summary>
/// Writes the end of a Json object.
/// </summary>
public virtual void WriteEndObject()
{
AutoCompleteClose(JsonToken.EndObject);
}
/// <summary>
/// Writes the beginning of a Json array.
/// </summary>
public virtual void WriteStartArray()
{
AutoComplete(JsonToken.StartArray);
Push(JTokenType.Array);
}
/// <summary>
/// Writes the end of an array.
/// </summary>
public virtual void WriteEndArray()
{
AutoCompleteClose(JsonToken.EndArray);
}
/// <summary>
/// Writes the start of a constructor with the given name.
/// </summary>
/// <param name="name">The name of the constructor.</param>
public virtual void WriteStartConstructor(string name)
{
AutoComplete(JsonToken.StartConstructor);
Push(JTokenType.Constructor);
}
/// <summary>
/// Writes the end constructor.
/// </summary>
public virtual void WriteEndConstructor()
{
AutoCompleteClose(JsonToken.EndConstructor);
}
/// <summary>
/// Writes the property name of a name/value pair on a Json object.
/// </summary>
/// <param name="name">The name of the property.</param>
public virtual void WritePropertyName(string name)
{
AutoComplete(JsonToken.PropertyName);
}
/// <summary>
/// Writes the end of the current Json object or array.
/// </summary>
public virtual void WriteEnd()
{
WriteEnd(Peek());
}
/// <summary>
/// Writes the current <see cref="JsonReader"/> token.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read the token from.</param>
public void WriteToken(JsonReader reader)
{
ValidationUtils.ArgumentNotNull(reader, "reader");
int initialDepth;
if (reader.TokenType == JsonToken.None)
initialDepth = -1;
else if (!IsStartToken(reader.TokenType))
initialDepth = reader.Depth + 1;
else
initialDepth = reader.Depth;
WriteToken(reader, initialDepth);
}
internal void WriteToken(JsonReader reader, int initialDepth)
{
do
{
switch (reader.TokenType)
{
case JsonToken.None:
// read to next
break;
case JsonToken.StartObject:
WriteStartObject();
break;
case JsonToken.StartArray:
WriteStartArray();
break;
case JsonToken.StartConstructor:
string constructorName = reader.Value.ToString();
// write a JValue date when the constructor is for a date
if (string.Compare(constructorName, "Date", StringComparison.Ordinal) == 0)
WriteConstructorDate(reader);
else
WriteStartConstructor(reader.Value.ToString());
break;
case JsonToken.PropertyName:
WritePropertyName(reader.Value.ToString());
break;
case JsonToken.Comment:
WriteComment(reader.Value.ToString());
break;
case JsonToken.Integer:
WriteValue(Convert.ToInt64(reader.Value, CultureInfo.InvariantCulture));
break;
case JsonToken.Float:
WriteValue(Convert.ToDouble(reader.Value, CultureInfo.InvariantCulture));
break;
case JsonToken.String:
WriteValue(reader.Value.ToString());
break;
case JsonToken.Boolean:
WriteValue(Convert.ToBoolean(reader.Value, CultureInfo.InvariantCulture));
break;
case JsonToken.Null:
WriteNull();
break;
case JsonToken.Undefined:
WriteUndefined();
break;
case JsonToken.EndObject:
WriteEndObject();
break;
case JsonToken.EndArray:
WriteEndArray();
break;
case JsonToken.EndConstructor:
WriteEndConstructor();
break;
case JsonToken.Date:
WriteValue((DateTime)reader.Value);
break;
case JsonToken.Raw:
WriteRawValue((string)reader.Value);
break;
case JsonToken.Bytes:
WriteValue((byte[])reader.Value);
break;
default:
throw MiscellaneousUtils.CreateArgumentOutOfRangeException("TokenType", reader.TokenType, "Unexpected token type.");
}
}
while (
// stop if we have reached the end of the token being read
initialDepth - 1 < reader.Depth - (IsEndToken(reader.TokenType) ? 1 : 0)
&& reader.Read());
}
private void WriteConstructorDate(JsonReader reader)
{
if (!reader.Read())
throw new Exception("Unexpected end while reading date constructor.");
if (reader.TokenType != JsonToken.Integer)
throw new Exception("Unexpected token while reading date constructor. Expected Integer, got " + reader.TokenType);
long ticks = (long)reader.Value;
DateTime date = JsonConvert.ConvertJavaScriptTicksToDateTime(ticks);
if (!reader.Read())
throw new Exception("Unexpected end while reading date constructor.");
if (reader.TokenType != JsonToken.EndConstructor)
throw new Exception("Unexpected token while reading date constructor. Expected EndConstructor, got " + reader.TokenType);
WriteValue(date);
}
private bool IsEndToken(JsonToken token)
{
switch (token)
{
case JsonToken.EndObject:
case JsonToken.EndArray:
case JsonToken.EndConstructor:
return true;
default:
return false;
}
}
private bool IsStartToken(JsonToken token)
{
switch (token)
{
case JsonToken.StartObject:
case JsonToken.StartArray:
case JsonToken.StartConstructor:
return true;
default:
return false;
}
}
private void WriteEnd(JTokenType type)
{
switch (type)
{
case JTokenType.Object:
WriteEndObject();
break;
case JTokenType.Array:
WriteEndArray();
break;
case JTokenType.Constructor:
WriteEndConstructor();
break;
default:
throw new JsonWriterException("Unexpected type when writing end: " + type);
}
}
private void AutoCompleteAll()
{
while (_top > 0)
{
WriteEnd();
}
}
private JTokenType GetTypeForCloseToken(JsonToken token)
{
switch (token)
{
case JsonToken.EndObject:
return JTokenType.Object;
case JsonToken.EndArray:
return JTokenType.Array;
case JsonToken.EndConstructor:
return JTokenType.Constructor;
default:
throw new JsonWriterException("No type for token: " + token);
}
}
private JsonToken GetCloseTokenForType(JTokenType type)
{
switch (type)
{
case JTokenType.Object:
return JsonToken.EndObject;
case JTokenType.Array:
return JsonToken.EndArray;
case JTokenType.Constructor:
return JsonToken.EndConstructor;
default:
throw new JsonWriterException("No close token for type: " + type);
}
}
private void AutoCompleteClose(JsonToken tokenBeingClosed)
{
// write closing symbol and calculate new state
int levelsToComplete = 0;
for (int i = 0; i < _top; i++)
{
int currentLevel = _top - i;
if (_stack[currentLevel] == GetTypeForCloseToken(tokenBeingClosed))
{
levelsToComplete = i + 1;
break;
}
}
if (levelsToComplete == 0)
throw new JsonWriterException("No token to close.");
for (int i = 0; i < levelsToComplete; i++)
{
JsonToken token = GetCloseTokenForType(Pop());
if (_currentState != State.ObjectStart && _currentState != State.ArrayStart)
WriteIndent();
WriteEnd(token);
}
JTokenType currentLevelType = Peek();
switch (currentLevelType)
{
case JTokenType.Object:
_currentState = State.Object;
break;
case JTokenType.Array:
_currentState = State.Array;
break;
case JTokenType.Constructor:
_currentState = State.Array;
break;
case JTokenType.None:
_currentState = State.Start;
break;
default:
throw new JsonWriterException("Unknown JsonType: " + currentLevelType);
}
}
/// <summary>
/// Writes the specified end token.
/// </summary>
/// <param name="token">The end token to write.</param>
protected virtual void WriteEnd(JsonToken token)
{
}
/// <summary>
/// Writes indent characters.
/// </summary>
protected virtual void WriteIndent()
{
}
/// <summary>
/// Writes the JSON value delimiter.
/// </summary>
protected virtual void WriteValueDelimiter()
{
}
/// <summary>
/// Writes an indent space.
/// </summary>
protected virtual void WriteIndentSpace()
{
}
internal void AutoComplete(JsonToken tokenBeingWritten)
{
int token;
switch (tokenBeingWritten)
{
default:
token = (int)tokenBeingWritten;
break;
case JsonToken.Integer:
case JsonToken.Float:
case JsonToken.String:
case JsonToken.Boolean:
case JsonToken.Null:
case JsonToken.Undefined:
case JsonToken.Date:
case JsonToken.Bytes:
// a value is being written
token = 7;
break;
}
// gets new state based on the current state and what is being written
State newState = stateArray[token][(int)_currentState];
if (newState == State.Error)
throw new JsonWriterException("Token {0} in state {1} would result in an invalid JavaScript object.".FormatWith(CultureInfo.InvariantCulture, tokenBeingWritten.ToString(), _currentState.ToString()));
if ((_currentState == State.Object || _currentState == State.Array || _currentState == State.Constructor) && tokenBeingWritten != JsonToken.Comment)
{
WriteValueDelimiter();
}
else if (_currentState == State.Property)
{
if (_formatting == Formatting.Indented)
WriteIndentSpace();
}
WriteState writeState = WriteState;
// don't indent a property when it is the first token to be written (i.e. at the start)
if ((tokenBeingWritten == JsonToken.PropertyName && writeState != WriteState.Start) ||
writeState == WriteState.Array || writeState == WriteState.Constructor)
{
WriteIndent();
}
_currentState = newState;
}
#region WriteValue methods
/// <summary>
/// Writes a null value.
/// </summary>
public virtual void WriteNull()
{
AutoComplete(JsonToken.Null);
}
/// <summary>
/// Writes an undefined value.
/// </summary>
public virtual void WriteUndefined()
{
AutoComplete(JsonToken.Undefined);
}
/// <summary>
/// Writes raw JSON without changing the writer's state.
/// </summary>
/// <param name="json">The raw JSON to write.</param>
public virtual void WriteRaw(string json)
{
}
/// <summary>
/// Writes raw JSON where a value is expected and updates the writer's state.
/// </summary>
/// <param name="json">The raw JSON to write.</param>
public virtual void WriteRawValue(string json)
{
// hack. want writer to change state as if a value had been written
AutoComplete(JsonToken.Undefined);
WriteRaw(json);
}
/// <summary>
/// Writes a <see cref="String"/> value.
/// </summary>
/// <param name="value">The <see cref="String"/> value to write.</param>
public virtual void WriteValue(string value)
{
AutoComplete(JsonToken.String);
}
/// <summary>
/// Writes a <see cref="Int32"/> value.
/// </summary>
/// <param name="value">The <see cref="Int32"/> value to write.</param>
public virtual void WriteValue(int value)
{
AutoComplete(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="UInt32"/> value.
/// </summary>
/// <param name="value">The <see cref="UInt32"/> value to write.</param>
//
public virtual void WriteValue(uint value)
{
AutoComplete(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Int64"/> value.
/// </summary>
/// <param name="value">The <see cref="Int64"/> value to write.</param>
public virtual void WriteValue(long value)
{
AutoComplete(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="UInt64"/> value.
/// </summary>
/// <param name="value">The <see cref="UInt64"/> value to write.</param>
//
public virtual void WriteValue(ulong value)
{
AutoComplete(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Single"/> value.
/// </summary>
/// <param name="value">The <see cref="Single"/> value to write.</param>
public virtual void WriteValue(float value)
{
AutoComplete(JsonToken.Float);
}
/// <summary>
/// Writes a <see cref="Double"/> value.
/// </summary>
/// <param name="value">The <see cref="Double"/> value to write.</param>
public virtual void WriteValue(double value)
{
AutoComplete(JsonToken.Float);
}
/// <summary>
/// Writes a <see cref="Boolean"/> value.
/// </summary>
/// <param name="value">The <see cref="Boolean"/> value to write.</param>
public virtual void WriteValue(bool value)
{
AutoComplete(JsonToken.Boolean);
}
/// <summary>
/// Writes a <see cref="Int16"/> value.
/// </summary>
/// <param name="value">The <see cref="Int16"/> value to write.</param>
public virtual void WriteValue(short value)
{
AutoComplete(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="UInt16"/> value.
/// </summary>
/// <param name="value">The <see cref="UInt16"/> value to write.</param>
//
public virtual void WriteValue(ushort value)
{
AutoComplete(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Char"/> value.
/// </summary>
/// <param name="value">The <see cref="Char"/> value to write.</param>
public virtual void WriteValue(char value)
{
AutoComplete(JsonToken.String);
}
/// <summary>
/// Writes a <see cref="Byte"/> value.
/// </summary>
/// <param name="value">The <see cref="Byte"/> value to write.</param>
public virtual void WriteValue(byte value)
{
AutoComplete(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="SByte"/> value.
/// </summary>
/// <param name="value">The <see cref="SByte"/> value to write.</param>
//
public virtual void WriteValue(sbyte value)
{
AutoComplete(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Decimal"/> value.
/// </summary>
/// <param name="value">The <see cref="Decimal"/> value to write.</param>
public virtual void WriteValue(decimal value)
{
AutoComplete(JsonToken.Float);
}
/// <summary>
/// Writes a <see cref="DateTime"/> value.
/// </summary>
/// <param name="value">The <see cref="DateTime"/> value to write.</param>
public virtual void WriteValue(DateTime value)
{
AutoComplete(JsonToken.Date);
}
/// <summary>
/// Writes a <see cref="DateTimeOffset"/> value.
/// </summary>
/// <param name="value">The <see cref="DateTimeOffset"/> value to write.</param>
public virtual void WriteValue(DateTimeOffset value)
{
AutoComplete(JsonToken.Date);
}
/// <summary>
/// Writes a <see cref="Guid"/> value.
/// </summary>
/// <param name="value">The <see cref="Guid"/> value to write.</param>
public virtual void WriteValue(Guid value)
{
AutoComplete(JsonToken.String);
}
/// <summary>
/// Writes a <see cref="TimeSpan"/> value.
/// </summary>
/// <param name="value">The <see cref="TimeSpan"/> value to write.</param>
public virtual void WriteValue(TimeSpan value)
{
AutoComplete(JsonToken.String);
}
/// <summary>
/// Writes a <see cref="Nullable{Int32}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Int32}"/> value to write.</param>
public virtual void WriteValue(int? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{UInt32}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{UInt32}"/> value to write.</param>
//
public virtual void WriteValue(uint? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Int64}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Int64}"/> value to write.</param>
public virtual void WriteValue(long? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{UInt64}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{UInt64}"/> value to write.</param>
//
public virtual void WriteValue(ulong? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Single}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Single}"/> value to write.</param>
public virtual void WriteValue(float? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Double}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Double}"/> value to write.</param>
public virtual void WriteValue(double? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Boolean}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Boolean}"/> value to write.</param>
public virtual void WriteValue(bool? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Int16}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Int16}"/> value to write.</param>
public virtual void WriteValue(short? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{UInt16}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{UInt16}"/> value to write.</param>
//
public virtual void WriteValue(ushort? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Char}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Char}"/> value to write.</param>
public virtual void WriteValue(char? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Byte}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Byte}"/> value to write.</param>
public virtual void WriteValue(byte? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{SByte}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{SByte}"/> value to write.</param>
//
public virtual void WriteValue(sbyte? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Decimal}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Decimal}"/> value to write.</param>
public virtual void WriteValue(decimal? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{DateTime}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{DateTime}"/> value to write.</param>
public virtual void WriteValue(DateTime? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{DateTimeOffset}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{DateTimeOffset}"/> value to write.</param>
public virtual void WriteValue(DateTimeOffset? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Guid}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Guid}"/> value to write.</param>
public virtual void WriteValue(Guid? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{TimeSpan}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{TimeSpan}"/> value to write.</param>
public virtual void WriteValue(TimeSpan? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="T:Byte[]"/> value.
/// </summary>
/// <param name="value">The <see cref="T:Byte[]"/> value to write.</param>
public virtual void WriteValue(byte[] value)
{
if (value == null)
WriteNull();
else
AutoComplete(JsonToken.Bytes);
}
/// <summary>
/// Writes a <see cref="Uri"/> value.
/// </summary>
/// <param name="value">The <see cref="Uri"/> value to write.</param>
public virtual void WriteValue(Uri value)
{
if (value == null)
WriteNull();
else
AutoComplete(JsonToken.String);
}
/// <summary>
/// Writes a <see cref="Object"/> value.
/// An error will raised if the value cannot be written as a single JSON token.
/// </summary>
/// <param name="value">The <see cref="Object"/> value to write.</param>
public virtual void WriteValue(object value)
{
if (value == null)
{
WriteNull();
return;
}
else if (value is IConvertible)
{
IConvertible convertible = value as IConvertible;
switch (convertible.GetTypeCode())
{
case TypeCode.String:
WriteValue(convertible.ToString(CultureInfo.InvariantCulture));
return;
case TypeCode.Char:
WriteValue(convertible.ToChar(CultureInfo.InvariantCulture));
return;
case TypeCode.Boolean:
WriteValue(convertible.ToBoolean(CultureInfo.InvariantCulture));
return;
case TypeCode.SByte:
WriteValue(convertible.ToSByte(CultureInfo.InvariantCulture));
return;
case TypeCode.Int16:
WriteValue(convertible.ToInt16(CultureInfo.InvariantCulture));
return;
case TypeCode.UInt16:
WriteValue(convertible.ToUInt16(CultureInfo.InvariantCulture));
return;
case TypeCode.Int32:
WriteValue(convertible.ToInt32(CultureInfo.InvariantCulture));
return;
case TypeCode.Byte:
WriteValue(convertible.ToByte(CultureInfo.InvariantCulture));
return;
case TypeCode.UInt32:
WriteValue(convertible.ToUInt32(CultureInfo.InvariantCulture));
return;
case TypeCode.Int64:
WriteValue(convertible.ToInt64(CultureInfo.InvariantCulture));
return;
case TypeCode.UInt64:
WriteValue(convertible.ToUInt64(CultureInfo.InvariantCulture));
return;
case TypeCode.Single:
WriteValue(convertible.ToSingle(CultureInfo.InvariantCulture));
return;
case TypeCode.Double:
WriteValue(convertible.ToDouble(CultureInfo.InvariantCulture));
return;
case TypeCode.DateTime:
WriteValue(convertible.ToDateTime(CultureInfo.InvariantCulture));
return;
case TypeCode.Decimal:
WriteValue(convertible.ToDecimal(CultureInfo.InvariantCulture));
return;
case TypeCode.DBNull:
WriteNull();
return;
}
}
else if (value is DateTimeOffset)
{
WriteValue((DateTimeOffset)value);
return;
}
else if (value is byte[])
{
WriteValue((byte[])value);
return;
}
else if (value is Guid)
{
WriteValue((Guid)value);
return;
}
else if (value is Uri)
{
WriteValue((Uri)value);
return;
}
else if (value is TimeSpan)
{
WriteValue((TimeSpan)value);
return;
}
throw new ArgumentException("Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.".FormatWith(CultureInfo.InvariantCulture, value.GetType()));
}
#endregion
/// <summary>
/// Writes out a comment <code>/*...*/</code> containing the specified text.
/// </summary>
/// <param name="text">Text to place inside the comment.</param>
public virtual void WriteComment(string text)
{
AutoComplete(JsonToken.Comment);
}
/// <summary>
/// Writes out the given white space.
/// </summary>
/// <param name="ws">The string of white space characters.</param>
public virtual void WriteWhitespace(string ws)
{
if (ws != null)
{
if (!StringUtils.IsWhiteSpace(ws))
throw new JsonWriterException("Only white space characters should be used.");
}
}
void IDisposable.Dispose()
{
Dispose(true);
}
private void Dispose(bool disposing)
{
if (WriteState != WriteState.Closed)
Close();
}
}
}
#endif
| |
// 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.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
//
// This file was autogenerated by a tool.
// Do not modify it.
//
namespace Microsoft.Azure.Batch
{
using Models = Microsoft.Azure.Batch.Protocol.Models;
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// A Job Preparation task to run before any tasks of the job on any given compute node.
/// </summary>
public partial class JobPreparationTask : ITransportObjectProvider<Models.JobPreparationTask>, IPropertyMetadata
{
private class PropertyContainer : PropertyCollection
{
public readonly PropertyAccessor<string> CommandLineProperty;
public readonly PropertyAccessor<TaskConstraints> ConstraintsProperty;
public readonly PropertyAccessor<IList<EnvironmentSetting>> EnvironmentSettingsProperty;
public readonly PropertyAccessor<string> IdProperty;
public readonly PropertyAccessor<bool?> RerunOnComputeNodeRebootAfterSuccessProperty;
public readonly PropertyAccessor<IList<ResourceFile>> ResourceFilesProperty;
public readonly PropertyAccessor<UserIdentity> UserIdentityProperty;
public readonly PropertyAccessor<bool?> WaitForSuccessProperty;
public PropertyContainer() : base(BindingState.Unbound)
{
this.CommandLineProperty = this.CreatePropertyAccessor<string>("CommandLine", BindingAccess.Read | BindingAccess.Write);
this.ConstraintsProperty = this.CreatePropertyAccessor<TaskConstraints>("Constraints", BindingAccess.Read | BindingAccess.Write);
this.EnvironmentSettingsProperty = this.CreatePropertyAccessor<IList<EnvironmentSetting>>("EnvironmentSettings", BindingAccess.Read | BindingAccess.Write);
this.IdProperty = this.CreatePropertyAccessor<string>("Id", BindingAccess.Read | BindingAccess.Write);
this.RerunOnComputeNodeRebootAfterSuccessProperty = this.CreatePropertyAccessor<bool?>("RerunOnComputeNodeRebootAfterSuccess", BindingAccess.Read | BindingAccess.Write);
this.ResourceFilesProperty = this.CreatePropertyAccessor<IList<ResourceFile>>("ResourceFiles", BindingAccess.Read | BindingAccess.Write);
this.UserIdentityProperty = this.CreatePropertyAccessor<UserIdentity>("UserIdentity", BindingAccess.Read | BindingAccess.Write);
this.WaitForSuccessProperty = this.CreatePropertyAccessor<bool?>("WaitForSuccess", BindingAccess.Read | BindingAccess.Write);
}
public PropertyContainer(Models.JobPreparationTask protocolObject) : base(BindingState.Bound)
{
this.CommandLineProperty = this.CreatePropertyAccessor(
protocolObject.CommandLine,
"CommandLine",
BindingAccess.Read | BindingAccess.Write);
this.ConstraintsProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.Constraints, o => new TaskConstraints(o)),
"Constraints",
BindingAccess.Read | BindingAccess.Write);
this.EnvironmentSettingsProperty = this.CreatePropertyAccessor(
EnvironmentSetting.ConvertFromProtocolCollection(protocolObject.EnvironmentSettings),
"EnvironmentSettings",
BindingAccess.Read | BindingAccess.Write);
this.IdProperty = this.CreatePropertyAccessor(
protocolObject.Id,
"Id",
BindingAccess.Read | BindingAccess.Write);
this.RerunOnComputeNodeRebootAfterSuccessProperty = this.CreatePropertyAccessor(
protocolObject.RerunOnNodeRebootAfterSuccess,
"RerunOnComputeNodeRebootAfterSuccess",
BindingAccess.Read | BindingAccess.Write);
this.ResourceFilesProperty = this.CreatePropertyAccessor(
ResourceFile.ConvertFromProtocolCollection(protocolObject.ResourceFiles),
"ResourceFiles",
BindingAccess.Read | BindingAccess.Write);
this.UserIdentityProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.UserIdentity, o => new UserIdentity(o).Freeze()),
"UserIdentity",
BindingAccess.Read);
this.WaitForSuccessProperty = this.CreatePropertyAccessor(
protocolObject.WaitForSuccess,
"WaitForSuccess",
BindingAccess.Read | BindingAccess.Write);
}
}
private readonly PropertyContainer propertyContainer;
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="JobPreparationTask"/> class.
/// </summary>
/// <param name='commandLine'>The command line of the task.</param>
public JobPreparationTask(
string commandLine)
{
this.propertyContainer = new PropertyContainer();
this.CommandLine = commandLine;
}
internal JobPreparationTask(Models.JobPreparationTask protocolObject)
{
this.propertyContainer = new PropertyContainer(protocolObject);
}
#endregion Constructors
#region JobPreparationTask
/// <summary>
/// Gets or sets the command line of the task.
/// </summary>
/// <remarks>
/// The command line does not run under a shell, and therefore cannot take advantage of shell features such as environment
/// variable expansion. If you want to take advantage of such features, you should invoke the shell in the command
/// line, for example using "cmd /c MyCommand" in Windows or "/bin/sh -c MyCommand" in Linux.
/// </remarks>
public string CommandLine
{
get { return this.propertyContainer.CommandLineProperty.Value; }
set { this.propertyContainer.CommandLineProperty.Value = value; }
}
/// <summary>
/// Gets or sets the execution constraints provided by the user for this Job Preparation task.
/// </summary>
public TaskConstraints Constraints
{
get { return this.propertyContainer.ConstraintsProperty.Value; }
set { this.propertyContainer.ConstraintsProperty.Value = value; }
}
/// <summary>
/// Gets or sets the collection of EnvironmentSetting instances.
/// </summary>
public IList<EnvironmentSetting> EnvironmentSettings
{
get { return this.propertyContainer.EnvironmentSettingsProperty.Value; }
set
{
this.propertyContainer.EnvironmentSettingsProperty.Value = ConcurrentChangeTrackedModifiableList<EnvironmentSetting>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets or sets the id of the task.
/// </summary>
public string Id
{
get { return this.propertyContainer.IdProperty.Value; }
set { this.propertyContainer.IdProperty.Value = value; }
}
/// <summary>
/// Gets or sets whether the Batch service should rerun the Job Preparation task after a compute node reboots.
/// </summary>
/// <remarks>
/// The Job Preparation task is always rerun if a compute node is reimaged, or if the Job Preparation task did not
/// complete (e.g. because the reboot occurred while the task was running). Therefore, you should always write a
/// Job Preparation task to be idempotent and to behave correctly if run multiple times. If this property is not
/// specified, a default value of true is assigned by the Batch service.
/// </remarks>
public bool? RerunOnComputeNodeRebootAfterSuccess
{
get { return this.propertyContainer.RerunOnComputeNodeRebootAfterSuccessProperty.Value; }
set { this.propertyContainer.RerunOnComputeNodeRebootAfterSuccessProperty.Value = value; }
}
/// <summary>
/// Gets or sets a list of files that the Batch service will download to the compute node before running the command
/// line.
/// </summary>
public IList<ResourceFile> ResourceFiles
{
get { return this.propertyContainer.ResourceFilesProperty.Value; }
set
{
this.propertyContainer.ResourceFilesProperty.Value = ConcurrentChangeTrackedModifiableList<ResourceFile>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets or sets the user identity under which the task runs.
/// </summary>
/// <remarks>
/// If omitted, the task runs as a non-administrative user unique to the task.
/// </remarks>
public UserIdentity UserIdentity
{
get { return this.propertyContainer.UserIdentityProperty.Value; }
set { this.propertyContainer.UserIdentityProperty.Value = value; }
}
/// <summary>
/// Gets or sets whether the Batch service should wait for the successful completion of the Job Preparation task
/// before scheduling any tasks on the compute node.
/// </summary>
/// <remarks>
/// A Job Preparation task execution is considered successful if its ExitCode is 0. If this property is not specified,
/// a default value of true is assigned by the Batch service.
/// </remarks>
public bool? WaitForSuccess
{
get { return this.propertyContainer.WaitForSuccessProperty.Value; }
set { this.propertyContainer.WaitForSuccessProperty.Value = value; }
}
#endregion // JobPreparationTask
#region IPropertyMetadata
bool IModifiable.HasBeenModified
{
get { return this.propertyContainer.HasBeenModified; }
}
bool IReadOnly.IsReadOnly
{
get { return this.propertyContainer.IsReadOnly; }
set { this.propertyContainer.IsReadOnly = value; }
}
#endregion //IPropertyMetadata
#region Internal/private methods
/// <summary>
/// Return a protocol object of the requested type.
/// </summary>
/// <returns>The protocol object of the requested type.</returns>
Models.JobPreparationTask ITransportObjectProvider<Models.JobPreparationTask>.GetTransportObject()
{
Models.JobPreparationTask result = new Models.JobPreparationTask()
{
CommandLine = this.CommandLine,
Constraints = UtilitiesInternal.CreateObjectWithNullCheck(this.Constraints, (o) => o.GetTransportObject()),
EnvironmentSettings = UtilitiesInternal.ConvertToProtocolCollection(this.EnvironmentSettings),
Id = this.Id,
RerunOnNodeRebootAfterSuccess = this.RerunOnComputeNodeRebootAfterSuccess,
ResourceFiles = UtilitiesInternal.ConvertToProtocolCollection(this.ResourceFiles),
UserIdentity = UtilitiesInternal.CreateObjectWithNullCheck(this.UserIdentity, (o) => o.GetTransportObject()),
WaitForSuccess = this.WaitForSuccess,
};
return result;
}
#endregion // Internal/private methods
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Projection
// Description: The basic module for MapWindow version 6.0
// ********************************************************************************************************
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 7/13/2009 3:27:36 PM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
// Name | Date | Comment
// --------------------|------------|------------------------------------------------------------
// Ted Dunsford | 5/3/2010 | Updated project to DotSpatial.Projection and license to LGPL
// ********************************************************************************************************
using System;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
namespace DotSpatial.Projections
{
public class Datum : ProjDescriptor, IEsriString
{
#region Private Variables
private const double SEC_TO_RAD = 4.84813681109535993589914102357e-6;
private DatumType _datumtype;
private string _description;
private string[] _nadGrids;
private string _name;
private Spheroid _spheroid;
private double[] _toWgs84;
private static readonly Lazy<DatumsHandler> _datumsHandler = new Lazy<DatumsHandler>(delegate
{
var dh = new DatumsHandler();
dh.Initialize();
return dh;
}, true);
#endregion Private Variables
#region Constructors
/// <summary>
/// Creates a new instance of Datum
/// </summary>
public Datum()
{
_spheroid = new Spheroid();
DatumType = DatumType.Unknown;
}
/// <summary>
/// uses a string name of a standard datum to create a new instance of the Datum class
/// </summary>
/// <param name="standardDatum">The string name of the datum to use</param>
public Datum(string standardDatum)
: this()
{
Proj4DatumName = standardDatum;
}
/// <summary>
/// Uses a Proj4Datums enumeration in order to specify a known datum to
/// define the spheroid and to WGS calculation method and parameters
/// </summary>
/// <param name="standardDatum">The Proj4Datums enumeration specifying the known datum</param>
public Datum(Proj4Datum standardDatum)
: this(standardDatum.ToString())
{
}
#endregion Constructors
#region Methods
/// <summary>
/// Returns a representaion of this object as a Proj4 string.
/// </summary>
/// <returns></returns>
public string ToProj4String()
{
// if you have a datum name you don't need to say anything about the Spheroid
string str = Proj4DatumName;
if (str == null)
{
switch (DatumType)
{
case DatumType.Unknown:
case DatumType.WGS84:
break;
case DatumType.Param3:
Debug.Assert(_toWgs84.Length >= 3);
str = String.Format(CultureInfo.InvariantCulture, " +towgs84={0},{1},{2}", _toWgs84[0], _toWgs84[1], _toWgs84[2]);
break;
case DatumType.Param7:
Debug.Assert(_toWgs84.Length >= 7);
str = String.Format(CultureInfo.InvariantCulture, " +towgs84={0},{1},{2},{3},{4},{5},{6}",
_toWgs84[0],
_toWgs84[1],
_toWgs84[2],
_toWgs84[3] / SEC_TO_RAD,
_toWgs84[4] / SEC_TO_RAD,
_toWgs84[5] / SEC_TO_RAD,
(_toWgs84[6] - 1) * 1000000.0);
break;
case DatumType.GridShift:
str = String.Format(" +nadgrids={0}", String.Join(",", NadGrids));
break;
default:
throw new ArgumentOutOfRangeException("DatumType");
}
return str + Spheroid.ToProj4String();
}
else
{
return String.Format(" +datum={0}", Proj4DatumName);
}
}
/// <summary>
/// Compares two datums to see if they are actually describing the same thing and
/// therefore don't need to be transformed.
/// </summary>
/// <param name="otherDatum">The other datum to compare against</param>
/// <returns>The boolean result of the operation.</returns>
public bool Matches(Datum otherDatum)
{
if (_datumtype != otherDatum.DatumType) return false;
if (_datumtype == DatumType.WGS84) return true;
if (_spheroid.EquatorialRadius != otherDatum.Spheroid.EquatorialRadius) return false;
if (_spheroid.PolarRadius != otherDatum.Spheroid.PolarRadius) return false;
if (_datumtype == DatumType.Param3)
{
if (_toWgs84[0] != otherDatum.ToWGS84[0]) return false;
if (_toWgs84[1] != otherDatum.ToWGS84[1]) return false;
if (_toWgs84[2] != otherDatum.ToWGS84[2]) return false;
return true;
}
if (_datumtype == DatumType.Param7)
{
if (_toWgs84[0] != otherDatum.ToWGS84[0]) return false;
if (_toWgs84[1] != otherDatum.ToWGS84[1]) return false;
if (_toWgs84[2] != otherDatum.ToWGS84[2]) return false;
if (_toWgs84[3] != otherDatum.ToWGS84[3]) return false;
if (_toWgs84[4] != otherDatum.ToWGS84[4]) return false;
if (_toWgs84[5] != otherDatum.ToWGS84[5]) return false;
if (_toWgs84[6] != otherDatum.ToWGS84[6]) return false;
return true;
}
if (_datumtype == DatumType.GridShift)
{
if (_nadGrids.Length != otherDatum.NadGrids.Length) return false;
return !_nadGrids.Where((t, i) => t != otherDatum.NadGrids[i]).Any();
}
return false;
}
#endregion Methods
#region Properties
/// <summary>
/// Gets or sets the name of the datum defining the spherical characteristics of the model of the earth
/// </summary>
public string Name
{
get { return _name; }
set { _name = value; }
}
/// <summary>
/// The spheroid of the earth, defining the maximal radius and the flattening factor
/// </summary>
public Spheroid Spheroid
{
get { return _spheroid; }
set { _spheroid = value; }
}
/// <summary>
/// Gets or sets the set of double parameters, (this can either be 3 or 7 parameters)
/// used to transform this
/// </summary>
public double[] ToWGS84
{
get { return _toWgs84; }
set { _toWgs84 = value; }
}
/// <summary>
/// Gets or sets the datum type, which clarifies how to perform transforms to WGS84
/// </summary>
public DatumType DatumType
{
get { return _datumtype; }
set { _datumtype = value; }
}
/// <summary>
/// Gets or sets an english description for this datum
/// </summary>
public string Description
{
get { return _description; }
set { _description = value; }
}
/// <summary>
/// Gets or sets the array of string nadGrid
/// </summary>
public string[] NadGrids
{
get { return _nadGrids; }
set { _nadGrids = value; }
}
#endregion Properties
/// <summary>
/// Lookups the proj4 datum based on the stored name.
/// </summary>
public string Proj4DatumName
{
get
{
if (Name == null)
return null;
switch (Name)
{
case "D_WGS_1984":
return "WGS84";
case "D_Greek":
return "GGRS87";
case "D_North_American_1983":
return "NAD83";
case "D_North_American_1927":
return "NAD27";
default:
// not sure where to lookup the remaining, missing values.
// also we could include this information in the datum.xml file where much of this information resides.
return null;
}
}
set
{
string id = value.ToLower();
switch (id)
{
case "wgs84":
_toWgs84 = new double[] { 0, 0, 0 };
_spheroid = new Spheroid(Proj4Ellipsoid.WGS_1984);
_description = "WGS 1984";
_name = "D_WGS_1984";
_datumtype = DatumType.WGS84;
break;
case "ggrs87":
_toWgs84 = new[] { -199.87, 74.79, 246.62 };
_spheroid = new Spheroid(Proj4Ellipsoid.GRS_1980);
_description = "Greek Geodetic Reference System 1987";
_datumtype = DatumType.Param3;
_name = "D_Greek";
break;
case "nad83":
_toWgs84 = new double[] { 0, 0, 0 };
_spheroid = new Spheroid(Proj4Ellipsoid.GRS_1980);
_description = "North American Datum 1983";
_datumtype = DatumType.WGS84;
_name = "D_North_American_1983";
break;
case "nad27":
_nadGrids = new[] { "@conus", "@ntv1_can", "@ntv2_0", "@alaska" };
_spheroid = new Spheroid(Proj4Ellipsoid.Clarke_1866);
_description = "North American Datum 1927";
_name = "D_North_American_1927";
_datumtype = DatumType.GridShift;
break;
case "potsdam":
_toWgs84 = new[] { 606.0, 23.0, 413.0 };
_spheroid = new Spheroid(Proj4Ellipsoid.Bessel_1841);
_description = "Potsdam Rauenberg 1950 DHDN";
_datumtype = DatumType.Param3;
break;
case "carthage":
_toWgs84 = new[] { -263.0, 6, 413 };
_spheroid = new Spheroid(Proj4Ellipsoid.ClarkeModified_1880);
_description = "Carthage 1934 Tunisia";
_datumtype = DatumType.Param3;
break;
case "hermannskogel":
_toWgs84 = new[] { 653.0, -212.0, 449 };
_spheroid = new Spheroid(Proj4Ellipsoid.Bessel_1841);
_description = "Hermannskogel";
_datumtype = DatumType.Param3;
break;
case "ire65":
InitializeToWgs84(new[] { "482.530", "-130.569", "564.557", "-1.042", "-0.214", "-0.631", "8.15" });
_spheroid = new Spheroid(Proj4Ellipsoid.AiryModified);
_description = "Ireland 1965";
break;
case "nzgd49":
InitializeToWgs84(new[] { "59.47", "-5.04", "187.44", "0.47", "-0.1", "1.024", "-4.5993" });
_spheroid = new Spheroid(Proj4Ellipsoid.International_1909);
_description = "New Zealand";
break;
case "osgb36":
InitializeToWgs84(new[] { "446.448", "-125.157", "542.060", "0.1502", "0.2470", "0.8421", "-20.4894" });
_spheroid = new Spheroid(Proj4Ellipsoid.Airy_1830);
_description = "Airy 1830";
break;
}
}
}
#region IEsriString Members
/// <summary>
/// Creates an esri well known text string for the datum part of the string
/// </summary>
/// <returns>The datum portion of the esri well known text</returns>
public string ToEsriString()
{
return @"DATUM[""" + _name + @"""," + Spheroid.ToEsriString() + "]";
}
/// <summary>
/// Parses the datum from the esri string
/// </summary>
/// <param name="esriString">The string to parse values from</param>
public void ParseEsriString(string esriString)
{
if (string.IsNullOrEmpty(esriString))
return;
if (esriString.Contains("DATUM") == false) return;
int iStart = esriString.IndexOf("DATUM") + 7;
int iEnd = esriString.IndexOf(@""",", iStart) - 1;
if (iEnd < iStart) return;
_name = esriString.Substring(iStart, iEnd - iStart + 1);
var datumEntry = _datumsHandler.Value[_name];
if (datumEntry != null)
{
DatumType = datumEntry.Type;
switch (DatumType)
{
case DatumType.Param3:
{
var transform = new double[3];
transform[0] = ParseDouble(datumEntry.P1);
transform[1] = ParseDouble(datumEntry.P2);
transform[2] = ParseDouble(datumEntry.P3);
ToWGS84 = transform;
}
break;
case DatumType.Param7:
{
double[] transform = new double[7];
transform[0] = ParseDouble(datumEntry.P1);
transform[1] = ParseDouble(datumEntry.P2);
transform[2] = ParseDouble(datumEntry.P3);
transform[3] = ParseDouble(datumEntry.P4);
transform[4] = ParseDouble(datumEntry.P5);
transform[5] = ParseDouble(datumEntry.P6);
transform[6] = ParseDouble(datumEntry.P7);
ToWGS84 = transform;
break;
}
case DatumType.GridShift:
if (!string.IsNullOrEmpty(datumEntry.Shift))
{
NadGrids = datumEntry.Shift.Split(new[] {";"}, StringSplitOptions.RemoveEmptyEntries);
}
break;
}
}
_spheroid.ParseEsriString(esriString);
}
private static double ParseDouble(string str)
{
if (string.IsNullOrEmpty(str)) return 0;
return double.Parse(str, CultureInfo.InvariantCulture);
}
#endregion
/// <summary>
/// Initializes to WGS84.
/// </summary>
/// <param name="values">The values.</param>
/// <exception cref="ArgumentNullException">Throws if <paramref name="values"/> is null</exception>
/// <exception cref="ArgumentOutOfRangeException">Throws if <paramref name="values"/> has length not 3 or 7.</exception>
public void InitializeToWgs84(string[] values)
{
if (values == null) throw new ArgumentNullException("values");
if (values.Length != 3 && values.Length != 7)
throw new ArgumentOutOfRangeException("values", "Unrecognized ToWgs84 array length. The number of elements in the array should be 3 or 7");
_toWgs84 = new double[values.Length];
for (int i = 0; i < values.Length; i++)
{
_toWgs84[i] = double.Parse(values[i], CultureInfo.InvariantCulture);
}
if (_toWgs84.Length == 3)
{
_datumtype = DatumType.Param3;
}
else
{
// checking to see if several blank values were included.
if (_toWgs84[3] == 0.0 && _toWgs84[4] == 0.0 && _toWgs84[5] == 0.0 && _toWgs84[6] == 0.0)
{
_datumtype = DatumType.Param3;
}
else
{
_datumtype = DatumType.Param7;
// Transform from arc seconds to radians
_toWgs84[3] *= SEC_TO_RAD;
_toWgs84[4] *= SEC_TO_RAD;
_toWgs84[5] *= SEC_TO_RAD;
// transform from parts per millon to scaling factor
_toWgs84[6] = (_toWgs84[6] / 1000000.0) + 1;
}
}
}
}
}
| |
using UnityEngine;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
public partial class Select : IEnumerable<GameObject>
{
Dictionary<GameObject, bool> gameObjects;
string query;
public string selector
{
get
{
return query;
}
}
public Select(params GameObject[] objects)
{
gameObjects = new Dictionary<GameObject, bool>();
this.query = "";
foreach (GameObject obj in objects)
{
gameObjects[obj] = true;
}
}
public Select(string query)
{
gameObjects = new Dictionary<GameObject, bool>();
this.query = query;
string head = query;
string tail = "";
if (query.Contains(','))
{
head = query.Substring(0, query.IndexOf(','));
tail = query.Substring(query.IndexOf(',') + 1);
}
foreach (Match match in Regex.Matches(" " + head.Trim(), @"(#[\w-]+|\.[\w_]+(?:\[.+\]|:!?[\w_]+)*|\s+#[\w-]+|\s+\w+|\s+\.[\w_]+(?:\[.+\]|:!?[\w_]+)*)"))
{
if (match.Value.StartsWith(" ."))
{
List<string> meta = ParseMetas(match.Value);
string cl = meta[0];
meta.RemoveAt(0);
FindByClass(cl, meta);
}
else if (match.Value.StartsWith(" #"))
{
FindByName(match.Value.Trim(" #".ToCharArray()));
}
else if (match.Value.StartsWith(" "))
{
FindByTag(match.Value.Trim());
}
else if (match.Value.StartsWith("."))
{
List<string> meta = ParseMetas(match.Value);
string cl = meta[0];
meta.RemoveAt(0);
PruneWithoutClass(cl, meta);
}
else if (match.Value.StartsWith("#"))
{
PruneWithoutName(match.Value.Trim("#".ToCharArray()));
}
}
if (tail != "")
{
Union(new Select(tail.Trim()));
}
}
List<string> ParseMetas(string query)
{
List<string> meta = new List<string>();
foreach (Match match in Regex.Matches(query, @"(\.[\w_]+|\[.*\]|:!?[\w_]+)"))
{
meta.Add(match.Value);
}
return meta;
}
public void Union(Select selection)
{
foreach (GameObject obj in selection)
{
gameObjects[obj] = true;
}
}
bool MatchesBooleanMeta(object obj, string meta)
{
bool expected = true;
string attribute = meta;
if (attribute.StartsWith("!"))
{
expected = false;
attribute = attribute.TrimStart('!');
}
FieldInfo field = obj.GetType().GetField(attribute);
if (field != null)
{
try
{
if ((bool)field.GetValue(obj) != expected)
{
return false;
}
}
catch
{
throw new Exception("Trying to use meta-selector :" + meta + " to access non-boolean field.");
}
}
PropertyInfo property = obj.GetType().GetProperty(attribute);
if (property != null)
{
try
{
if ((bool)property.GetGetMethod().Invoke(obj, null) != expected)
{
return false;
}
}
catch
{
throw new Exception("Trying to use meta-selector :" + meta + " to access non-boolean field.");
}
}
return true;
}
bool MatchesComparisonMeta(object obj, string meta)
{
Match match = Regex.Match(meta, @"^([\w_]+)(!=|=|>=|<=|>|<)(.+)$");
if (!match.Success)
{
throw new Exception("Invalid syntax in meta-selector [" + meta + "]");
}
string fieldName = match.Groups[1].Value;
string comparisonType = match.Groups[2].Value;
string valueString = match.Groups[3].Value;
FieldInfo field = obj.GetType().GetField(fieldName);
if (field == null)
{
throw new Exception("Invalid field in meta-selector [" + meta + "]");
}
MethodInfo parseMethod = field.FieldType.GetMethod("Parse", new Type[] { typeof(string) });
MethodInfo compareMethod = field.FieldType.GetMethod("CompareTo", new Type[] { field.FieldType });
if (parseMethod == null || compareMethod == null)
{
throw new Exception("Field type in [" + meta + "] needs both a Parse and a CompareTo method for this selector to work");
}
object value = parseMethod.Invoke(null, new string[] { valueString });
int comparison = (int)compareMethod.Invoke(field.GetValue(obj), new object[] { value });
return ((comparisonType == "=" && comparison == 0)
|| (comparisonType == ">" && comparison > 0)
|| (comparisonType == "<" && comparison < 0)
|| (comparisonType == ">=" && comparison >= 0)
|| (comparisonType == "<=" && comparison <= 0)
|| (comparisonType == "!=" && comparison != 0));
}
bool MatchesMeta(Component component, List<string> metas)
{
foreach (string meta in metas)
{
if (meta.StartsWith(":"))
{
if (!MatchesBooleanMeta(component, meta.TrimStart(':')))
{
return false;
}
}
else if (meta.StartsWith("["))
{
if (!MatchesComparisonMeta(component, meta.Trim("[]".ToCharArray())))
{
return false;
}
}
}
return true;
}
void FindByClass(string className, List<string> meta)
{
System.Type type = System.Type.GetType(className) ?? Assembly.Load("UnityEngine").GetType("UnityEngine." + className);
if (type != null)
{
if (gameObjects.Count != 0)
{
List<GameObject> parents = gameObjects.Keys.ToList();
gameObjects = new Dictionary<GameObject, bool>();
foreach (GameObject parent in parents)
{
foreach (Component component in parent.GetComponentsInChildren(type))
{
if (component.gameObject != parent && MatchesMeta(component, meta))
{
gameObjects[component.gameObject] = true;
}
}
}
}
else
{
foreach (Component component in Resources.FindObjectsOfTypeAll(type))
{
if (MatchesMeta(component, meta))
{
gameObjects[component.gameObject] = true;
}
}
}
}
}
void FindByName(string name)
{
if (gameObjects.Count != 0)
{
List<GameObject> parents = gameObjects.Keys.ToList();
gameObjects = new Dictionary<GameObject, bool>();
foreach (GameObject parent in parents)
{
foreach (Transform transform in parent.GetComponentsInChildren<Transform>())
{
if (transform.gameObject != parent && transform.name == name)
{
gameObjects[transform.gameObject] = true;
}
}
}
}
else
{
foreach (Transform transform in Resources.FindObjectsOfTypeAll(typeof(Transform)))
{
if (transform.name == name)
{
gameObjects[transform.gameObject] = true;
}
}
}
}
void FindByTag(string tag)
{
// TODO: if gameObjects isn't empty find in children
if (gameObjects.Count != 0)
{
List<GameObject> parents = gameObjects.Keys.ToList();
gameObjects = new Dictionary<GameObject, bool>();
foreach (GameObject parent in parents)
{
foreach (Transform transform in parent.GetComponentsInChildren<Transform>())
{
if (transform.gameObject != parent && transform.tag == tag)
{
gameObjects[transform.gameObject] = true;
}
}
}
}
else
{
foreach (GameObject obj in GameObject.FindGameObjectsWithTag(tag))
{
gameObjects[obj] = true;
}
}
}
void PruneWithoutClass(string className, List<string> meta)
{
System.Type type = System.Type.GetType(className) ?? Assembly.Load("UnityEngine").GetType("UnityEngine." + className);
List<GameObject> toRemove = gameObjects.Keys.ToList().Where((GameObject obj) =>
{
Component component = obj.GetComponent(type);
if (component == null)
{
return true;
}
if (!MatchesMeta(component, meta))
{
return true;
}
return false;
}).ToList();
foreach (GameObject remove in toRemove)
{
gameObjects.Remove(remove);
}
}
void PruneWithoutName(string name)
{
List<GameObject> toRemove = gameObjects.Keys.ToList().Where((GameObject obj) =>
{
return obj.name != name;
}).ToList();
foreach (GameObject remove in toRemove)
{
gameObjects.Remove(remove);
}
}
public GameObject this[int i]
{
get
{
return gameObjects.Keys.ToArray()[i];
}
}
#region IEnumerable<GameObject> Members
public IEnumerator<GameObject> GetEnumerator()
{
return gameObjects.Keys.ToList().GetEnumerator();
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return gameObjects.Keys.ToList().GetEnumerator();
}
#endregion
}
| |
using System;
using System.Diagnostics;
using System.Text;
using u8 = System.Byte;
using u32 = System.UInt32;
namespace CleanSqlite
{
public partial class Sqlite3
{
/*
** 2001 September 15
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains C code routines that are called by the parser
** in order to generate code for DELETE FROM statements.
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2
**
*************************************************************************
*/
//#include "sqliteInt.h"
/*
** While a SrcList can in general represent multiple tables and subqueries
** (as in the FROM clause of a SELECT statement) in this case it contains
** the name of a single table, as one might find in an INSERT, DELETE,
** or UPDATE statement. Look up that table in the symbol table and
** return a pointer. Set an error message and return NULL if the table
** name is not found or if any other error occurs.
**
** The following fields are initialized appropriate in pSrc:
**
** pSrc->a[0].pTab Pointer to the Table object
** pSrc->a[0].pIndex Pointer to the INDEXED BY index, if there is one
**
*/
static Table sqlite3SrcListLookup( Parse pParse, SrcList pSrc )
{
SrcList_item pItem = pSrc.a[0];
Table pTab;
Debug.Assert( pItem != null && pSrc.nSrc == 1 );
pTab = sqlite3LocateTable( pParse, 0, pItem.zName, pItem.zDatabase );
sqlite3DeleteTable( pParse.db, ref pItem.pTab );
pItem.pTab = pTab;
if ( pTab != null )
{
pTab.nRef++;
}
if ( sqlite3IndexedByLookup( pParse, pItem ) != 0 )
{
pTab = null;
}
return pTab;
}
/*
** Check to make sure the given table is writable. If it is not
** writable, generate an error message and return 1. If it is
** writable return 0;
*/
static bool sqlite3IsReadOnly( Parse pParse, Table pTab, int viewOk )
{
/* A table is not writable under the following circumstances:
**
** 1) It is a virtual table and no implementation of the xUpdate method
** has been provided, or
** 2) It is a system table (i.e. sqlite_master), this call is not
** part of a nested parse and writable_schema pragma has not
** been specified.
**
** In either case leave an error message in pParse and return non-zero.
*/
if (
( IsVirtual( pTab )
&& sqlite3GetVTable( pParse.db, pTab ).pMod.pModule.xUpdate == null )
|| ( ( pTab.tabFlags & TF_Readonly ) != 0
&& ( pParse.db.flags & SQLITE_WriteSchema ) == 0
&& pParse.nested == 0 )
)
{
sqlite3ErrorMsg( pParse, "table %s may not be modified", pTab.zName );
return true;
}
#if !SQLITE_OMIT_VIEW
if ( viewOk == 0 && pTab.pSelect != null )
{
sqlite3ErrorMsg( pParse, "cannot modify %s because it is a view", pTab.zName );
return true;
}
#endif
return false;
}
#if !SQLITE_OMIT_VIEW && !SQLITE_OMIT_TRIGGER
/*
** Evaluate a view and store its result in an ephemeral table. The
** pWhere argument is an optional WHERE clause that restricts the
** set of rows in the view that are to be added to the ephemeral table.
*/
static void sqlite3MaterializeView(
Parse pParse, /* Parsing context */
Table pView, /* View definition */
Expr pWhere, /* Optional WHERE clause to be added */
int iCur /* VdbeCursor number for ephemerial table */
)
{
SelectDest dest = new SelectDest();
Select pDup;
sqlite3 db = pParse.db;
pDup = sqlite3SelectDup( db, pView.pSelect, 0 );
if ( pWhere != null )
{
SrcList pFrom;
pWhere = sqlite3ExprDup( db, pWhere, 0 );
pFrom = sqlite3SrcListAppend( db, null, null, null );
//if ( pFrom != null )
//{
Debug.Assert( pFrom.nSrc == 1 );
pFrom.a[0].zAlias = pView.zName;// sqlite3DbStrDup( db, pView.zName );
pFrom.a[0].pSelect = pDup;
Debug.Assert( pFrom.a[0].pOn == null );
Debug.Assert( pFrom.a[0].pUsing == null );
//}
//else
//{
// sqlite3SelectDelete( db, ref pDup );
//}
pDup = sqlite3SelectNew( pParse, null, pFrom, pWhere, null, null, null, 0, null, null );
}
sqlite3SelectDestInit( dest, SRT_EphemTab, iCur );
sqlite3Select( pParse, pDup, ref dest );
sqlite3SelectDelete( db, ref pDup );
}
#endif //* !SQLITE_OMIT_VIEW) && !SQLITE_OMIT_TRIGGER) */
#if (SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !(SQLITE_OMIT_SUBQUERY)
/*
** Generate an expression tree to implement the WHERE, ORDER BY,
** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
**
** DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
** \__________________________/
** pLimitWhere (pInClause)
*/
Expr sqlite3LimitWhere(
Parse pParse, /* The parser context */
SrcList pSrc, /* the FROM clause -- which tables to scan */
Expr pWhere, /* The WHERE clause. May be null */
ExprList pOrderBy, /* The ORDER BY clause. May be null */
Expr pLimit, /* The LIMIT clause. May be null */
Expr pOffset, /* The OFFSET clause. May be null */
char zStmtType /* Either DELETE or UPDATE. For error messages. */
){
Expr pWhereRowid = null; /* WHERE rowid .. */
Expr pInClause = null; /* WHERE rowid IN ( select ) */
Expr pSelectRowid = null; /* SELECT rowid ... */
ExprList pEList = null; /* Expression list contaning only pSelectRowid */
SrcList pSelectSrc = null; /* SELECT rowid FROM x ... (dup of pSrc) */
Select pSelect = null; /* Complete SELECT tree */
/* Check that there isn't an ORDER BY without a LIMIT clause.
*/
if( pOrderBy!=null && (pLimit == null) ) {
sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
pParse.parseError = 1;
goto limit_where_cleanup_2;
}
/* We only need to generate a select expression if there
** is a limit/offset term to enforce.
*/
if ( pLimit == null )
{
/* if pLimit is null, pOffset will always be null as well. */
Debug.Assert( pOffset == null );
return pWhere;
}
/* Generate a select expression tree to enforce the limit/offset
** term for the DELETE or UPDATE statement. For example:
** DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
** becomes:
** DELETE FROM table_a WHERE rowid IN (
** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
** );
*/
pSelectRowid = sqlite3PExpr( pParse, TK_ROW, null, null, null );
if( pSelectRowid == null ) goto limit_where_cleanup_2;
pEList = sqlite3ExprListAppend( pParse, null, pSelectRowid);
if( pEList == null ) goto limit_where_cleanup_2;
/* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
** and the SELECT subtree. */
pSelectSrc = sqlite3SrcListDup(pParse.db, pSrc,0);
if( pSelectSrc == null ) {
sqlite3ExprListDelete(pParse.db, pEList);
goto limit_where_cleanup_2;
}
/* generate the SELECT expression tree. */
pSelect = sqlite3SelectNew( pParse, pEList, pSelectSrc, pWhere, null, null,
pOrderBy, 0, pLimit, pOffset );
if( pSelect == null ) return null;
/* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
pWhereRowid = sqlite3PExpr( pParse, TK_ROW, null, null, null );
if( pWhereRowid == null ) goto limit_where_cleanup_1;
pInClause = sqlite3PExpr( pParse, TK_IN, pWhereRowid, null, null );
if( pInClause == null ) goto limit_where_cleanup_1;
pInClause->x.pSelect = pSelect;
pInClause->flags |= EP_xIsSelect;
sqlite3ExprSetHeight(pParse, pInClause);
return pInClause;
/* something went wrong. clean up anything allocated. */
limit_where_cleanup_1:
sqlite3SelectDelete(pParse.db, pSelect);
return null;
limit_where_cleanup_2:
sqlite3ExprDelete(pParse.db, ref pWhere);
sqlite3ExprListDelete(pParse.db, pOrderBy);
sqlite3ExprDelete(pParse.db, ref pLimit);
sqlite3ExprDelete(pParse.db, ref pOffset);
return null;
}
#endif //* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
/*
** Generate code for a DELETE FROM statement.
**
** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
** \________/ \________________/
** pTabList pWhere
*/
static void sqlite3DeleteFrom(
Parse pParse, /* The parser context */
SrcList pTabList, /* The table from which we should delete things */
Expr pWhere /* The WHERE clause. May be null */
)
{
Vdbe v; /* The virtual database engine */
Table pTab; /* The table from which records will be deleted */
string zDb; /* Name of database holding pTab */
int end, addr = 0; /* A couple addresses of generated code */
int i; /* Loop counter */
WhereInfo pWInfo; /* Information about the WHERE clause */
Index pIdx; /* For looping over indices of the table */
int iCur; /* VDBE VdbeCursor number for pTab */
sqlite3 db; /* Main database structure */
AuthContext sContext; /* Authorization context */
NameContext sNC; /* Name context to resolve expressions in */
int iDb; /* Database number */
int memCnt = -1; /* Memory cell used for change counting */
int rcauth; /* Value returned by authorization callback */
#if !SQLITE_OMIT_TRIGGER
bool isView; /* True if attempting to delete from a view */
Trigger pTrigger; /* List of table triggers, if required */
#endif
sContext = new AuthContext();//memset(&sContext, 0, sizeof(sContext));
db = pParse.db;
if ( pParse.nErr != 0 /*|| db.mallocFailed != 0 */ )
{
goto delete_from_cleanup;
}
Debug.Assert( pTabList.nSrc == 1 );
/* Locate the table which we want to delete. This table has to be
** put in an SrcList structure because some of the subroutines we
** will be calling are designed to work with multiple tables and expect
** an SrcList* parameter instead of just a Table* parameter.
*/
pTab = sqlite3SrcListLookup( pParse, pTabList );
if ( pTab == null )
goto delete_from_cleanup;
/* Figure out if we have any triggers and if the table being
** deleted from is a view
*/
#if !SQLITE_OMIT_TRIGGER
int iDummy;
pTrigger = sqlite3TriggersExist( pParse, pTab, TK_DELETE, null, out iDummy );
isView = pTab.pSelect != null;
#else
const Trigger pTrigger = null;
bool isView = false;
#endif
#if SQLITE_OMIT_VIEW
//# undef isView
isView = false;
#endif
/* If pTab is really a view, make sure it has been initialized.
*/
if ( sqlite3ViewGetColumnNames( pParse, pTab ) != 0 )
{
goto delete_from_cleanup;
}
if ( sqlite3IsReadOnly( pParse, pTab, ( pTrigger != null ? 1 : 0 ) ) )
{
goto delete_from_cleanup;
}
iDb = sqlite3SchemaToIndex( db, pTab.pSchema );
Debug.Assert( iDb < db.nDb );
zDb = db.aDb[iDb].zName;
#if !SQLITE_OMIT_AUTHORIZATION
rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
#else
rcauth = SQLITE_OK;
#endif
Debug.Assert( rcauth == SQLITE_OK || rcauth == SQLITE_DENY || rcauth == SQLITE_IGNORE );
if ( rcauth == SQLITE_DENY )
{
goto delete_from_cleanup;
}
Debug.Assert( !isView || pTrigger != null );
/* Assign cursor number to the table and all its indices.
*/
Debug.Assert( pTabList.nSrc == 1 );
iCur = pTabList.a[0].iCursor = pParse.nTab++;
for ( pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext )
{
pParse.nTab++;
}
#if !SQLITE_OMIT_AUTHORIZATION
/* Start the view context
*/
if( isView ){
sqlite3AuthContextPush(pParse, sContext, pTab.zName);
}
#endif
/* Begin generating code.
*/
v = sqlite3GetVdbe( pParse );
if ( v == null )
{
goto delete_from_cleanup;
}
if ( pParse.nested == 0 )
sqlite3VdbeCountChanges( v );
sqlite3BeginWriteOperation( pParse, 1, iDb );
/* If we are trying to delete from a view, realize that view into
** a ephemeral table.
*/
#if !(SQLITE_OMIT_VIEW) && !(SQLITE_OMIT_TRIGGER)
if ( isView )
{
sqlite3MaterializeView( pParse, pTab, pWhere, iCur );
}
#endif
/* Resolve the column names in the WHERE clause.
*/
sNC = new NameContext();// memset( &sNC, 0, sizeof( sNC ) );
sNC.pParse = pParse;
sNC.pSrcList = pTabList;
if ( sqlite3ResolveExprNames( sNC, ref pWhere ) != 0 )
{
goto delete_from_cleanup;
}
/* Initialize the counter of the number of rows deleted, if
** we are counting rows.
*/
if ( ( db.flags & SQLITE_CountRows ) != 0 )
{
memCnt = ++pParse.nMem;
sqlite3VdbeAddOp2( v, OP_Integer, 0, memCnt );
}
#if !SQLITE_OMIT_TRUNCATE_OPTIMIZATION
/* Special case: A DELETE without a WHERE clause deletes everything.
** It is easier just to erase the whole table. Prior to version 3.6.5,
** this optimization caused the row change count (the value returned by
** API function sqlite3_count_changes) to be set incorrectly. */
if ( rcauth == SQLITE_OK && pWhere == null && null == pTrigger && !IsVirtual( pTab )
&& 0 == sqlite3FkRequired( pParse, pTab, null, 0 )
)
{
Debug.Assert( !isView );
sqlite3VdbeAddOp4( v, OP_Clear, pTab.tnum, iDb, memCnt,
pTab.zName, P4_STATIC );
for ( pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext )
{
Debug.Assert( pIdx.pSchema == pTab.pSchema );
sqlite3VdbeAddOp2( v, OP_Clear, pIdx.tnum, iDb );
}
}
else
#endif //* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
/* The usual case: There is a WHERE clause so we have to scan through
** the table and pick which records to delete.
*/
{
int iRowSet = ++pParse.nMem; /* Register for rowset of rows to delete */
int iRowid = ++pParse.nMem; /* Used for storing rowid values. */
int regRowid; /* Actual register containing rowids */
/* Collect rowids of every row to be deleted.
*/
sqlite3VdbeAddOp2( v, OP_Null, 0, iRowSet );
ExprList elDummy = null;
pWInfo = sqlite3WhereBegin( pParse, pTabList, pWhere, ref elDummy, WHERE_DUPLICATES_OK );
if ( pWInfo == null )
goto delete_from_cleanup;
regRowid = sqlite3ExprCodeGetColumn( pParse, pTab, -1, iCur, iRowid );
sqlite3VdbeAddOp2( v, OP_RowSetAdd, iRowSet, regRowid );
if ( ( db.flags & SQLITE_CountRows ) != 0 )
{
sqlite3VdbeAddOp2( v, OP_AddImm, memCnt, 1 );
}
sqlite3WhereEnd( pWInfo );
/* Delete every item whose key was written to the list during the
** database scan. We have to delete items after the scan is complete
** because deleting an item can change the scan order. */
end = sqlite3VdbeMakeLabel( v );
/* Unless this is a view, open cursors for the table we are
** deleting from and all its indices. If this is a view, then the
** only effect this statement has is to fire the INSTEAD OF
** triggers. */
if ( !isView )
{
sqlite3OpenTableAndIndices( pParse, pTab, iCur, OP_OpenWrite );
}
addr = sqlite3VdbeAddOp3( v, OP_RowSetRead, iRowSet, end, iRowid );
/* Delete the row */
#if !SQLITE_OMIT_VIRTUALTABLE
if ( IsVirtual( pTab ) )
{
VTable pVTab = sqlite3GetVTable( db, pTab );
sqlite3VtabMakeWritable( pParse, pTab );
sqlite3VdbeAddOp4( v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB );
sqlite3VdbeChangeP5( v, OE_Abort );
sqlite3MayAbort( pParse );
}
else
#endif
{
int count = ( pParse.nested == 0 ) ? 1 : 0; /* True to count changes */
sqlite3GenerateRowDelete( pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default );
}
/* End of the delete loop */
sqlite3VdbeAddOp2( v, OP_Goto, 0, addr );
sqlite3VdbeResolveLabel( v, end );
/* Close the cursors open on the table and its indexes. */
if ( !isView && !IsVirtual( pTab ) )
{
for ( i = 1, pIdx = pTab.pIndex; pIdx != null; i++, pIdx = pIdx.pNext )
{
sqlite3VdbeAddOp2( v, OP_Close, iCur + i, pIdx.tnum );
}
sqlite3VdbeAddOp1( v, OP_Close, iCur );
}
}
/* Update the sqlite_sequence table by storing the content of the
** maximum rowid counter values recorded while inserting into
** autoincrement tables.
*/
if ( pParse.nested == 0 && pParse.pTriggerTab == null )
{
sqlite3AutoincrementEnd( pParse );
}
/* Return the number of rows that were deleted. If this routine is
** generating code because of a call to sqlite3NestedParse(), do not
** invoke the callback function.
*/
if ( ( db.flags & SQLITE_CountRows ) != 0 && 0 == pParse.nested && null == pParse.pTriggerTab )
{
sqlite3VdbeAddOp2( v, OP_ResultRow, memCnt, 1 );
sqlite3VdbeSetNumCols( v, 1 );
sqlite3VdbeSetColName( v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC );
}
delete_from_cleanup:
#if !SQLITE_OMIT_AUTHORIZATION
sqlite3AuthContextPop(sContext);
#endif
sqlite3SrcListDelete( db, ref pTabList );
sqlite3ExprDelete( db, ref pWhere );
return;
}
/* Make sure "isView" and other macros defined above are undefined. Otherwise
** thely may interfere with compilation of other functions in this file
** (or in another file, if this file becomes part of the amalgamation). */
//#if isView
// #undef isView
//#endif
//#if pTrigger
// #undef pTrigger
//#endif
/*
** This routine generates VDBE code that causes a single row of a
** single table to be deleted.
**
** The VDBE must be in a particular state when this routine is called.
** These are the requirements:
**
** 1. A read/write cursor pointing to pTab, the table containing the row
** to be deleted, must be opened as cursor number $iCur.
**
** 2. Read/write cursors for all indices of pTab must be open as
** cursor number base+i for the i-th index.
**
** 3. The record number of the row to be deleted must be stored in
** memory cell iRowid.
**
** This routine generates code to remove both the table record and all
** index entries that point to that record.
*/
static void sqlite3GenerateRowDelete(
Parse pParse, /* Parsing context */
Table pTab, /* Table containing the row to be deleted */
int iCur, /* VdbeCursor number for the table */
int iRowid, /* Memory cell that contains the rowid to delete */
int count, /* If non-zero, increment the row change counter */
Trigger pTrigger, /* List of triggers to (potentially) fire */
int onconf /* Default ON CONFLICT policy for triggers */
)
{
Vdbe v = pParse.pVdbe; /* Vdbe */
int iOld = 0; /* First register in OLD.* array */
int iLabel; /* Label resolved to end of generated code */
/* Vdbe is guaranteed to have been allocated by this stage. */
Debug.Assert( v != null );
/* Seek cursor iCur to the row to delete. If this row no longer exists
** (this can happen if a trigger program has already deleted it), do
** not attempt to delete it or fire any DELETE triggers. */
iLabel = sqlite3VdbeMakeLabel( v );
sqlite3VdbeAddOp3( v, OP_NotExists, iCur, iLabel, iRowid );
/* If there are any triggers to fire, allocate a range of registers to
** use for the old.* references in the triggers. */
if ( sqlite3FkRequired( pParse, pTab, null, 0 ) != 0 || pTrigger != null )
{
u32 mask; /* Mask of OLD.* columns in use */
int iCol; /* Iterator used while populating OLD.* */
/* TODO: Could use temporary registers here. Also could attempt to
** avoid copying the contents of the rowid register. */
mask = sqlite3TriggerColmask(
pParse, pTrigger, null, 0, TRIGGER_BEFORE | TRIGGER_AFTER, pTab, onconf
);
mask |= sqlite3FkOldmask( pParse, pTab );
iOld = pParse.nMem + 1;
pParse.nMem += ( 1 + pTab.nCol );
/* Populate the OLD.* pseudo-table register array. These values will be
** used by any BEFORE and AFTER triggers that exist. */
sqlite3VdbeAddOp2( v, OP_Copy, iRowid, iOld );
for ( iCol = 0; iCol < pTab.nCol; iCol++ )
{
if ( mask == 0xffffffff || ( mask & ( 1 << iCol ) ) != 0 )
{
sqlite3ExprCodeGetColumnOfTable( v, pTab, iCur, iCol, iOld + iCol + 1 );
}
}
/* Invoke BEFORE DELETE trigger programs. */
sqlite3CodeRowTrigger( pParse, pTrigger,
TK_DELETE, null, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
);
/* Seek the cursor to the row to be deleted again. It may be that
** the BEFORE triggers coded above have already removed the row
** being deleted. Do not attempt to delete the row a second time, and
** do not fire AFTER triggers. */
sqlite3VdbeAddOp3( v, OP_NotExists, iCur, iLabel, iRowid );
/* Do FK processing. This call checks that any FK constraints that
** refer to this table (i.e. constraints attached to other tables)
** are not violated by deleting this row. */
sqlite3FkCheck( pParse, pTab, iOld, 0 );
}
/* Delete the index and table entries. Skip this step if pTab is really
** a view (in which case the only effect of the DELETE statement is to
** fire the INSTEAD OF triggers). */
if ( pTab.pSelect == null )
{
sqlite3GenerateRowIndexDelete( pParse, pTab, iCur, 0 );
sqlite3VdbeAddOp2( v, OP_Delete, iCur, ( count != 0 ? (int)OPFLAG_NCHANGE : 0 ) );
if ( count != 0 )
{
sqlite3VdbeChangeP4( v, -1, pTab.zName, P4_TRANSIENT );
}
}
/* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
** handle rows (possibly in other tables) that refer via a foreign key
** to the row just deleted. */
sqlite3FkActions( pParse, pTab, null, iOld );
/* Invoke AFTER DELETE trigger programs. */
sqlite3CodeRowTrigger( pParse, pTrigger,
TK_DELETE, null, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
);
/* Jump here if the row had already been deleted before any BEFORE
** trigger programs were invoked. Or if a trigger program throws a
** RAISE(IGNORE) exception. */
sqlite3VdbeResolveLabel( v, iLabel );
}
/*
** This routine generates VDBE code that causes the deletion of all
** index entries associated with a single row of a single table.
**
** The VDBE must be in a particular state when this routine is called.
** These are the requirements:
**
** 1. A read/write cursor pointing to pTab, the table containing the row
** to be deleted, must be opened as cursor number "iCur".
**
** 2. Read/write cursors for all indices of pTab must be open as
** cursor number iCur+i for the i-th index.
**
** 3. The "iCur" cursor must be pointing to the row that is to be
** deleted.
*/
static void sqlite3GenerateRowIndexDelete(
Parse pParse, /* Parsing and code generating context */
Table pTab, /* Table containing the row to be deleted */
int iCur, /* VdbeCursor number for the table */
int nothing /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
)
{
int[] aRegIdx = null;
sqlite3GenerateRowIndexDelete( pParse, pTab, iCur, aRegIdx );
}
static void sqlite3GenerateRowIndexDelete(
Parse pParse, /* Parsing and code generating context */
Table pTab, /* Table containing the row to be deleted */
int iCur, /* VdbeCursor number for the table */
int[] aRegIdx /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
)
{
int i;
Index pIdx;
int r1;
for ( i = 1, pIdx = pTab.pIndex; pIdx != null; i++, pIdx = pIdx.pNext )
{
if ( aRegIdx != null && aRegIdx[i - 1] == 0 )
continue;
r1 = sqlite3GenerateIndexKey( pParse, pIdx, iCur, 0, false );
sqlite3VdbeAddOp3( pParse.pVdbe, OP_IdxDelete, iCur + i, r1, pIdx.nColumn + 1 );
}
}
/*
** Generate code that will assemble an index key and put it in register
** regOut. The key with be for index pIdx which is an index on pTab.
** iCur is the index of a cursor open on the pTab table and pointing to
** the entry that needs indexing.
**
** Return a register number which is the first in a block of
** registers that holds the elements of the index key. The
** block of registers has already been deallocated by the time
** this routine returns.
*/
static int sqlite3GenerateIndexKey(
Parse pParse, /* Parsing context */
Index pIdx, /* The index for which to generate a key */
int iCur, /* VdbeCursor number for the pIdx.pTable table */
int regOut, /* Write the new index key to this register */
bool doMakeRec /* Run the OP_MakeRecord instruction if true */
)
{
Vdbe v = pParse.pVdbe;
int j;
Table pTab = pIdx.pTable;
int regBase;
int nCol;
nCol = pIdx.nColumn;
regBase = sqlite3GetTempRange( pParse, nCol + 1 );
sqlite3VdbeAddOp2( v, OP_Rowid, iCur, regBase + nCol );
for ( j = 0; j < nCol; j++ )
{
int idx = pIdx.aiColumn[j];
if ( idx == pTab.iPKey )
{
sqlite3VdbeAddOp2( v, OP_SCopy, regBase + nCol, regBase + j );
}
else
{
sqlite3VdbeAddOp3( v, OP_Column, iCur, idx, regBase + j );
sqlite3ColumnDefault( v, pTab, idx, -1 );
}
}
if ( doMakeRec )
{
string zAff;
if ( pTab.pSelect != null|| ( pParse.db.flags & SQLITE_IdxRealAsInt ) != 0 )
{
zAff = "";
}
else
{
zAff = sqlite3IndexAffinityStr( v, pIdx );
}
sqlite3VdbeAddOp3( v, OP_MakeRecord, regBase, nCol + 1, regOut );
sqlite3VdbeChangeP4( v, -1, zAff, P4_TRANSIENT );
}
sqlite3ReleaseTempRange( pParse, regBase, nCol + 1 );
return regBase;
}
}
}
| |
using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Documents;
using System.Windows.Media;
namespace Sautom.Client.Ui.Controls
{
[TemplatePart(Name = "content", Type = typeof(Grid))]
[TemplatePart(Name = "contentHost", Type = typeof(ContentPresenter))]
[TemplatePart(Name = "dialog", Type = typeof(Popup))]
public class ModalDialogPopup : ContentControl, IModalDialogPopup
{
#region Constructors
static ModalDialogPopup()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(ModalDialogPopup),
new FrameworkPropertyMetadata(typeof(ModalDialogPopup)));
}
#endregion Constructors
#region Fields
public static readonly DependencyProperty IsOpenProperty =
DependencyProperty.Register("IsOpen", typeof(bool), typeof(ModalDialogPopup),
new PropertyMetadata(false, OnOpenChanged));
static AdornerLayer _myAdorner;
static FrameworkElement _rootElement;
Grid _content;
ContentPresenter _contentHost;
Popup _dialog;
bool _flagIsLoaded;
double _oldLeft;
double _oldTop;
Window _shell;
Shader _shader;
#endregion Fields
#region Properties
public Control HostedContent
{
get;
set;
}
public bool IsDesignMode
{
get
{
return DesignerProperties.GetIsInDesignMode(this);
}
}
public bool IsOpen
{
get
{
return (bool)GetValue(IsOpenProperty);
}
set
{
SetValue(IsOpenProperty, value);
}
}
public PopupAnimation PopupAnimation { get; set; } = PopupAnimation.Slide;
public Shader Shader
{
get
{
if (_shader == null && !IsDesignMode)
{
_shader = new Shader(_rootElement);
}
return _shader;
}
set
{
_shader = value;
}
}
#endregion Properties
#region Methods
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
_dialog = GetTemplateChild("dialog") as Popup;
_content = GetTemplateChild("content") as Grid;
_contentHost = GetTemplateChild("contentHost") as ContentPresenter;
if (_dialog != null)
{
_dialog.PopupAnimation = PopupAnimation;
Loaded += ModalDialogHostLoaded;
Unloaded += ModalDialogHostUnloaded;
}
if (_content != null)
{
_content.Background = Background;
}
if (_contentHost != null)
{
_contentHost.Content = HostedContent;
}
}
private static void OnOpenChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var context = (ModalDialogPopup)d;
if (context.IsDesignMode)
{
return;
}
//depdendency property changed callback fires
//too soon, before OnApplyTemplate. so workaround :|
if (context._flagIsLoaded)
{
if ((bool)e.NewValue)
{
context.Show();
}
else
{
context.Close();
}
}
}
void Close()
{
if (!IsDesignMode)
{
_dialog.IsOpen = false;
_myAdorner.Visibility = Visibility.Hidden;
}
}
void Show()
{
if (!IsDesignMode)
{
_dialog.IsOpen = true;
_myAdorner.Visibility = Visibility.Visible;
Reposition();
}
}
void EnsureRootElement()
{
if (_rootElement != null) return;
_rootElement = Parent as FrameworkElement;
while (_rootElement != null)
{
if (_rootElement.Parent is Window)
{
//we just want the direct child element of our window
//this is our root element.
break;
}
_rootElement = _rootElement.Parent as FrameworkElement;
}
}
void ModalDialogHostLoaded(object sender, RoutedEventArgs e)
{
_flagIsLoaded = true;
EnsureRootElement();
if (!IsDesignMode)
{
if (_shell == null)
{
_shell = (Window)_rootElement.Parent;
_shell.LocationChanged += ShellLocationChanged;
_shell.SizeChanged += ShellSizeChanged;
_shell.StateChanged += ShellStateChanged;
_oldTop = _shell.Top;
}
if (_myAdorner == null)
{
_myAdorner = AdornerLayer.GetAdornerLayer(_rootElement);
_myAdorner.Visibility = Visibility.Hidden;
_myAdorner.Add(Shader);
}
}
//first set PlacementTarget and Placement
if (_rootElement != null)
{
_dialog.PlacementTarget = _rootElement;
_dialog.Placement = PlacementMode.Relative;
}
if (IsOpen)
{
Show();
}
}
void ModalDialogHostUnloaded(object sender, RoutedEventArgs e)
{
Close();
}
void Reposition()
{
EnsureRootElement();
if (_rootElement == null)
{
throw new Exception("ModalDialogPopup was unable to locate the root element.");
}
FrameworkElement elem = (FrameworkElement)_dialog.Child;
double actualX = _rootElement.ActualWidth / 2 - elem.ActualWidth / 2;
double actualY = _rootElement.ActualHeight / 2 - elem.ActualHeight / 2;
_dialog.HorizontalOffset = Math.Abs(actualX);
_dialog.VerticalOffset = Math.Abs(actualY);
}
void ShellLocationChanged(object sender, EventArgs e)
{
Window s = (Window)sender;
FrameworkElement elem = (FrameworkElement)_dialog.Child;
double actualX = _rootElement.ActualWidth / 2 - elem.ActualWidth / 2;
double actualY = _rootElement.ActualHeight / 2 - elem.ActualHeight / 2;
double x = Math.Abs(_oldLeft - s.Left);
double y = Math.Abs(_oldTop - s.Top);
_dialog.HorizontalOffset = Math.Abs(x - actualX);
_dialog.VerticalOffset = Math.Abs(y - actualY);
_oldLeft = s.Left;
_oldTop = s.Top;
}
void ShellSizeChanged(object sender, SizeChangedEventArgs e)
{
Window s = (Window)sender;
Reposition();
}
void ShellStateChanged(object sender, EventArgs e)
{
Window s = (Window)sender;
switch (s.WindowState)
{
case WindowState.Maximized:
case WindowState.Normal:
if (IsOpen)
{
Show();
}
break;
case WindowState.Minimized:
if (IsOpen)
{
Close();
}
break;
}
}
#endregion Methods
}
public class Shader : Adorner
{
#region Methods
protected override void OnRender(DrawingContext drawingContext)
{
FrameworkElement elem = (FrameworkElement)AdornedElement;
Rect adornedElementRect = new Rect(0, 0, elem.ActualWidth, elem.ActualHeight);
drawingContext.DrawRectangle(Background, StrokeBorder, adornedElementRect);
}
#endregion Methods
#region Constructors
public Shader(UIElement adornedElement)
: base(adornedElement)
{
Background = new SolidColorBrush(Colors.Black);
Background.Opacity = 0.5d;
StrokeBorder = null;
}
public Shader(UIElement adornedElement, SolidColorBrush background, Pen strokeBorder)
: this(adornedElement)
{
//caller needs to have set opacity on background brush
Background = background;
StrokeBorder = strokeBorder;
}
#endregion Constructors
#region Properties
SolidColorBrush Background
{
get; }
Pen StrokeBorder
{
get; }
#endregion Properties
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Diagnostics;
namespace DotVVM.Framework.Utils
{
public static class ExpressionUtils
{
public static Expression ConvertToObject(Expression expr)
{
if (expr.Type == typeof(object)) return expr;
else if (expr.Type == typeof(void)) return WrapInReturnNull(expr);
else return Expression.Convert(expr, typeof(object));
}
public static Expression WrapInReturnNull(Expression expr)
{
return Expression.Block(expr, Expression.Constant(null));
}
public static Expression Indexer(Expression instance, Expression index)
{
return Expression.Property(instance,
instance.Type.GetTypeInfo().GetProperty("Item", new[] { index.Type }),
index);
}
public static Expression Replace(Expression ex, string paramName, Expression paramValue)
{
return Replace(ex, new[] { new KeyValuePair<string, Expression>(paramName, paramValue) });
}
public static Expression Replace(Expression ex, IEnumerable<KeyValuePair<string, Expression>> namedParameters)
{
var visitor = new ReplaceVisitor();
foreach (var p in namedParameters)
{
visitor.NamedParams.Add(p.Key, p.Value);
}
return visitor.Visit(ex);
}
public static Expression Replace(LambdaExpression ex, params Expression[] parameters)
{
var visitor = new ReplaceVisitor();
for (int i = 0; i < parameters.Length; i++)
{
visitor.Params.Add(ex.Parameters[i], parameters[i]);
}
var result = visitor.Visit(ex.Body);
if (result.CanReduce) result = result.Reduce();
return result;
}
[Conditional("DEBUG")]
public static void AddDebug(this IList<Expression> block, [CallerFilePath] string fileName = null, [CallerLineNumber] int lineNumber = -1)
{
if (fileName == null || lineNumber < 0) throw new ArgumentException();
block.Add(Expression.DebugInfo(Expression.SymbolDocument(fileName), lineNumber, 0, lineNumber + 1, 0));
}
#region Replace overloads
public static Expression Replace<T1, TRes>(Expression<Func<T1, TRes>> ex, Expression p1)
{
return Replace(ex as LambdaExpression, p1);
}
public static Expression Replace<T1, T2, TRes>(Expression<Func<T1, T2, TRes>> ex, Expression p1, Expression p2)
{
return Replace(ex as LambdaExpression, p1, p2);
}
public static Expression Replace<T1, T2, T3, TRes>(Expression<Func<T1, T2, T3, TRes>> ex, Expression p1, Expression p2, Expression p3)
{
return Replace(ex as LambdaExpression, p1, p2, p3);
}
public static Expression Replace<T1, T2, T3, T4, TRes>(Expression<Func<T1, T2, T3, T4, TRes>> ex, Expression p1, Expression p2, Expression p3, Expression p4)
{
return Replace(ex as LambdaExpression, p1, p2, p3, p4);
}
public static Expression Replace(Expression<Action> ex)
{
return Replace(ex as LambdaExpression);
}
public static Expression Replace<T1>(Expression<Action<T1>> ex, Expression p1)
{
return Replace(ex as LambdaExpression, p1);
}
public static Expression Replace<T1, T2>(Expression<Action<T1, T2>> ex, Expression p1, Expression p2)
{
return Replace(ex as LambdaExpression, p1, p2);
}
public static Expression Replace<T1, T2, T3>(Expression<Action<T1, T2, T3>> ex, Expression p1, Expression p2, Expression p3)
{
return Replace(ex as LambdaExpression, p1, p2, p3);
}
public static Expression Replace<T1, T2, T3, T4>(Expression<Action<T1, T2, T3, T4>> ex, Expression p1, Expression p2, Expression p3, Expression p4)
{
return Replace(ex as LambdaExpression, p1, p2, p3, p4);
}
#endregion
public static void ForEachMember(this Expression expression, Action<MemberInfo> memberAction)
{
var visitor = new MemberInfoWalkingVisitor();
visitor.MemberInfoAction = memberAction;
visitor.Visit(expression);
}
private class ReplaceVisitor : ExpressionVisitor
{
public Dictionary<ParameterExpression, Expression> Params { get; } = new Dictionary<ParameterExpression, Expression>();
public Dictionary<string, Expression> NamedParams { get; } = new Dictionary<string, Expression>();
protected override Expression VisitParameter(ParameterExpression node)
{
if (Params.ContainsKey(node)) return Params[node];
else if (!string.IsNullOrEmpty(node.Name) && NamedParams.ContainsKey(node.Name)) return NamedParams[node.Name];
else return base.VisitParameter(node);
}
}
private class MemberInfoWalkingVisitor: ExpressionVisitor
{
public Action<MemberInfo> MemberInfoAction { get; set; }
public Action<PropertyInfo> PropertyInfoAction { get; set; }
public Action<MethodInfo> MethodInfoAction { get; set; }
private void Invoke(MethodInfo method)
{
if (method == null) return;
if (MethodInfoAction != null) MethodInfoAction(method);
if (MemberInfoAction != null) MemberInfoAction(method);
}
private void Invoke(PropertyInfo property)
{
if (property == null) return;
if (MethodInfoAction != null) PropertyInfoAction(property);
if (MemberInfoAction != null) MemberInfoAction(property);
}
private void Invoke(MemberInfo memberInfo)
{
if (memberInfo == null) return;
if (memberInfo is PropertyInfo) Invoke(memberInfo as PropertyInfo);
else if (memberInfo is MethodInfo) Invoke(memberInfo as MethodInfo);
else if (MemberInfoAction != null) MemberInfoAction(memberInfo);
}
protected override Expression VisitMethodCall(MethodCallExpression node)
{
Invoke(node.Method);
return base.VisitMethodCall(node);
}
protected override Expression VisitBinary(BinaryExpression node)
{
Invoke(node.Method);
return base.VisitBinary(node);
}
protected override Expression VisitMember(MemberExpression node)
{
Invoke(node.Member);
return base.VisitMember(node);
}
protected override Expression VisitUnary(UnaryExpression node)
{
Invoke(node.Method);
return base.VisitUnary(node);
}
protected override Expression VisitNew(NewExpression node)
{
Invoke(node.Constructor);
return base.VisitNew(node);
}
}
/// <summary>
/// will execute operators, property and field accesses on constant expression, so it will be cleaner
/// </summary>
public static Expression OptimizeConstants(this Expression ex)
{
var v = new ConstantsOptimizingVisitor();
return v.Visit(ex);
}
private class ConstantsOptimizingVisitor : ExpressionVisitor
{
protected override Expression VisitMember(MemberExpression node)
{
if (node.Member.MemberType == MemberTypes.Property)
{
var i = Visit(node.Expression);
if (i.NodeType == ExpressionType.Constant)
{
var ce = (ConstantExpression)i;
var prop = ce.Type.GetProperty(node.Member.Name);
var val = prop.GetValue(ce.Value);
return Expression.Constant(val, prop.PropertyType);
}
else return node;
}
else if (node.Member.MemberType == MemberTypes.Field)
{
var i = Visit(node.Expression);
if (i.NodeType == ExpressionType.Constant)
{
var ce = (ConstantExpression)i;
var f = node.Member as FieldInfo;
var val = f.GetValue(ce.Value);
return Expression.Constant(val, f.FieldType);
}
else return node;
}
else return base.VisitMember(node);
}
protected override Expression VisitBinary(BinaryExpression node)
{
var l = Visit(node.Left);
var lc = l as ConstantExpression;
var r = Visit(node.Right);
var rc = r as ConstantExpression;
if (lc != null && rc != null)
{
if (node.Method != null)
return Expression.Constant(node.Method.Invoke(null, new object[] { lc.Value, rc.Value }));
else return node;
}
else return base.VisitBinary(node);
}
protected override Expression VisitUnary(UnaryExpression node)
{
var op = Visit(node.Operand);
if (op is ConstantExpression)
{
return Expression.Constant(
node.Method.Invoke(null, new object[] { (op as ConstantExpression).Value }), node.Type);
}
else return base.VisitUnary(node);
}
}
}
}
| |
//
// (C) Copyright 2003-2011 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
namespace Revit.SDK.Samples.ImportExport.CS
{
/// <summary>
/// Provide a dialog which provides the options of lower priority information
/// for export DWF format
/// </summary>
partial class ExportDWFOptionForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.checkBoxRoomsAndAreas = new System.Windows.Forms.CheckBox();
this.checkBoxModelElements = new System.Windows.Forms.CheckBox();
this.buttonOK = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.checkBoxMergeViews = new System.Windows.Forms.CheckBox();
this.groupBoxGraphicsSetting = new System.Windows.Forms.GroupBox();
this.comboBoxImageQuality = new System.Windows.Forms.ComboBox();
this.labelImageQuality = new System.Windows.Forms.Label();
this.radioButtonCompressedFormat = new System.Windows.Forms.RadioButton();
this.radioButtonStandardFormat = new System.Windows.Forms.RadioButton();
this.groupBox1.SuspendLayout();
this.groupBoxGraphicsSetting.SuspendLayout();
this.SuspendLayout();
//
// groupBox1
//
this.groupBox1.Controls.Add(this.checkBoxRoomsAndAreas);
this.groupBox1.Controls.Add(this.checkBoxModelElements);
this.groupBox1.Location = new System.Drawing.Point(13, 13);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(308, 68);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Export Object Data";
//
// checkBoxRoomsAndAreas
//
this.checkBoxRoomsAndAreas.AutoSize = true;
this.checkBoxRoomsAndAreas.Location = new System.Drawing.Point(10, 43);
this.checkBoxRoomsAndAreas.Name = "checkBoxRoomsAndAreas";
this.checkBoxRoomsAndAreas.Size = new System.Drawing.Size(110, 17);
this.checkBoxRoomsAndAreas.TabIndex = 0;
this.checkBoxRoomsAndAreas.Text = "Rooms and Areas";
this.checkBoxRoomsAndAreas.UseVisualStyleBackColor = true;
//
// checkBoxModelElements
//
this.checkBoxModelElements.AutoSize = true;
this.checkBoxModelElements.Location = new System.Drawing.Point(10, 20);
this.checkBoxModelElements.Name = "checkBoxModelElements";
this.checkBoxModelElements.Size = new System.Drawing.Size(100, 17);
this.checkBoxModelElements.TabIndex = 0;
this.checkBoxModelElements.Text = "Model Elements";
this.checkBoxModelElements.UseVisualStyleBackColor = true;
this.checkBoxModelElements.CheckedChanged += new System.EventHandler(this.checkBoxModelElements_CheckedChanged);
//
// buttonOK
//
this.buttonOK.DialogResult = System.Windows.Forms.DialogResult.OK;
this.buttonOK.Location = new System.Drawing.Point(114, 230);
this.buttonOK.Name = "buttonOK";
this.buttonOK.Size = new System.Drawing.Size(91, 23);
this.buttonOK.TabIndex = 1;
this.buttonOK.Text = "&OK";
this.buttonOK.UseVisualStyleBackColor = true;
this.buttonOK.Click += new System.EventHandler(this.buttonOK_Click);
//
// buttonCancel
//
this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.buttonCancel.Location = new System.Drawing.Point(220, 230);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(101, 23);
this.buttonCancel.TabIndex = 1;
this.buttonCancel.Text = "&Cancel";
this.buttonCancel.UseVisualStyleBackColor = true;
//
// checkBoxMergeViews
//
this.checkBoxMergeViews.AutoSize = true;
this.checkBoxMergeViews.Location = new System.Drawing.Point(23, 195);
this.checkBoxMergeViews.Name = "checkBoxMergeViews";
this.checkBoxMergeViews.Size = new System.Drawing.Size(226, 17);
this.checkBoxMergeViews.TabIndex = 4;
this.checkBoxMergeViews.Text = "Create separate files for each view/sheet";
this.checkBoxMergeViews.UseVisualStyleBackColor = true;
//
// groupBoxGraphicsSetting
//
this.groupBoxGraphicsSetting.Controls.Add(this.comboBoxImageQuality);
this.groupBoxGraphicsSetting.Controls.Add(this.labelImageQuality);
this.groupBoxGraphicsSetting.Controls.Add(this.radioButtonCompressedFormat);
this.groupBoxGraphicsSetting.Controls.Add(this.radioButtonStandardFormat);
this.groupBoxGraphicsSetting.Location = new System.Drawing.Point(13, 88);
this.groupBoxGraphicsSetting.Name = "groupBoxGraphicsSetting";
this.groupBoxGraphicsSetting.Size = new System.Drawing.Size(308, 100);
this.groupBoxGraphicsSetting.TabIndex = 5;
this.groupBoxGraphicsSetting.TabStop = false;
this.groupBoxGraphicsSetting.Text = "Graphics Settings";
//
// comboBoxImageQuality
//
this.comboBoxImageQuality.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxImageQuality.FormattingEnabled = true;
this.comboBoxImageQuality.Location = new System.Drawing.Point(129, 66);
this.comboBoxImageQuality.Name = "comboBoxImageQuality";
this.comboBoxImageQuality.Size = new System.Drawing.Size(163, 21);
this.comboBoxImageQuality.TabIndex = 3;
//
// labelImageQuality
//
this.labelImageQuality.AutoSize = true;
this.labelImageQuality.Location = new System.Drawing.Point(54, 69);
this.labelImageQuality.Name = "labelImageQuality";
this.labelImageQuality.Size = new System.Drawing.Size(78, 13);
this.labelImageQuality.TabIndex = 2;
this.labelImageQuality.Text = "Image Quality:";
//
// radioButtonCompressedFormat
//
this.radioButtonCompressedFormat.AutoSize = true;
this.radioButtonCompressedFormat.Location = new System.Drawing.Point(10, 41);
this.radioButtonCompressedFormat.Name = "radioButtonCompressedFormat";
this.radioButtonCompressedFormat.Size = new System.Drawing.Size(170, 17);
this.radioButtonCompressedFormat.TabIndex = 0;
this.radioButtonCompressedFormat.TabStop = true;
this.radioButtonCompressedFormat.Text = "Use compressed raster format";
this.radioButtonCompressedFormat.UseVisualStyleBackColor = true;
this.radioButtonCompressedFormat.CheckedChanged += new System.EventHandler(this.radioButtonCompressedFormat_CheckedChanged);
//
// radioButtonStandardFormat
//
this.radioButtonStandardFormat.AutoSize = true;
this.radioButtonStandardFormat.Location = new System.Drawing.Point(10, 20);
this.radioButtonStandardFormat.Name = "radioButtonStandardFormat";
this.radioButtonStandardFormat.Size = new System.Drawing.Size(124, 17);
this.radioButtonStandardFormat.TabIndex = 0;
this.radioButtonStandardFormat.TabStop = true;
this.radioButtonStandardFormat.Text = "Use standard format";
this.radioButtonStandardFormat.UseVisualStyleBackColor = true;
//
// ExportDWFOptionForm
//
this.AcceptButton = this.buttonOK;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.buttonCancel;
this.ClientSize = new System.Drawing.Size(335, 262);
this.Controls.Add(this.groupBoxGraphicsSetting);
this.Controls.Add(this.checkBoxMergeViews);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonOK);
this.Controls.Add(this.groupBox1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "ExportDWFOptionForm";
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Export DWF Options";
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.groupBoxGraphicsSetting.ResumeLayout(false);
this.groupBoxGraphicsSetting.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.CheckBox checkBoxRoomsAndAreas;
private System.Windows.Forms.CheckBox checkBoxModelElements;
private System.Windows.Forms.Button buttonOK;
private System.Windows.Forms.Button buttonCancel;
private System.Windows.Forms.CheckBox checkBoxMergeViews;
private System.Windows.Forms.GroupBox groupBoxGraphicsSetting;
private System.Windows.Forms.ComboBox comboBoxImageQuality;
private System.Windows.Forms.Label labelImageQuality;
private System.Windows.Forms.RadioButton radioButtonCompressedFormat;
private System.Windows.Forms.RadioButton radioButtonStandardFormat;
}
}
| |
using Pathfinding;
using UnityEditor;
using UnityEngine;
namespace Pathfinding {
public class GraphEditor : GraphEditorBase {
public AstarPathEditor editor;
/** Called by editor scripts to rescan the graphs e.g when the user moved a graph.
* Will only scan graphs if not playing and time to scan last graph was less than some constant (to avoid lag with large graphs) */
public bool AutoScan () {
if (!Application.isPlaying && AstarPath.active != null && AstarPath.active.lastScanTime < 0.11F) {
AstarPath.active.Scan ();
return true;
}
return false;
}
public virtual void OnEnable () {
}
public virtual void OnDisable () {
}
public virtual void OnDestroy () {
}
public Object ObjectField (string label, Object obj, System.Type objType, bool allowSceneObjects) {
return ObjectField (new GUIContent (label),obj,objType,allowSceneObjects);
}
public Object ObjectField (GUIContent label, Object obj, System.Type objType, bool allowSceneObjects) {
obj = EditorGUILayout.ObjectField (label, obj, objType, allowSceneObjects);
if (obj != null) {
if (allowSceneObjects && !EditorUtility.IsPersistent (obj)) {
//Object is in the scene
var com = obj as Component;
var go = obj as GameObject;
if (com != null) {
go = com.gameObject;
}
if (go != null) {
var urh = go.GetComponent<UnityReferenceHelper> ();
if (urh == null) {
if (FixLabel ("Object's GameObject must have a UnityReferenceHelper component attached")) {
go.AddComponent<UnityReferenceHelper>();
}
}
}
} else if (EditorUtility.IsPersistent (obj)) {
string path = AssetDatabase.GetAssetPath (obj);
System.Text.RegularExpressions.Regex rg = new System.Text.RegularExpressions.Regex(@"Resources[/|\\][^/]*$");
if (!rg.IsMatch(path)) {
if (FixLabel ("Object must be in the 'Resources' folder, top level")) {
if (!System.IO.Directory.Exists (Application.dataPath+"/Resources")) {
System.IO.Directory.CreateDirectory (Application.dataPath+"/Resources");
AssetDatabase.Refresh ();
}
string ext = System.IO.Path.GetExtension(path);
string error = AssetDatabase.MoveAsset (path,"Assets/Resources/"+obj.name+ext);
if (error == "") {
//Debug.Log ("Successful move");
path = AssetDatabase.GetAssetPath (obj);
} else {
Debug.LogError ("Couldn't move asset - "+error);
}
}
}
if (!AssetDatabase.IsMainAsset (obj) && obj.name != AssetDatabase.LoadMainAssetAtPath (path).name) {
if (FixLabel ("Due to technical reasons, the main asset must\nhave the same name as the referenced asset")) {
string error = AssetDatabase.RenameAsset (path,obj.name);
if (error == "") {
//Debug.Log ("Successful");
} else {
Debug.LogError ("Couldn't rename asset - "+error);
}
}
}
}
}
return obj;
}
/** Draws common graph settings */
public void OnBaseInspectorGUI (NavGraph target) {
int penalty = EditorGUILayout.IntField (new GUIContent ("Initial Penalty","Initial Penalty for nodes in this graph. Set during Scan."),(int)target.initialPenalty);
if (penalty < 0) penalty = 0;
target.initialPenalty = (uint)penalty;
}
/** Override to implement graph inspectors */
public virtual void OnInspectorGUI (NavGraph target) {
}
/** Override to implement scene GUI drawing for the graph */
public virtual void OnSceneGUI (NavGraph target) {
}
/** Override to implement scene Gizmos drawing for the graph editor */
public virtual void OnDrawGizmos () {
}
/** Draws a thin separator line */
public void Separator () {
GUIStyle separator = AstarPathEditor.astarSkin.FindStyle ("PixelBox3Separator");
if (separator == null) {
separator = new GUIStyle ();
}
Rect r = GUILayoutUtility.GetRect (new GUIContent (),separator);
if (Event.current.type == EventType.Repaint) {
separator.Draw (r,false,false,false,false);
}
}
/** Draws a small help box with a 'Fix' button to the right. \returns Boolean - Returns true if the button was clicked */
public bool FixLabel (string label, string buttonLabel = "Fix", int buttonWidth = 40) {
bool returnValue = false;
GUILayout.BeginHorizontal ();
GUILayout.Space (14*EditorGUI.indentLevel);
GUILayout.BeginHorizontal (AstarPathEditor.helpBox);
GUILayout.Label (label, EditorGUIUtility.isProSkin ? EditorStyles.whiteMiniLabel : EditorStyles.miniLabel,GUILayout.ExpandWidth (true));
if (GUILayout.Button (buttonLabel,EditorStyles.miniButton,GUILayout.Width (buttonWidth))) {
returnValue = true;
}
GUILayout.EndHorizontal ();
GUILayout.EndHorizontal ();
return returnValue;
}
/** Draws a small help box.
* Works with EditorGUI.indentLevel
*/
public void HelpBox (string label) {
GUILayout.BeginHorizontal ();
GUILayout.Space (14*EditorGUI.indentLevel);
GUILayout.Label (label, AstarPathEditor.helpBox);
GUILayout.EndHorizontal ();
}
/** Draws a toggle with a bold label to the right. Does not enable or disable GUI */
public bool ToggleGroup (string label, bool value) {
return ToggleGroup (new GUIContent (label),value);
}
/** Draws a toggle with a bold label to the right. Does not enable or disable GUI */
public bool ToggleGroup (GUIContent label, bool value) {
GUILayout.BeginHorizontal ();
GUILayout.Space (13*EditorGUI.indentLevel);
value = GUILayout.Toggle (value,"",GUILayout.Width (10));
GUIStyle boxHeader = AstarPathEditor.astarSkin.FindStyle ("CollisionHeader");
if (GUILayout.Button (label,boxHeader, GUILayout.Width (100))) {
value = !value;
}
GUILayout.EndHorizontal ();
return value;
}
/** Draws a wire cube using handles */
public static void DrawWireCube (Vector3 center, Vector3 size) {
size *= 0.5F;
Vector3 dx = new Vector3 (size.x,0,0);
Vector3 dy = new Vector3 (0,size.y,0);
Vector3 dz = new Vector3 (0,0,size.z);
Vector3 p1 = center-dy-dz-dx;
Vector3 p2 = center-dy-dz+dx;
Vector3 p3 = center-dy+dz+dx;
Vector3 p4 = center-dy+dz-dx;
Vector3 p5 = center+dy-dz-dx;
Vector3 p6 = center+dy-dz+dx;
Vector3 p7 = center+dy+dz+dx;
Vector3 p8 = center+dy+dz-dx;
Handles.DrawLine (p1,p2);
Handles.DrawLine (p2,p3);
Handles.DrawLine (p3,p4);
Handles.DrawLine (p4,p1);
Handles.DrawLine (p5,p6);
Handles.DrawLine (p6,p7);
Handles.DrawLine (p7,p8);
Handles.DrawLine (p8,p5);
Handles.DrawLine (p1,p5);
Handles.DrawLine (p2,p6);
Handles.DrawLine (p3,p7);
Handles.DrawLine (p4,p8);
}
}
}
| |
#region Apache Notice
/*****************************************************************************
* $Header: $
* $Revision: $
* $Date: $
*
* iBATIS.NET Data Mapper
* Copyright (C) 2004 - Gilles Bayon
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
********************************************************************************/
#endregion
#region Imports
using System;
using System.Collections;
using System.Data;
using System.Reflection;
using System.Text;
using IBatisNet.Common;
using IBatisNet.Common.Logging;
using IBatisNet.Common.Utilities.Objects;
using IBatisNet.DataMapper.Commands;
using IBatisNet.DataMapper.Configuration.ParameterMapping;
using IBatisNet.DataMapper.Configuration.ResultMapping;
using IBatisNet.DataMapper.Configuration.Statements;
using IBatisNet.DataMapper.Exceptions;
using IBatisNet.DataMapper.Scope;
using IBatisNet.DataMapper.TypeHandlers;
#endregion
namespace IBatisNet.DataMapper.MappedStatements
{
/// <summary>
/// Summary description for MappedStatement.
/// </summary>
public class MappedStatement : IMappedStatement
{
/// <summary>
/// Event launch on exceute query
/// </summary>
public event ExecuteEventHandler Execute;
/// <summary>
/// Enumeration of the ExecuteQuery method.
/// </summary>
private enum ExecuteMethod : int
{
ExecuteQueryForObject =0,
ExecuteQueryForIList,
ExecuteQueryForArrayList,
ExecuteQueryForStrongTypedIList
}
/// <summary>
/// All data tor retrieve 'select' result property
/// </summary>
/// <remarks>
/// As ADO.NET allows to open DataReader per connection at once, we keep
/// all th data to make the open the 'whish' DataReader after having closed the current.
/// </remarks>
private class PostBindind
{
#region Fields
private IMappedStatement _statement = null;
private ResultProperty _property = null;
private object _target = null;
private object _keys = null;
private ExecuteMethod _method = ExecuteMethod.ExecuteQueryForIList;
#endregion
#region Properties
/// <summary>
///
/// </summary>
public IMappedStatement Statement
{
set { _statement = value; }
get { return _statement; }
}
/// <summary>
///
/// </summary>
public ResultProperty ResultProperty
{
set { _property = value; }
get { return _property; }
}
/// <summary>
///
/// </summary>
public object Target
{
set { _target = value; }
get { return _target; }
}
/// <summary>
///
/// </summary>
public object Keys
{
set { _keys = value; }
get { return _keys; }
}
/// <summary>
///
/// </summary>
public ExecuteMethod Method
{
set { _method = value; }
get { return _method; }
}
#endregion
}
#region Fields
// Magic number used to set the the maximum number of rows returned to 'all'.
internal const int NO_MAXIMUM_RESULTS = -1;
// Magic number used to set the the number of rows skipped to 'none'.
internal const int NO_SKIPPED_RESULTS = -1;
private static readonly ILog _logger = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType );
private IStatement _statement = null;
private SqlMapper _sqlMap = null;
private IPreparedCommand _preparedCommand = null;
#endregion
#region Properties
/// <summary>
/// The IPreparedCommand to use
/// </summary>
public IPreparedCommand PreparedCommand
{
get { return _preparedCommand; }
}
/// <summary>
/// Name used to identify the MappedStatement amongst the others.
/// This the name of the SQL statement by default.
/// </summary>
public string Name
{
get { return _statement.Id; }
}
/// <summary>
/// The SQL statment used by this MappedStatement
/// </summary>
public IStatement Statement
{
get { return _statement; }
}
/// <summary>
/// The SqlMap used by this MappedStatement
/// </summary>
public SqlMapper SqlMap
{
get { return _sqlMap; }
}
#endregion
#region Constructor (s) / Destructor
/// <summary>
/// Constructor
/// </summary>
/// <param name="sqlMap">An SqlMap</param>
/// <param name="statement">An SQL statement</param>
internal MappedStatement( SqlMapper sqlMap, IStatement statement )
{
_sqlMap = sqlMap;
_statement = statement;
_preparedCommand = PreparedCommandFactory.GetPreparedCommand(sqlMap.UseEmbedStatementParams);
}
#endregion
#region Methods
/// <summary>
///
/// </summary>
/// <param name="request"></param>
/// <param name="reader"></param>
/// <param name="resultMap"></param>
/// <param name="resultObject"></param>
private bool FillObjectWithReaderAndResultMap(RequestScope request,IDataReader reader,
ResultMap resultMap, object resultObject)
{
bool dataFound = false;
// For each Property in the ResultMap, set the property in the object
foreach(DictionaryEntry entry in resultMap.ColumnsToPropertiesMap)
{
request.IsRowDataFound = false;
ResultProperty property = (ResultProperty)entry.Value;
SetObjectProperty(request, resultMap, property, ref resultObject, reader);
dataFound = dataFound || request.IsRowDataFound;
}
request.IsRowDataFound = dataFound;
return dataFound;
}
/// <summary>
///
/// </summary>
/// <param name="request"></param>
/// <param name="reader"></param>
/// <param name="resultObject"></param>
/// <returns></returns>
private object ApplyResultMap(RequestScope request, IDataReader reader, object resultObject)
{
object outObject = resultObject;
// If there's an ResultMap, use it
if (request.ResultMap != null)
{
ResultMap resultMap = request.GetResultMap(reader);
if (outObject == null)
{
outObject = resultMap.CreateInstanceOfResult();
}
// For each Property in the ResultMap, set the property in the object
foreach(DictionaryEntry entry in resultMap.ColumnsToPropertiesMap)
{
ResultProperty property = (ResultProperty)entry.Value;
SetObjectProperty(request, resultMap, property, ref outObject, reader);
}
}
else // else try to use a ResultClass
{
if (_statement.ResultClass != null)
{
if (outObject == null)
{
outObject = _statement.CreateInstanceOfResultClass();
}
// Check if the ResultClass is a 'primitive' Type
if (_sqlMap.TypeHandlerFactory.IsSimpleType(_statement.ResultClass))
{
// Create a ResultMap
ResultMap resultMap = new ResultMap();
// Create a ResultProperty
ResultProperty property = new ResultProperty();
property.PropertyName = "value";
property.ColumnIndex = 0;
property.TypeHandler = _sqlMap.TypeHandlerFactory.GetTypeHandler(outObject.GetType());
resultMap.AddResultPropery(property);
SetObjectProperty(request, request.ResultMap, property, ref outObject, reader);
}
else if (outObject is Hashtable)
{
for (int i = 0; i < reader.FieldCount; i++)
{
string columnName = reader.GetName(i);
((Hashtable) outObject).Add(columnName, reader.GetValue(i));
}
}
else
{
AutoMapReader( reader, ref outObject);
}
}
}
return outObject;
}
/// <summary>
/// Retrieve the output parameter and map them on the result object.
/// This routine is only use is you specified a ParameterMap and some output attribute
/// or if you use a store procedure with output parameter...
/// </summary>
/// <param name="request"></param>
/// <param name="session">The current session.</param>
/// <param name="result">The result object.</param>
/// <param name="command">The command sql.</param>
private void RetrieveOutputParameters(RequestScope request, IDalSession session, IDbCommand command, object result)
{
if (request.ParameterMap != null)
{
for(int i=0; i<request.ParameterMap.PropertiesList.Count; i++)
{
ParameterProperty mapping = request.ParameterMap.GetProperty(i);
if (mapping.Direction == ParameterDirection.Output ||
mapping.Direction == ParameterDirection.InputOutput)
{
string parameterName = string.Empty;
if (session.DataSource.Provider.UseParameterPrefixInParameter == false)
{
parameterName = mapping.ColumnName;
}
else
{
parameterName = session.DataSource.Provider.ParameterPrefix +
mapping.ColumnName;
}
if (mapping.TypeHandler == null) // Find the TypeHandler
{
lock(mapping)
{
if (mapping.TypeHandler == null)
{
Type propertyType =ObjectProbe.GetPropertyTypeForGetter(result,mapping.PropertyName);
mapping.TypeHandler = _sqlMap.TypeHandlerFactory.GetTypeHandler(propertyType);
}
}
}
object dataBaseValue = mapping.TypeHandler.GetDataBaseValue( ((IDataParameter)command.Parameters[parameterName]).Value, result.GetType() );
request.IsRowDataFound = request.IsRowDataFound || (dataBaseValue != null);
ObjectProbe.SetPropertyValue(result, mapping.PropertyName, dataBaseValue);
}
}
}
}
#region ExecuteForObject
/// <summary>
/// Executes an SQL statement that returns a single row as an Object.
/// </summary>
/// <param name="session">The session used to execute the statement.</param>
/// <param name="parameterObject">The object used to set the parameters in the SQL.</param>
/// <returns>The object</returns>
public virtual object ExecuteQueryForObject( IDalSession session, object parameterObject )
{
return ExecuteQueryForObject(session, parameterObject, null);
}
/// <summary>
/// Executes an SQL statement that returns a single row as an Object of the type of
/// the resultObject passed in as a parameter.
/// </summary>
/// <param name="session">The session used to execute the statement.</param>
/// <param name="parameterObject">The object used to set the parameters in the SQL.</param>
/// <param name="resultObject">The result object.</param>
/// <returns>The object</returns>
public virtual object ExecuteQueryForObject(IDalSession session, object parameterObject, object resultObject )
{
object obj = null;
RequestScope request = _statement.Sql.GetRequestScope(parameterObject, session);;
obj = RunQueryForObject(request, session, parameterObject, resultObject);
return obj;
}
/// <summary>
/// Executes an SQL statement that returns a single row as an Object of the type of
/// the resultObject passed in as a parameter.
/// </summary>
/// <param name="request">The request scope.</param>
/// <param name="session">The session used to execute the statement.</param>
/// <param name="parameterObject">The object used to set the parameters in the SQL.</param>
/// <param name="resultObject">The result object.</param>
/// <returns>The object</returns>
internal object RunQueryForObject(RequestScope request, IDalSession session, object parameterObject, object resultObject )
{
object result = resultObject;
using ( IDbCommand command = _preparedCommand.Create( request, session, this.Statement, parameterObject ) )
{
using ( IDataReader reader = command.ExecuteReader() )
{
if ( reader.Read() )
{
result = ApplyResultMap(request, reader, resultObject);
}
}
ExecutePostSelect( session, request);
#region remark
// If you are using the OleDb data provider (as you are), you need to close the
// DataReader before output parameters are visible.
#endregion
RetrieveOutputParameters(request, session, command, parameterObject);
}
RaiseExecuteEvent();
return result;
}
#endregion
#region ExecuteQueryForList
/// <summary>
/// Runs a query with a custom object that gets a chance
/// to deal with each row as it is processed.
/// </summary>
/// <param name="session">The session used to execute the statement.</param>
/// <param name="parameterObject">The object used to set the parameters in the SQL.</param>
/// <param name="rowDelegate"></param>
public virtual IList ExecuteQueryForRowDelegate( IDalSession session, object parameterObject, SqlMapper.RowDelegate rowDelegate )
{
RequestScope request = _statement.Sql.GetRequestScope(parameterObject, session);;
if (rowDelegate == null)
{
throw new DataMapperException("A null RowDelegate was passed to QueryForRowDelegate.");
}
return RunQueryForList(request, session, parameterObject, NO_SKIPPED_RESULTS, NO_MAXIMUM_RESULTS, rowDelegate);
}
/// <summary>
/// Runs a query with a custom object that gets a chance
/// to deal with each row as it is processed.
/// </summary>
/// <param name="session">The session used to execute the statement</param>
/// <param name="parameterObject">The object used to set the parameters in the SQL. </param>
/// <param name="keyProperty">The property of the result object to be used as the key. </param>
/// <param name="valueProperty">The property of the result object to be used as the value (or null)</param>
/// <param name="rowDelegate"></param>
/// <returns>A hashtable of object containing the rows keyed by keyProperty.</returns>
///<exception cref="DataMapperException">If a transaction is not in progress, or the database throws an exception.</exception>
public virtual IDictionary ExecuteQueryForMapWithRowDelegate( IDalSession session, object parameterObject, string keyProperty, string valueProperty, SqlMapper.DictionaryRowDelegate rowDelegate )
{
RequestScope request = _statement.Sql.GetRequestScope(parameterObject, session);;
if (rowDelegate == null)
{
throw new DataMapperException("A null DictionaryRowDelegate was passed to QueryForMapWithRowDelegate.");
}
return RunQueryForMap(request, session, parameterObject, keyProperty, valueProperty, rowDelegate);
}
/// <summary>
/// Executes the SQL and retuns all rows selected. This is exactly the same as
/// calling ExecuteQueryForList(session, parameterObject, NO_SKIPPED_RESULTS, NO_MAXIMUM_RESULTS).
/// </summary>
/// <param name="session">The session used to execute the statement.</param>
/// <param name="parameterObject">The object used to set the parameters in the SQL.</param>
/// <returns>A List of result objects.</returns>
public virtual IList ExecuteQueryForList( IDalSession session, object parameterObject )
{
return ExecuteQueryForList( session, parameterObject, NO_SKIPPED_RESULTS, NO_MAXIMUM_RESULTS);
}
/// <summary>
/// Executes the SQL and retuns a subset of the rows selected.
/// </summary>
/// <param name="session">The session used to execute the statement.</param>
/// <param name="parameterObject">The object used to set the parameters in the SQL.</param>
/// <param name="skipResults">The number of rows to skip over.</param>
/// <param name="maxResults">The maximum number of rows to return.</param>
/// <returns>A List of result objects.</returns>
public virtual IList ExecuteQueryForList( IDalSession session, object parameterObject, int skipResults, int maxResults )
{
IList list = null;
RequestScope request = _statement.Sql.GetRequestScope(parameterObject, session);;
list = RunQueryForList(request, session, parameterObject, skipResults, maxResults, null);
return list;
}
/// <summary>
/// Executes the SQL and retuns a List of result objects.
/// </summary>
/// <param name="request">The request scope.</param>
/// <param name="session">The session used to execute the statement.</param>
/// <param name="parameterObject">The object used to set the parameters in the SQL.</param>
/// <param name="skipResults">The number of rows to skip over.</param>
/// <param name="maxResults">The maximum number of rows to return.</param>
/// <param name="rowDelegate"></param>
/// <returns>A List of result objects.</returns>
internal IList RunQueryForList(RequestScope request, IDalSession session, object parameterObject, int skipResults, int maxResults, SqlMapper.RowDelegate rowDelegate)
{
IList list = null;
using ( IDbCommand command = _preparedCommand.Create( request, session, this.Statement, parameterObject ) )
{
if (_statement.ListClass == null)
{
list = new ArrayList();
}
else
{
list = _statement.CreateInstanceOfListClass();
}
using ( IDataReader reader = command.ExecuteReader() )
{
// skip results
for (int i = 0; i < skipResults; i++)
{
if (!reader.Read())
{
break;
}
}
int n = 0;
if (rowDelegate == null)
{
while ( (maxResults == NO_MAXIMUM_RESULTS || n < maxResults)
&& reader.Read() )
{
object obj = ApplyResultMap(request, reader, null);
list.Add( obj );
n++;
}
}
else
{
while ( (maxResults == NO_MAXIMUM_RESULTS || n < maxResults)
&& reader.Read() )
{
object obj = ApplyResultMap(request, reader, null);
rowDelegate(obj, parameterObject, list);
n++;
}
}
}
ExecutePostSelect( session, request);
RetrieveOutputParameters(request, session, command, parameterObject);
}
return list;
}
/// <summary>
/// Executes the SQL and and fill a strongly typed collection.
/// </summary>
/// <param name="session">The session used to execute the statement.</param>
/// <param name="parameterObject">The object used to set the parameters in the SQL.</param>
/// <param name="resultObject">A strongly typed collection of result objects.</param>
public virtual void ExecuteQueryForList(IDalSession session, object parameterObject, IList resultObject )
{
RequestScope request = _statement.Sql.GetRequestScope(parameterObject, session);;
//using ( IDbCommand command = CreatePreparedCommand(request, session, parameterObject ) )
using ( IDbCommand command = _preparedCommand.Create( request, session, this.Statement, parameterObject ) )
{
using ( IDataReader reader = command.ExecuteReader() )
{
while ( reader.Read() )
{
object obj = ApplyResultMap(request, reader, null);
resultObject.Add( obj );
}
}
ExecutePostSelect( session, request);
RetrieveOutputParameters(request, session, command, parameterObject);
}
}
#endregion
#region ExecuteUpdate, ExecuteInsert
/// <summary>
/// Execute an update statement. Also used for delete statement.
/// Return the number of row effected.
/// </summary>
/// <param name="session">The session used to execute the statement.</param>
/// <param name="parameterObject">The object used to set the parameters in the SQL.</param>
/// <returns>The number of row effected.</returns>
public virtual int ExecuteUpdate(IDalSession session, object parameterObject )
{
int rows = 0; // the number of rows affected
RequestScope request = _statement.Sql.GetRequestScope(parameterObject, session);;
//using (IDbCommand command = CreatePreparedCommand(request, session, parameterObject ))
using ( IDbCommand command = _preparedCommand.Create( request, session, this.Statement, parameterObject ) )
{
rows = command.ExecuteNonQuery();
ExecutePostSelect( session, request);
RetrieveOutputParameters(request, session, command, parameterObject);
}
RaiseExecuteEvent();
return rows;
}
/// <summary>
/// Execute an insert statement. Fill the parameter object with
/// the ouput parameters if any, also could return the insert generated key
/// </summary>
/// <param name="session">The session</param>
/// <param name="parameterObject">The parameter object used to fill the statement.</param>
/// <returns>Can return the insert generated key.</returns>
public virtual object ExecuteInsert(IDalSession session, object parameterObject )
{
object generatedKey = null;
SelectKey selectKeyStatement = null;
RequestScope request = _statement.Sql.GetRequestScope(parameterObject, session);;
if (_statement is Insert)
{
selectKeyStatement = ((Insert)_statement).SelectKey;
}
if (selectKeyStatement != null && !selectKeyStatement.isAfter)
{
IMappedStatement mappedStatement = _sqlMap.GetMappedStatement( selectKeyStatement.Id );
generatedKey = mappedStatement.ExecuteQueryForObject(session, parameterObject);
ObjectProbe.SetPropertyValue(parameterObject, selectKeyStatement.PropertyName, generatedKey);
}
using ( IDbCommand command = _preparedCommand.Create( request, session, this.Statement, parameterObject ) )
{
if (_statement is Insert)
{
command.ExecuteNonQuery();
}
else
{
generatedKey = command.ExecuteScalar();
if ( (_statement.ResultClass!=null) &&
_sqlMap.TypeHandlerFactory.IsSimpleType(_statement.ResultClass) )
{
ITypeHandler typeHandler = _sqlMap.TypeHandlerFactory.GetTypeHandler(_statement.ResultClass);
generatedKey = typeHandler.GetDataBaseValue(generatedKey, _statement.ResultClass);
}
}
if (selectKeyStatement != null && selectKeyStatement.isAfter)
{
IMappedStatement mappedStatement = _sqlMap.GetMappedStatement( selectKeyStatement.Id );
generatedKey = mappedStatement.ExecuteQueryForObject(session, parameterObject);
ObjectProbe.SetPropertyValue(parameterObject, selectKeyStatement.PropertyName, generatedKey);
}
ExecutePostSelect( session, request);
RetrieveOutputParameters(request, session, command, parameterObject);
}
RaiseExecuteEvent();
return generatedKey;
}
#endregion
#region ExecuteQueryForMap
/// <summary>
/// Executes the SQL and retuns all rows selected in a map that is keyed on the property named
/// in the keyProperty parameter. The value at each key will be the value of the property specified
/// in the valueProperty parameter. If valueProperty is null, the entire result object will be entered.
/// </summary>
/// <param name="session">The session used to execute the statement</param>
/// <param name="parameterObject">The object used to set the parameters in the SQL. </param>
/// <param name="keyProperty">The property of the result object to be used as the key. </param>
/// <param name="valueProperty">The property of the result object to be used as the value (or null)</param>
/// <returns>A hashtable of object containing the rows keyed by keyProperty.</returns>
///<exception cref="DataMapperException">If a transaction is not in progress, or the database throws an exception.</exception>
public virtual IDictionary ExecuteQueryForMap( IDalSession session, object parameterObject, string keyProperty, string valueProperty )
{
IDictionary map = new Hashtable();
RequestScope request = _statement.Sql.GetRequestScope(parameterObject, session);;
map = RunQueryForMap(request, session, parameterObject, keyProperty, valueProperty, null );
return map;
}
/// <summary>
/// Executes the SQL and retuns all rows selected in a map that is keyed on the property named
/// in the keyProperty parameter. The value at each key will be the value of the property specified
/// in the valueProperty parameter. If valueProperty is null, the entire result object will be entered.
/// </summary>
/// <param name="request">The request scope.</param>
/// <param name="session">The session used to execute the statement</param>
/// <param name="parameterObject">The object used to set the parameters in the SQL.</param>
/// <param name="keyProperty">The property of the result object to be used as the key.</param>
/// <param name="valueProperty">The property of the result object to be used as the value (or null)</param>
/// <param name="rowDelegate"></param>
/// <returns>A hashtable of object containing the rows keyed by keyProperty.</returns>
///<exception cref="DataMapperException">If a transaction is not in progress, or the database throws an exception.</exception>
internal IDictionary RunQueryForMap( RequestScope request,
IDalSession session,
object parameterObject,
string keyProperty,
string valueProperty,
SqlMapper.DictionaryRowDelegate rowDelegate )
{
IDictionary map = new Hashtable();
using (IDbCommand command = _preparedCommand.Create(request, session, this.Statement, parameterObject))
{
using (IDataReader reader = command.ExecuteReader())
{
if (rowDelegate == null)
{
while (reader.Read() )
{
object obj = ApplyResultMap(request, reader, null);
object key = ObjectProbe.GetPropertyValue(obj, keyProperty);
object value = obj;
if (valueProperty != null)
{
value = ObjectProbe.GetPropertyValue(obj, valueProperty);
}
map.Add(key, value);
}
}
else
{
while (reader.Read())
{
object obj = ApplyResultMap(request, reader, null);
object key = ObjectProbe.GetPropertyValue(obj, keyProperty);
object value = obj;
if (valueProperty != null)
{
value = ObjectProbe.GetPropertyValue(obj, valueProperty);
}
rowDelegate(key, value, parameterObject, map);
}
}
}
}
return map;
}
#endregion
/// <summary>
/// Process 'select' result properties
/// </summary>
/// <param name="request"></param>
/// <param name="session"></param>
private void ExecutePostSelect(IDalSession session, RequestScope request)
{
while (request.QueueSelect.Count>0)
{
PostBindind postSelect = request.QueueSelect.Dequeue() as PostBindind;
if (postSelect.Method == ExecuteMethod.ExecuteQueryForIList)
{
object values = postSelect.Statement.ExecuteQueryForList(session, postSelect.Keys);
ObjectProbe.SetPropertyValue( postSelect.Target, postSelect.ResultProperty.PropertyName, values);
}
else if (postSelect.Method == ExecuteMethod.ExecuteQueryForStrongTypedIList)
{
object values = Activator.CreateInstance(postSelect.ResultProperty.PropertyInfo.PropertyType);
postSelect.Statement.ExecuteQueryForList(session, postSelect.Keys, (IList)values);
ObjectProbe.SetPropertyValue( postSelect.Target, postSelect.ResultProperty.PropertyName, values);
}
if (postSelect.Method == ExecuteMethod.ExecuteQueryForArrayList)
{
IList values = postSelect.Statement.ExecuteQueryForList(session, postSelect.Keys);
Type elementType = postSelect.ResultProperty.PropertyInfo.PropertyType.GetElementType();
Array array = Array.CreateInstance(elementType, values.Count);
for(int i=0;i<values.Count;i++)
{
array.SetValue(values[i],i);
}
postSelect.ResultProperty.PropertyInfo.SetValue(postSelect.Target, array, null);
}
else if (postSelect.Method == ExecuteMethod.ExecuteQueryForObject)
{
object value = postSelect.Statement.ExecuteQueryForObject(session, postSelect.Keys);
ObjectProbe.SetPropertyValue( postSelect.Target, postSelect.ResultProperty.PropertyName, value);
}
}
}
/// <summary>
///
/// </summary>
/// <param name="request"></param>
/// <param name="resultMap"></param>
/// <param name="mapping"></param>
/// <param name="target"></param>
/// <param name="reader"></param>
private void SetObjectProperty(RequestScope request, ResultMap resultMap,
ResultProperty mapping, ref object target, IDataReader reader)
{
string selectStatement = mapping.Select;
if (selectStatement.Length == 0 && mapping.NestedResultMap == null)
{
// If the property is not a 'select' ResultProperty
// or a 'resultMap' ResultProperty
// We have a 'normal' ResultMap
#region Not a select statement
if (mapping.TypeHandler == null || mapping.TypeHandler is UnknownTypeHandler) // Find the TypeHandler
{
lock(mapping)
{
if (mapping.TypeHandler == null || mapping.TypeHandler is UnknownTypeHandler)
{
int columnIndex = 0;
if (mapping.ColumnIndex == ResultProperty.UNKNOWN_COLUMN_INDEX)
{
columnIndex = reader.GetOrdinal(mapping.ColumnName);
}
else
{
columnIndex = mapping.ColumnIndex;
}
Type systemType =((IDataRecord)reader).GetFieldType(columnIndex);
mapping.TypeHandler = _sqlMap.TypeHandlerFactory.GetTypeHandler(systemType);
}
}
}
object dataBaseValue = mapping.GetDataBaseValue( reader );
request.IsRowDataFound = request.IsRowDataFound || (dataBaseValue != null);
if (resultMap != null)
{
resultMap.SetValueOfProperty( ref target, mapping, dataBaseValue );
}
else
{
MappedStatement.SetValueOfProperty( ref target, mapping, dataBaseValue );
}
#endregion
}
else if (mapping.NestedResultMap != null) // 'resultMap' ResultProperty
{
object obj = null;
obj = mapping.NestedResultMap.CreateInstanceOfResult();
if (FillObjectWithReaderAndResultMap(request, reader, mapping.NestedResultMap, obj) == false)
{
obj = null;
}
MappedStatement.SetValueOfProperty( ref target, mapping, obj );
}
else //'select' ResultProperty
{
// Get the select statement
IMappedStatement queryStatement = _sqlMap.GetMappedStatement(selectStatement);
string paramString = mapping.ColumnName;
object keys = null;
bool wasNull = false;
#region Find Key(s)
if (paramString.IndexOf(',')>0 || paramString.IndexOf('=')>0) // composite parameters key
{
IDictionary keyMap = new Hashtable();
keys = keyMap;
// define which character is seperating fields
char[] splitter = {'=',','};
string[] paramTab = paramString.Split(splitter);
if (paramTab.Length % 2 != 0)
{
throw new DataMapperException("Invalid composite key string format in '"+mapping.PropertyName+". It must be: property1=column1,property2=column2,...");
}
IEnumerator enumerator = paramTab.GetEnumerator();
while (!wasNull && enumerator.MoveNext())
{
string hashKey = ((string)enumerator.Current).Trim();
enumerator.MoveNext();
object hashValue = reader.GetValue( reader.GetOrdinal(((string)enumerator.Current).Trim()) );
keyMap.Add(hashKey, hashValue );
wasNull = (hashValue == DBNull.Value);
}
}
else // single parameter key
{
keys = reader.GetValue(reader.GetOrdinal(paramString));
wasNull = reader.IsDBNull(reader.GetOrdinal(paramString));
}
#endregion
if (wasNull)
{
// set the value of an object property to null
ObjectProbe.SetPropertyValue(target, mapping.PropertyName, null);
}
else // Collection object or .Net object
{
PostBindind postSelect = new PostBindind();
postSelect.Statement = queryStatement;
postSelect.Keys = keys;
postSelect.Target = target;
postSelect.ResultProperty = mapping;
#region Collection object or .NET object
// Check if the object to Map implement 'IList' or is IList type
// If yes the ResultProperty is map to a IList object
if ( (mapping.PropertyInfo.PropertyType.GetInterface("IList") != null) ||
(mapping.PropertyInfo.PropertyType == typeof(IList)))
{
object values = null;
if (mapping.IsLazyLoad)
{
values = LazyLoadList.NewInstance(queryStatement, keys, target, mapping.PropertyName);
ObjectProbe.SetPropertyValue( target, mapping.PropertyName, values);
}
else
{
if (mapping.PropertyInfo.PropertyType == typeof(IList))
{
postSelect.Method = ExecuteMethod.ExecuteQueryForIList;
}
else
{
postSelect.Method = ExecuteMethod.ExecuteQueryForStrongTypedIList;
}
}
}
else if (mapping.PropertyInfo.PropertyType.IsArray)
{
postSelect.Method = ExecuteMethod.ExecuteQueryForArrayList;
}
else // The ResultProperty is map to a .Net object
{
postSelect.Method = ExecuteMethod.ExecuteQueryForObject;
}
#endregion
if (!mapping.IsLazyLoad)
{
request.QueueSelect.Enqueue(postSelect);
}
}
}
}
private static void SetValueOfProperty( ref object target, ResultProperty property, object dataBaseValue )
{
if (target is Hashtable)
{
((Hashtable) target).Add(property.PropertyName, dataBaseValue);
}
else
{
if (property.PropertyName == "value")
{
target = dataBaseValue;
}
else
{
if (dataBaseValue == null)
{
ObjectProbe.SetPropertyValue( target, property.PropertyName, null);
// if (property.PropertyInfo != null)
// {
// property.PropertyInfo.SetValue( target, null, null );
// }
// else
// {
// ObjectProbe.SetPropertyValue( target, property.PropertyName, null);
// }
}
else
{
ObjectProbe.SetPropertyValue(target, property.PropertyName, dataBaseValue);
// if (property.PropertyInfo != null)
// {
// property.PropertyInfo.SetValue( target, dataBaseValue, null );
// }
// else
// {
// ObjectProbe.SetPropertyValue( target, property.PropertyName, dataBaseValue);
// }
}
}
}
}
/// <summary>
/// Raise an event ExecuteEventArgs
/// (Used when a query is executed)
/// </summary>
private void RaiseExecuteEvent()
{
ExecuteEventArgs e = new ExecuteEventArgs();
e.StatementName = _statement.Id;
if (Execute != null)
{
Execute(this, e);
}
}
/// <summary>
/// ToString implementation.
/// </summary>
/// <returns>A string that describes the MappedStatement</returns>
public override string ToString()
{
StringBuilder buffer = new StringBuilder();
buffer.Append("\tMappedStatement: " + this.Name);
buffer.Append(Environment.NewLine);
if (_statement.ParameterMap != null) buffer.Append(_statement.ParameterMap.Id);
if (_statement.ResultMap != null) buffer.Append(_statement.ResultMap.Id);
return buffer.ToString();
}
private ReaderAutoMapper _readerAutoMapper = null;
private void AutoMapReader( IDataReader reader,ref object resultObject)
{
if (_statement.RemapResults)
{
ReaderAutoMapper readerAutoMapper = new ReaderAutoMapper(_sqlMap.TypeHandlerFactory, reader, ref resultObject);
readerAutoMapper.AutoMapReader( reader, ref resultObject );
_logger.Debug("The RemapResults");
}
else
{
if (_readerAutoMapper == null)
{
lock (this)
{
if (_readerAutoMapper == null)
{
_readerAutoMapper = new ReaderAutoMapper(_sqlMap.TypeHandlerFactory, reader, ref resultObject);
}
}
}
_logger.Debug("The AutoMapReader");
_readerAutoMapper.AutoMapReader( reader, ref resultObject );
}
}
#endregion
private class ReaderAutoMapper
{
private ResultMap _resultMap = new ResultMap();
/// <summary>
///
/// </summary>
/// <param name="reader"></param>
/// <param name="resultObject"></param>
/// <param name="typeHandlerFactory"></param>
public ReaderAutoMapper(TypeHandlerFactory typeHandlerFactory, IDataReader reader,ref object resultObject)
{
try
{
// Get all PropertyInfo from the resultObject properties
ReflectionInfo reflectionInfo = ReflectionInfo.GetInstance(resultObject.GetType());
string[] propertiesName = reflectionInfo.GetWriteablePropertyNames();
Hashtable propertyMap = new Hashtable();
for (int i = 0; i < propertiesName.Length; i++)
{
propertyMap.Add( propertiesName[i].ToUpper(), reflectionInfo.GetSetter(propertiesName[i]) );
}
// Get all column Name from the reader
// and build a resultMap from with the help of the PropertyInfo[].
DataTable dataColumn = reader.GetSchemaTable();
for (int i = 0; i < dataColumn.Rows.Count; i++)
{
string columnName = dataColumn.Rows[i][0].ToString();
PropertyInfo matchedPropertyInfo = propertyMap[columnName.ToUpper()] as PropertyInfo;
ResultProperty property = new ResultProperty();
property.ColumnName = columnName;
property.ColumnIndex = i;
if (resultObject is Hashtable)
{
property.PropertyName = columnName;
_resultMap.AddResultPropery(property);
}
Type propertyType = null;
if (matchedPropertyInfo == null )
{
try
{
propertyType = ObjectProbe.GetPropertyTypeForSetter(resultObject, columnName);
}
catch
{
_logger.Error("The column [" + columnName + "] could not be auto mapped to a property on [" + resultObject.ToString() + "]");
}
}
else
{
propertyType = reflectionInfo.GetSetterType(matchedPropertyInfo.Name);
}
if(propertyType != null || matchedPropertyInfo != null)
{
property.PropertyName = (matchedPropertyInfo != null ? matchedPropertyInfo.Name : columnName );
if (matchedPropertyInfo != null)
{
property.Initialize(typeHandlerFactory, matchedPropertyInfo );
}
else
{
property.TypeHandler = typeHandlerFactory.GetTypeHandler(propertyType);
}
_resultMap.AddResultPropery(property);
}
// // Fix for IBATISNET-73 (JIRA-73) from Ron Grabowski
// if (property.PropertyName != null && property.PropertyName.Length > 0)
// {
// // Set TypeHandler
// Type propertyType = reflectionInfo.GetSetterType(property.PropertyName);
// property.TypeHandler = typeHandlerFactory.GetTypeHandler( propertyType );
// }
// else
// {
// if (_logger.IsDebugEnabled)
// {
// _logger.Debug("The column [" + columnName + "] could not be auto mapped to a property on [" + resultObject.ToString() + "]");
// }
// }
}
}
catch (Exception e)
{
throw new DataMapperException("Error automapping columns. Cause: " + e.Message, e);
}
}
/// <summary>
///
/// </summary>
/// <param name="reader"></param>
/// <param name="resultObject"></param>
public void AutoMapReader(IDataReader reader, ref object resultObject)
{
foreach (string key in _resultMap.ColumnsToPropertiesMap.Keys)
{
ResultProperty property = (ResultProperty) _resultMap.ColumnsToPropertiesMap[key];
MappedStatement.SetValueOfProperty( ref resultObject, property,
property.GetDataBaseValue( reader ));
}
}
}
}
}
| |
//
// TemplateEngine.cs
//
// Author: najmeddine nouri
//
// Copyright (c) 2013 najmeddine nouri, amine gassem
//
// 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.
//
// Except as contained in this notice, the name(s) of the above copyright holders
// shall not be used in advertising or otherwise to promote the sale, use or other
// dealings in this Software without prior written authorization.
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using Badr.Net;
using Badr.Server.Net;
using Badr.Server.Settings;
using Badr.Server.Templates.Rendering;
using Badr.Server.Templates.Parsing;
namespace Badr.Server.Templates
{
public class TemplateEngine
{
private Scope _scope0;
private string _semiParsed;
private bool _isStaticTemplate;
protected internal string TemplateContent { get; protected set; }
protected internal List<ExprRenderer> ExprRenderers { get; protected set; }
public List<TemplateError> Errors { get; protected set; }
public bool ContainsErrors { get { return Errors != null && Errors.Count > 0; } }
public TemplateEngine(string templateContent)
{
Errors = new List<TemplateError>();
TemplateContent = templateContent;
Compile();
}
protected void Compile()
{
if (ParseExpressions())
if (!_isStaticTemplate && CreateScopes())
SemiParsed();
}
public string Render(BadrRequest request, TemplateContext context)
{
if (ContainsErrors)
throw new TemplateException(string.Join(Environment.NewLine, Errors.Select(te => te.Message)), this);
if (_isStaticTemplate)
return TemplateContent;
else
return new RenderContext(request).Render(_scope0, context);
}
public string Render(TemplateContext context)
{
return Render (null, context);
}
private bool ParseExpressions()
{
Parser parser = new Parser(BadrGrammar.RE_EXPR_INSTRUCTION,
BadrGrammar.RE_EXPR_VARIABLE,
BadrGrammar.RE_EXPR_SPECIAL_TAG);
var list = new List<Parser.ExprMatchResult>();
list.AddRange(parser.Match(TemplateContent, ExprType.INSTRUCTION, BadrGrammar.GROUP_INSTRUCTION));
list.AddRange(parser.Match(TemplateContent, ExprType.VAR, BadrGrammar.GROUP_VARIABLE));
list.AddRange(parser.Match(TemplateContent, ExprType.SPECIAL_TAG, BadrGrammar.GROUP_SPECIAL_TAG));
if(list.Count == 0){
_isStaticTemplate = true;
return true;
}
ExprRenderers = new List<ExprRenderer>();
foreach (Parser.ExprMatchResult emr in list)
{
ExprRenderer er = RenderManager.GetExprRenderer(emr);
if (er != null)
ExprRenderers.Add(er);
else
{
Errors.Add(new TemplateError(emr.Line, string.Format(" near '{0}', line {1}", emr.Match, emr.Line)));
}
}
if (ContainsErrors)
{
Errors.Insert(0, new TemplateError(-1, "Syntax error:"));
return false;
}
ExprRenderers.Sort(new Comparison<ExprRenderer>((er1, er2) =>
{
return er1.ExprMatchResult.StartIndex.CompareTo(er2.ExprMatchResult.StartIndex);
}));
return true;
}
private bool CreateScopes()
{
int level = 0;
List<int> passedBlockExprs = new List<int>();
_scope0 = new Scope(TemplateContent) { Level = level };
Scope currScope = _scope0;
for (int i = 0; i < ExprRenderers.Count; i++)
{
ExprRenderer currRenderer = ExprRenderers[i];
if (currRenderer.RenderType == ExprRenderType.Simple)
{
currRenderer.Level = level;
Scope scope = new Scope(TemplateContent)
{
ExprRenderer = currRenderer,
Level = level,
Start = currRenderer.ExprMatchResult,
End = currRenderer.ExprMatchResult
};
currScope.Add(scope);
}
else
{
if (currRenderer.RenderType == ExprRenderType.BlockStart)
level += 1;
currRenderer.Level = level;
if (currRenderer.RenderType == ExprRenderType.BlockStart)
{
Scope scope = new Scope(TemplateContent)
{
Level = level,
ExprRenderer = currRenderer,
Start = currRenderer.ExprMatchResult
};
currScope.Add(scope);
currScope = scope;
}
else
{
currScope.End = currRenderer.ExprMatchResult;
currScope = currScope.ParentScope;
if (currRenderer.RenderType == ExprRenderType.BlockMiddle)
{
Scope scope = new Scope(TemplateContent)
{
Level = level,
ExprRenderer = currRenderer,
Start = currRenderer.ExprMatchResult
};
currScope.Add(scope);
if (currRenderer.JointRendererName != null)
{
for (int j = i - 1; j >= 0; j--)
{
ExprRenderer render_j = ExprRenderers[j];
if (render_j.Level == render_j.Level
&& render_j.Name == currRenderer.JointRendererName)
{
currRenderer.JointRenderer = render_j;
break;
}
}
}
currScope = scope;
continue;
}
}
if (currRenderer.RenderType == ExprRenderType.BlockEnd || currRenderer.RenderType == ExprRenderType.BlockMiddle)
{
int blockStarExprIndex = GetBlockStartExprIndex(currRenderer, i);
if (ContainsErrors)
return false;
passedBlockExprs.Add(blockStarExprIndex);
}
if (currRenderer.RenderType == ExprRenderType.BlockEnd)
level -= 1;
}
}
for (int i = 0; i < ExprRenderers.Count; i++)
{
if (!passedBlockExprs.Contains(i))
{
ExprRenderer er_i = ExprRenderers[i];
if (er_i.RenderType == ExprRenderType.BlockStart)
{
if (er_i.BlockDef == null)
throw new TemplateException(string.Format("[FATAL] Missing block definition, line {0}", er_i.ExprMatchResult.Line), this);
Errors.Add(new TemplateError(er_i.ExprMatchResult.Line, string.Format("Missing '{0}' block end instruction, line {1}",
er_i.BlockDef.Name,
er_i.ExprMatchResult.Line)));
}
}
}
_scope0.ExtractStaticTextRecursive();
return ContainsErrors;
}
private int GetBlockStartExprIndex(ExprRenderer exprRenderer, int exprRendererIndex)
{
ExprBlockDef exprBlock = exprRenderer.BlockDef;
if (exprBlock != null)
{
int startExprIndex = -1;
for (int i = exprRendererIndex - 1; i >= 0; i--)
{
ExprRenderer er_i = ExprRenderers[i];
if (er_i.Level == exprRenderer.Level)
{
if (exprBlock.IsStartingExpr(er_i.Name))
{
startExprIndex = i;
break;
}
else if (exprBlock.IsEndingExpr(er_i.Name))
// if same ending instruction encountered befor the startting instruction (same level)
break;
}
}
if (startExprIndex != -1)
return startExprIndex;
else
{
Errors.Add(new TemplateError(exprRenderer.ExprMatchResult.Line, string.Format("Missing '{0}' block start instruction, line {1}", exprBlock.Name, exprRenderer.ExprMatchResult.Line)));
}
}
else
{
Errors.Add(new TemplateError(exprRenderer.ExprMatchResult.Line, string.Format("[FATAL] Missing block definition, line {0}", exprRenderer.ExprMatchResult.Line)));
}
return -1;
}
protected void SemiParsed()
{
_semiParsed = "";
int sIndex1, sIndex2;
int eIndex1, eIndex2;
sIndex1 = 0; eIndex1 = -1;
for (int i = 0; i < ExprRenderers.Count; i++)
{
ExprRenderer currExprRenderer = ExprRenderers[i];
sIndex2 = currExprRenderer.ExprMatchResult.StartIndex;
eIndex2 = currExprRenderer.ExprMatchResult.EndIndex;
if (sIndex2 > sIndex1)
{
if (eIndex1 < sIndex2 - 1)
_semiParsed += TemplateContent.Substring(eIndex1 + 1, sIndex2 - eIndex1 - 1);
_semiParsed += string.Format("[{0}:{1}]", currExprRenderer.Name, currExprRenderer.Level);
}
sIndex1 = sIndex2; eIndex1 = eIndex2;
}
if (ExprRenderers.Count > 0)
{
if (ExprRenderers[ExprRenderers.Count - 1].ExprMatchResult.EndIndex < TemplateContent.Length - 1)
_semiParsed += TemplateContent.Substring(ExprRenderers[ExprRenderers.Count - 1].ExprMatchResult.EndIndex + 1);
}
else
_semiParsed += TemplateContent;
}
}
public class TemplateError
{
public TemplateError(int line, string message)
{
Line = line;
Message = message;
}
public readonly int Line;
public readonly string Message;
}
}
| |
// $Id: GroupRequest.java,v 1.8 2004/09/05 04:54:22 ovidiuf Exp $
using System;
using System.Collections;
using Alachisoft.NGroups;
using Alachisoft.NGroups.Stack;
using Alachisoft.NCache.Common.Net;
using Alachisoft.NCache.Common.Monitoring;
using System.Text;
using System.Configuration;
using System.Collections.Generic;
using Alachisoft.NCache.Common.Util;
using Alachisoft.NCache.Common.Logger;
using Alachisoft.NGroups.Util;
namespace Alachisoft.NGroups.Blocks
{
/// <summary> Sends a message to all members of the group and waits for all responses (or timeout). Returns a
/// boolean value (success or failure). Results (if any) can be retrieved when _done.<p>
/// The supported transport to send requests is currently either a RequestCorrelator or a generic
/// Transport. One of them has to be given in the constructor. It will then be used to send a
/// request. When a message is received by either one, the receiveResponse() of this class has to
/// be called (this class does not actively receive requests/responses itself). Also, when a view change
/// or suspicion is received, the methods viewChange() or suspect() of this class have to be called.<p>
/// When started, an array of responses, correlating to the membership, is created. Each response
/// is added to the corresponding field in the array. When all fields have been set, the algorithm
/// terminates.
/// This algorithm can optionally use a suspicion service (failure detector) to detect (and
/// exclude from the membership) fauly members. If no suspicion service is available, timeouts
/// can be used instead (see <code>execute()</code>). When _done, a list of suspected members
/// can be retrieved.<p>
/// Because a channel might deliver requests, and responses to <em>different</em> requests, the
/// <code>GroupRequest</code> class cannot itself receive and process requests/responses from the
/// channel. A mechanism outside this class has to do this; it has to determine what the responses
/// are for the message sent by the <code>execute()</code> method and call <code>receiveResponse()</code>
/// to do so.<p>
/// <b>Requirements</b>: lossless delivery, e.g. acknowledgment-based message confirmation.
/// </summary>
/// <author> Bela Ban
/// </author>
/// <version> $Revision: 1.8 $
/// </version>
public class GroupRequest : RspCollector, Command
{
/// <summary>Returns the results as a RspList </summary>
virtual public RspList Results
{
get
{
RspList retval = new RspList();
Address sender;
lock (rsp_mutex)
{
for (int i = 0; i < membership.Length; i++)
{
sender = membership[i];
switch (received[i])
{
case SUSPECTED:
retval.addSuspect(sender);
break;
case RECEIVED:
retval.addRsp(sender, responses[i]);
break;
case NOT_RECEIVED:
retval.addNotReceived(sender);
break;
}
}
return retval;
}
}
}
virtual public int NumSuspects
{
get { return suspects.Count; }
}
virtual public ArrayList Suspects
{
get { return suspects; }
}
virtual public bool Done
{
get { return _done; }
}
/// <summary>Generates a new unique request ID </summary>
private static long RequestId
{
get
{
lock (req_mutex)
{
//Request id ranges from 0 to long.Max. If it reaches the max we
//re-initialize it to -1;
if (last_req_id == long.MaxValue) last_req_id = -1;
long result = ++last_req_id;
return result;
}
}
}
public void AddNHop(Address sender)
{
lock (_nhopMutex)
{
expectedNHopResponses++;
if (!nHops.Contains(sender))
nHops.Add(sender);
}
}
public void AddNHopDefaultStatus(Address sender)
{
if (!receivedFromNHops.ContainsKey(sender))
receivedFromNHops.Add(sender, NOT_RECEIVED);
}
virtual protected internal bool Responses
{
get
{
int num_not_received = getNum(NOT_RECEIVED);
int num_received = getNum(RECEIVED);
int num_suspected = getNum(SUSPECTED);
int num_total = membership.Length;
int num_receivedFromNHops = getNumFromNHops(RECEIVED);
int num_suspectedNHops = getNumFromNHops(SUSPECTED);
int num_okResponsesFromNHops = num_receivedFromNHops + num_suspectedNHops;
switch (rsp_mode)
{
case GET_FIRST:
if (num_received > 0)
return true;
if (num_suspected >= num_total)
// e.g. 2 members, and both suspected
return true;
break;
case GET_FIRST_NHOP:
if (num_received > 0 && num_okResponsesFromNHops == expectedNHopResponses)
return true;
if (num_suspected >= num_total)
return true;
break;
case GET_ALL:
if (num_not_received > 0)
return false;
return true;
case GET_ALL_NHOP:
if (num_not_received > 0)
return false;
if (num_okResponsesFromNHops < expectedNHopResponses)
return false;
return true;
case GET_N:
if (expected_mbrs >= num_total)
{
rsp_mode = GET_ALL;
return Responses;
}
if (num_received >= expected_mbrs)
{
return true;
}
if (num_received + num_not_received < expected_mbrs)
{
if (num_received + num_suspected >= expected_mbrs)
{
return true;
}
return false;
}
return false;
case GET_NONE:
return true;
default:
NCacheLog.Error("rsp_mode " + rsp_mode + " unknown !");
break;
}
return false;
}
}
/// <summary>return only first response </summary>
public const byte GET_FIRST = 1;
/// <summary>return all responses </summary>
public const byte GET_ALL = 2;
/// <summary>return n responses (may block) </summary>
public const byte GET_N = 3;
/// <summary>return no response (async call) </summary>
public const byte GET_NONE = 4;
/// <summary>
/// This type is used when two nodes dont communicate directly. Consider three nodes 1,2 and 3.
/// 1 sends request to 2; 2 forwards request to 3; 3 executes the request and send the response
/// directly to 1 instead of 2.
/// </summary>
public const byte GET_FIRST_NHOP = 5;
public const byte GET_ALL_NHOP = 6;
private const byte NOT_RECEIVED = 0;
private const byte RECEIVED = 1;
private const byte SUSPECTED = 2;
private Address[] membership = null; // current membership
private object[] responses = null; // responses corresponding to membership
private byte[] received = null; // status of response for each mbr (see above)
private long[] timeStats = null; // responses corresponding to membership
/// <summary>
/// replica nodes in the cluster from where we are expecting responses. Following is the detail of how
/// it works.
/// 1. In case of synchronous POR, when an operation is transferred to main node through clustering
/// layer, main node does the following: -
/// a) it executes the operation on itself.
/// b) it transfers the operation to its replica (the next hop).
/// c) it sends the response of this operation back and as part of this
/// response, it informs the node that another response is expected from replica node (the next hop).
/// 2. this dictionary is filled with the replica addresses (next hop addresses) received as part of the response
/// from main node along with the status (RECEIVED/NOT_RECEIVED...).
/// </summary>
private Dictionary<Address, byte> receivedFromNHops = new Dictionary<Address, byte>();
/// <summary>
/// list of next hop members.
/// </summary>
private List<Address> nHops = new List<Address>();
/// <summary>
/// number of responses expected from next hops. When one node send requests to other node (NHop Request),
/// the node may or may not send the same request to next hop depending on the success/failure of the request
/// on this node. this counter tells how many requests were sent to next hops and their responses are now
/// expected.
/// </summary>
private int expectedNHopResponses = 0;
private object _nhopMutex = new object();
/// <summary>bounded queue of suspected members </summary>
private ArrayList suspects = ArrayList.Synchronized(new ArrayList(10));
/// <summary>list of members, changed by viewChange() </summary>
private ArrayList members = ArrayList.Synchronized(new ArrayList(10));
/// <summary>
/// the list of all the current members in the cluster.
/// this list is different from the members list of the Group Request which
/// only contains the addresses of members to which this group request must
/// send the message.
/// list of total membership is used to determine which member has been
/// suspected after the new list of members is received through view change
/// event.
/// </summary>
private ArrayList clusterMembership = ArrayList.Synchronized(new ArrayList(10));
/// <summary>keep suspects vector bounded </summary>
private int max_suspects = 40;
protected internal Message request_msg = null;
protected internal RequestCorrelator corr = null; // either use RequestCorrelator or ...
protected internal Transport transport = null; // Transport (one of them has to be non-null)
protected internal byte rsp_mode = GET_ALL;
private bool _done = false;
protected internal object rsp_mutex = new object();
protected internal long timeout = 0;
protected internal int expected_mbrs = 0;
/// <summary>to generate unique request IDs (see getRequestId()) </summary>
private static long last_req_id = -1;
protected internal long req_id = -1; // request ID for this request
private static object req_mutex = new object();
private ILogger _ncacheLog;
private ILogger NCacheLog
{
get { return _ncacheLog; }
}
private bool _seqReset;
private int _retriesAfteSeqReset;
static GroupRequest()
{
}
/// <param name="m">The message to be sent
/// </param>
/// <param name="corr">The request correlator to be used. A request correlator sends requests tagged with
/// a unique ID and notifies the sender when matching responses are received. The
/// reason <code>GroupRequest</code> uses it instead of a <code>Transport</code> is
/// that multiple requests/responses might be sent/received concurrently.
/// </param>
/// <param name="members">The initial membership. This value reflects the membership to which the request
/// is sent (and from which potential responses are expected). Is reset by reset().
/// </param>
/// <param name="rsp_mode">How many responses are expected. Can be
/// <ol>
/// <li><code>GET_ALL</code>: wait for all responses from non-suspected members.
/// A suspicion service might warn
/// us when a member from which a response is outstanding has crashed, so it can
/// be excluded from the responses. If no suspision service is available, a
/// timeout can be used (a value of 0 means wait forever). <em>If a timeout of
/// 0 is used, no suspicion service is available and a member from which we
/// expect a response has crashed, this methods blocks forever !</em>.
/// <li><code>GET_FIRST</code>: wait for the first available response.
/// <li><code>GET_MAJORITY</code>: wait for the majority of all responses. The
/// majority is re-computed when a member is suspected.
/// <li><code>GET_ABS_MAJORITY</code>: wait for the majority of
/// <em>all</em> members.
/// This includes failed members, so it may block if no timeout is specified.
/// <li><code>GET_N</CODE>: wait for N members.
/// Return if n is >= membership+suspects.
/// <li><code>GET_NONE</code>: don't wait for any response. Essentially send an
/// asynchronous message to the group members.
/// </ol>
/// </param>
public GroupRequest(Message m, RequestCorrelator corr, ArrayList members, ArrayList clusterCompleteMembership, byte rsp_mode, ILogger NCacheLog)
{
request_msg = m;
this.corr = corr;
this.rsp_mode = rsp_mode;
this._ncacheLog = NCacheLog;
this.clusterMembership = clusterCompleteMembership;
reset(members);
}
/// <param name="timeout">Time to wait for responses (ms). A value of <= 0 means wait indefinitely
/// (e.g. if a suspicion service is available; timeouts are not needed).
/// </param>
public GroupRequest(Message m, RequestCorrelator corr, ArrayList members, ArrayList clusterCompleteMembership, byte rsp_mode, long timeout, int expected_mbrs, ILogger NCacheLog)
: this(m, corr, members, clusterCompleteMembership, rsp_mode, NCacheLog)
{
if (timeout > 0)
this.timeout = timeout;
this.expected_mbrs = expected_mbrs;
}
public GroupRequest(Message m, Transport transport, ArrayList members, ArrayList clusterCompleteMembership, byte rsp_mode, ILogger NCacheLog)
{
request_msg = m;
this.transport = transport;
this.rsp_mode = rsp_mode;
this._ncacheLog = NCacheLog;
this.clusterMembership = clusterCompleteMembership;
reset(members);
}
/// <param name="timeout">Time to wait for responses (ms). A value of <= 0 means wait indefinitely
/// (e.g. if a suspicion service is available; timeouts are not needed).
/// </param>
public GroupRequest(Message m, Transport transport, ArrayList members, ArrayList clusterCompleteMembership, byte rsp_mode, long timeout, int expected_mbrs, ILogger NCacheLog)
: this(m, transport, members, clusterCompleteMembership, rsp_mode, NCacheLog)
{
if (timeout > 0)
this.timeout = timeout;
this.expected_mbrs = expected_mbrs;
}
/// <summary> Sends the message. Returns when n responses have been received, or a
/// timeout has occurred. <em>n</em> can be the first response, all
/// responses, or a majority of the responses.
/// </summary>
public virtual bool execute()
{
if(ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("GrpReq.Exec", "mode :" + rsp_mode);
bool retval;
if (corr == null && transport == null)
{
NCacheLog.Error("GroupRequest.execute()", "both corr and transport are null, cannot send group request");
return false;
}
lock (rsp_mutex)
{
_done = false;
retval = doExecute(timeout);
if (retval == false)
{
if(NCacheLog.IsInfoEnabled) NCacheLog.Info("GroupRequest.execute()", "call did not execute correctly, request is " + ToString());
}
if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("GrpReq.Exec", "exited; result:" + retval);
_done = true;
return retval;
}
}
/// <summary> Resets the group request, so it can be reused for another execution.</summary>
public virtual void reset(Message m, byte mode, long timeout)
{
lock (rsp_mutex)
{
_done = false;
request_msg = m;
rsp_mode = mode;
this.timeout = timeout;
System.Threading.Monitor.PulseAll(rsp_mutex);
}
}
public virtual void reset(Message m, ArrayList members, byte rsp_mode, long timeout, int expected_rsps)
{
lock (rsp_mutex)
{
reset(m, rsp_mode, timeout);
reset(members);
this.expected_mbrs = expected_rsps;
System.Threading.Monitor.PulseAll(rsp_mutex);
}
}
/// <summary> This method sets the <code>membership</code> variable to the value of
/// <code>members</code>. It requires that the caller already hold the
/// <code>rsp_mutex</code> lock.
/// </summary>
/// <param name="mbrs">The new list of members
/// </param>
public virtual void reset(ArrayList mbrs)
{
if (mbrs != null)
{
int size = mbrs.Count;
membership = new Address[size];
responses = new object[size];
received = new byte[size];
timeStats = new long[size];
for (int i = 0; i < size; i++)
{
membership[i] = (Address)mbrs[i];
responses[i] = null;
received[i] = NOT_RECEIVED;
timeStats[i] = 0;
}
// maintain local membership
this.members.Clear();
this.members.AddRange(mbrs);
}
else
{
if (membership != null)
{
for (int i = 0; i < membership.Length; i++)
{
responses[i] = null;
received[i] = NOT_RECEIVED;
}
}
}
}
public void SequenceReset()
{
lock (rsp_mutex)
{
_seqReset = true;
_retriesAfteSeqReset = 0;
System.Threading.Monitor.PulseAll(rsp_mutex);
}
}
/* ---------------------- Interface RspCollector -------------------------- */
/// <summary> <b>Callback</b> (called by RequestCorrelator or Transport).
/// Adds a response to the response table. When all responses have been received,
/// <code>execute()</code> returns.
/// </summary>
public virtual void receiveResponse(Message m)
{
Address sender = m.Src, mbr;
object val = null;
if (_done)
{
NCacheLog.Warn("GroupRequest.receiveResponse()", "command is done; cannot add response !");
return;
}
if (suspects != null && suspects.Count > 0 && suspects.Contains(sender))
{
NCacheLog.Warn("GroupRequest.receiveResponse()", "received response from suspected member " + sender + "; discarding");
return;
}
if (m.Length > 0 || m.BufferLength >0)
{
try
{
if (m.responseExpected)
{
OperationResponse opRes = new OperationResponse();
if (m.Buffers != null)
opRes.SerializablePayload = m.Buffers;
else
opRes.SerializablePayload = m.getFlatObject();
opRes.UserPayload = m.Payload;
val = opRes;
}
else
{
if (m.Buffers != null)
val = m.Buffers;
else
val = m.getFlatObject();
}
}
catch (System.Exception e)
{
NCacheLog.Error("GroupRequest.receiveResponse()", "exception=" + e.Message);
}
}
lock (rsp_mutex)
{
bool isMainMember = false;
for (int i = 0; i < membership.Length; i++)
{
mbr = membership[i];
if (mbr.Equals(sender))
{
isMainMember = true;
if (received[i] == NOT_RECEIVED)
{
responses[i] = val;
received[i] = RECEIVED;
if (NCacheLog.IsInfoEnabled) NCacheLog.Info("GroupRequest.receiveResponse()", "received response for request " + req_id + ", sender=" + sender + ", val=" + val);
System.Threading.Monitor.PulseAll(rsp_mutex); // wakes up execute()
break;
}
}
}
if (!isMainMember)
{
receivedFromNHops[sender] = RECEIVED;
//nTrace.criticalInfo("GroupRequest.receiveResponse", sender.ToString() + " has sent nhop response");
System.Threading.Monitor.PulseAll(rsp_mutex);
}
}
}
/// <summary> <b>Callback</b> (called by RequestCorrelator or Transport).
/// Report to <code>GroupRequest</code> that a member is reported as faulty (suspected).
/// This method would probably be called when getting a suspect message from a failure detector
/// (where available). It is used to exclude faulty members from the response list.
/// </summary>
public virtual void suspect(Address suspected_member)
{
Address mbr;
bool isMainMember = false;
lock (rsp_mutex)
{
// modify 'suspects' and 'responses' array
for (int i = 0; i < membership.Length; i++)
{
mbr = membership[i];
if (mbr.Equals(suspected_member))
{
isMainMember = true;
addSuspect(suspected_member);
responses[i] = null;
received[i] = SUSPECTED;
System.Threading.Monitor.PulseAll(rsp_mutex);
break;
}
}
if (!isMainMember)
{
if (clusterMembership != null && clusterMembership.Contains(suspected_member))
receivedFromNHops[suspected_member] = SUSPECTED;
System.Threading.Monitor.PulseAll(rsp_mutex);
}
}
}
/// <summary> Any member of 'membership' that is not in the new view is flagged as
/// SUSPECTED. Any member in the new view that is <em>not</em> in the
/// membership (ie, the set of responses expected for the current RPC) will
/// <em>not</em> be added to it. If we did this we might run into the
/// following problem:
/// <ul>
/// <li>Membership is {A,B}
/// <li>A sends a synchronous group RPC (which sleeps for 60 secs in the
/// invocation handler)
/// <li>C joins while A waits for responses from A and B
/// <li>If this would generate a new view {A,B,C} and if this expanded the
/// response set to {A,B,C}, A would wait forever on C's response because C
/// never received the request in the first place, therefore won't send a
/// response.
/// </ul>
/// </summary>
public virtual void viewChange(View new_view)
{
Address mbr;
ArrayList mbrs = new_view != null ? new_view.Members : null;
if (membership == null || membership.Length == 0 || mbrs == null)
return;
lock (rsp_mutex)
{
ArrayList oldMembership = clusterMembership != null ? clusterMembership.Clone() as ArrayList : null;
clusterMembership.Clear();
clusterMembership.AddRange(mbrs);
this.members.Clear();
this.members.AddRange(mbrs);
for (int i = 0; i < membership.Length; i++)
{
mbr = membership[i];
if (!mbrs.Contains(mbr))
{
addSuspect(mbr);
responses[i] = null;
received[i] = SUSPECTED;
}
if (oldMembership != null)
oldMembership.Remove(mbr);
}
//by this time, membershipClone cotains all those members that are not part of
//group request normal membership and are no longer part of the cluster membership
//according to the new view.
//this way we are suspecting replica members.
if (oldMembership != null)
{
foreach (Address member in oldMembership)
{
if (!mbrs.Contains(member))
receivedFromNHops[member] = SUSPECTED;
}
}
System.Threading.Monitor.PulseAll(rsp_mutex);
}
}
/* -------------------- End of Interface RspCollector ----------------------------------- */
public override string ToString()
{
System.Text.StringBuilder ret = new System.Text.StringBuilder();
ret.Append("[GroupRequest:\n");
ret.Append("req_id=").Append(req_id).Append('\n');
ret.Append("members: ");
for (int i = 0; i < membership.Length; i++)
{
ret.Append(membership[i] + " ");
}
ret.Append("\nresponses: ");
for (int i = 0; i < responses.Length; i++)
{
ret.Append(responses[i] + " ");
}
if (suspects.Count > 0)
ret.Append("\nsuspects: " + Global.CollectionToString(suspects));
ret.Append("\nrequest_msg: " + request_msg);
ret.Append("\nrsp_mode: " + rsp_mode);
ret.Append("\ndone: " + _done);
ret.Append("\ntimeout: " + timeout);
ret.Append("\nexpected_mbrs: " + expected_mbrs);
ret.Append("\n]");
return ret.ToString();
}
/* --------------------------------- Private Methods -------------------------------------*/
/// <summary>This method runs with rsp_mutex locked (called by <code>execute()</code>). </summary>
protected internal virtual bool doExecute_old(long timeout)
{
long start_time = 0;
Address mbr, suspect;
if (rsp_mode != GET_NONE)
{
req_id = corr.NextRequestId;
}
reset(null); // clear 'responses' array
if (suspects != null)
{
// mark all suspects in 'received' array
for (int i = 0; i < suspects.Count; i++)
{
suspect = (Address)suspects[i];
for (int j = 0; j < membership.Length; j++)
{
mbr = membership[j];
if (mbr.Equals(suspect))
{
received[j] = SUSPECTED;
break; // we can break here because we ensure there are no duplicate members
}
}
}
}
try
{
if (NCacheLog.IsInfoEnabled) NCacheLog.Info("GroupRequest.doExecute()", "sending request (id=" + req_id + ')');
if (corr != null)
{
ArrayList tmp = members != null ? members : null;
corr.sendRequest(req_id, tmp, request_msg, rsp_mode == GET_NONE ? null : this);
}
else
{
transport.send(request_msg);
}
}
catch (System.Exception e)
{
NCacheLog.Error("GroupRequest.doExecute()", "exception=" + e.Message);
if (corr != null)
{
corr.done(req_id);
}
return false;
}
long orig_timeout = timeout;
if (timeout <= 0)
{
while (true)
{
/* Wait for responses: */
adjustMembership(); // may not be necessary, just to make sure...
if (Responses)
{
if (corr != null)
{
corr.done(req_id);
}
if (NCacheLog.IsInfoEnabled) NCacheLog.Info("GroupRequest.doExecute()", "received all responses: " + ToString());
return true;
}
try
{
System.Threading.Monitor.Wait(rsp_mutex);
}
catch (System.Exception e)
{
NCacheLog.Error("GroupRequest.doExecute():2", "exception=" + e.Message);
}
}
}
else
{
start_time = (System.DateTime.Now.Ticks - 621355968000000000) / 10000;
while (timeout > 0)
{
/* Wait for responses: */
if (Responses)
{
if (corr != null)
corr.done(req_id);
if (NCacheLog.IsInfoEnabled) NCacheLog.Info("GroupRequest.doExecute()", "received all responses: " + ToString());
return true;
}
timeout = orig_timeout - ((System.DateTime.Now.Ticks - 621355968000000000) / 10000 - start_time);
if (timeout > 0)
{
try
{
System.Threading.Monitor.Wait(rsp_mutex, TimeSpan.FromMilliseconds(timeout));
}
catch (System.Exception e)
{
NCacheLog.Error("GroupRequest.doExecute():3", "exception=" + e);
//e.printStacknTrace();
}
}
}
if (timeout <= 0)
{
RspList rspList = Results;
string failedNodes = "";
if (rspList != null)
{
for (int i = 0; i < rspList.size(); i++)
{
Rsp rsp = rspList.elementAt(i) as Rsp;
if (rsp != null && !rsp.wasReceived())
failedNodes += rsp.Sender;
}
}
if (NCacheLog.IsInfoEnabled) NCacheLog.Info("GroupRequest.doExecute:", "[ " + req_id + " ] did not receive rsp from " + failedNodes + " [Timeout] " + timeout + " [timeout-val =" + orig_timeout + "]");
}
if (corr != null)
{
corr.done(req_id);
}
return false;
}
}
protected internal virtual bool doExecute(long timeout)
{
long start_time = 0;
Address mbr, suspect;
if (rsp_mode != GET_NONE)
{
req_id = corr.NextRequestId;
}
reset(null); // clear 'responses' array
if (suspects != null)
{
// mark all suspects in 'received' array
for (int i = 0; i < suspects.Count; i++)
{
suspect = (Address)suspects[i];
for (int j = 0; j < membership.Length; j++)
{
mbr = membership[j];
if (mbr.Equals(suspect))
{
received[j] = SUSPECTED;
break; // we can break here because we ensure there are no duplicate members
}
}
}
}
try
{
if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("GrpReq.doExec", "sending req_id :" + req_id + "; timeout: " + timeout);
if (NCacheLog.IsInfoEnabled) NCacheLog.Info("GroupRequest.doExecute()", "sending request (id=" + req_id + ')');
if (corr != null)
{
ArrayList tmp = members != null ? members : null;
if (rsp_mode == GET_FIRST_NHOP || rsp_mode == GET_ALL_NHOP)
corr.sendNHopRequest(req_id, tmp, request_msg, this);
else
corr.sendRequest(req_id, tmp, request_msg, rsp_mode == GET_NONE ? null : this);
}
else
{
transport.send(request_msg);
}
}
catch (System.Exception e)
{
NCacheLog.Error("GroupRequest.doExecute()", "exception=" + e.Message);
if (corr != null)
{
corr.done(req_id);
}
return false;
}
long orig_timeout = timeout;
if (timeout <= 0)
{
while (true)
{
/* Wait for responses: */
adjustMembership(); // may not be necessary, just to make sure...
if (Responses)
{
if (corr != null)
{
corr.done(req_id);
}
if (NCacheLog.IsInfoEnabled) NCacheLog.Info("GroupRequest.doExecute()", "received all responses: " + ToString());
return true;
}
try
{
System.Threading.Monitor.Wait(rsp_mutex);
}
catch (System.Exception e)
{
NCacheLog.Error("GroupRequest.doExecute():2", "exception=" + e.Message);
}
}
}
else
{
start_time = (System.DateTime.Now.Ticks - 621355968000000000) / 10000;
long wakeuptime = timeout;
int retries = ServiceConfiguration.RequestEnquiryInterval;
int enquiryFailure = 0;
if (ServiceConfiguration.AllowRequestEnquiry)
{
wakeuptime = ServiceConfiguration.RequestEnquiryInterval * 1000;
}
while (timeout > 0)
{
/* Wait for responses: */
if (Responses)
{
if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("GrpReq.doExec", "req_id :" + req_id + " completed" );
if (corr != null)
corr.done(req_id);
if (NCacheLog.IsInfoEnabled) NCacheLog.Info("GroupRequest.doExecute()", "received all responses: " + ToString());
return true;
}
timeout = orig_timeout - ((System.DateTime.Now.Ticks - 621355968000000000) / 10000 - start_time);
if (ServiceConfiguration.AllowRequestEnquiry)
{
if (wakeuptime > timeout)
wakeuptime = timeout;
}
else
{
wakeuptime = timeout;
}
if (timeout > 0)
{
try
{
timeout = orig_timeout - ((System.DateTime.Now.Ticks - 621355968000000000) / 10000 - start_time);
bool reacquired = System.Threading.Monitor.Wait(rsp_mutex, TimeSpan.FromMilliseconds(wakeuptime));
if ((!reacquired || _seqReset) && ServiceConfiguration.AllowRequestEnquiry)
{
//_seqReset = false;
if (Responses)
{
if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("GrpReq.doExec", "req_id :" + req_id + " completed");
if (corr != null)
corr.done(req_id);
if (NCacheLog.IsInfoEnabled) NCacheLog.Info("GroupRequest.doExecute()", "received all responses: " + ToString());
return true;
}
else
{
if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("GrpReq.doExec", "req_id :" + req_id + " completed");
if ((timeout > 0 && wakeuptime < timeout) && retries > 0)
{
if (_seqReset)
{
_retriesAfteSeqReset++;
}
retries--;
bool enquireAgain = GetRequestStatus();
if (!enquireAgain)
enquiryFailure++;
if (enquiryFailure >=3 || _retriesAfteSeqReset > 3)
{
if (corr != null)
corr.done(req_id);
return false;
}
}
}
}
}
catch (System.Exception e)
{
NCacheLog.Error("GroupRequest.doExecute():3", "exception=" + e);
}
}
}
if (timeout <= 0)
{
RspList rspList = Results;
string failedNodes = "";
if (rspList != null)
{
for (int i = 0; i < rspList.size(); i++)
{
Rsp rsp = rspList.elementAt(i) as Rsp;
if (rsp != null && !rsp.wasReceived())
failedNodes += rsp.Sender;
}
}
if (NCacheLog.IsInfoEnabled) NCacheLog.Info("GroupRequest.doExecute:", "[ " + req_id + " ] did not receive rsp from " + failedNodes + " [Timeout] " + timeout + " [timeout-val =" + orig_timeout + "]");
}
if (corr != null)
{
corr.done(req_id);
}
return false;
}
}
private bool GetRequestStatus()
{
Hashtable statusResult = null;
ArrayList failedNodes = new ArrayList();
RspList rspList = Results;
bool enquireStatusAgain = true;
int suspectCount = 0;
string notRecvNodes = "";
if (rspList != null)
{
for (int i = 0; i < rspList.size(); i++)
{
Rsp rsp = rspList.elementAt(i) as Rsp;
if (rsp != null && !rsp.wasReceived())
{
notRecvNodes += rsp.sender + ",";
failedNodes.Add(rsp.Sender);
}
if (rsp != null && rsp.wasSuspected())
suspectCount++;
}
}
if (NCacheLog.IsInfoEnabled) NCacheLog.Info("GroupRequest.GetReqStatus", req_id + " rsp not received from " + failedNodes.Count + " nodes");
bool resendReq = true;
ArrayList resendList = new ArrayList();
int notRespondingCount = 0;
if(failedNodes.Count >0)
{
if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("GrpReq.GetReqStatus", " did not recv rsps from " + notRecvNodes + " nodes");
statusResult = corr.FetchRequestStatus(failedNodes, this.clusterMembership, req_id);
StringBuilder sb = null;
if (ServerMonitor.MonitorActivity) sb = new StringBuilder();
if (statusResult != null)
{
foreach (Address node in failedNodes)
{
RequestStatus status = statusResult[node] as RequestStatus;
if (status.Status == RequestStatus.REQ_NOT_RECEIVED)
{
if(sb != null) sb.Append("(" + node + ":" + "REQ_NOT_RECEIVED)");
resendList.Add(node);
}
if (status.Status == RequestStatus.NONE)
{
if (sb != null) sb.Append("(" + node + ":" + "NONE)");
notRespondingCount++;
}
if (status.Status == RequestStatus.REQ_PROCESSED)
{
if (sb != null) sb.Append("(" + node + ":" + "REQ_PROCESSED)");
if (!request_msg.IsSeqRequired)
{
resendList.Add(node);
}
}
}
if (sb != null && ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("GrpReq.GetReqStatus", "status of failed nodes " + sb.ToString());
if (request_msg.IsSeqRequired)
{
if (resendList.Count != rspList.size())
{
if (NCacheLog.IsInfoEnabled) NCacheLog.Info("GroupRequest.GetReqStatus", req_id + "sequence message; no need to resend; resend_count " + resendList.Count);
if (notRespondingCount > 0)
{
resendReq = false;
}
else
{
enquireStatusAgain = false;
resendReq = false;
}
}
}
if (NCacheLog.IsInfoEnabled) NCacheLog.Info("GroupRequest.GetReqStatus", req_id + "received REQ_NOT_RECEIVED status from " + resendList.Count + " nodes");
}
else
if (NCacheLog.IsInfoEnabled) NCacheLog.Info("GroupRequest.GetReqStatus", req_id + " status result is NULL");
if (resendReq && resendList.Count > 0)
{
if (corr != null)
{
if (resendList.Count == 1)
{
request_msg.Dest = resendList[0] as Address;
}
else
{
request_msg.Dests = resendList;
}
if (NCacheLog.IsInfoEnabled) NCacheLog.Info("GroupRequest.GetReqStatus", req_id + " resending messages to " + resendList.Count);
corr.sendRequest(req_id, resendList, request_msg, rsp_mode == GET_NONE ? null : this);
}
}
}
return enquireStatusAgain;
}
/// <summary>Return number of elements of a certain type in array 'received'. Type can be RECEIVED,
/// NOT_RECEIVED or SUSPECTED
/// </summary>
public virtual int getNum(int type)
{
int retval = 0;
for (int i = 0; i < received.Length; i++)
if (received[i] == type)
retval++;
return retval;
}
public virtual int getNumFromNHops(int type)
{
int retval = 0;
lock (_nhopMutex)
{
foreach (Address replica in nHops)
{
byte status = 0;
if (receivedFromNHops.TryGetValue(replica, out status))
{
if (status == type)
retval++;
}
}
}
return retval;
}
public virtual void printReceived()
{
for (int i = 0; i < received.Length; i++)
{
if (NCacheLog.IsInfoEnabled) NCacheLog.Info(membership[i] + ": " + (received[i] == NOT_RECEIVED ? "NOT_RECEIVED" : (received[i] == RECEIVED ? "RECEIVED" : "SUSPECTED")));
}
}
/// <summary> Adjusts the 'received' array in the following way:
/// <ul>
/// <li>if a member P in 'membership' is not in 'members', P's entry in the 'received' array
/// will be marked as SUSPECTED
/// <li>if P is 'suspected_mbr', then P's entry in the 'received' array will be marked
/// as SUSPECTED
/// </ul>
/// This call requires exclusive access to rsp_mutex (called by getResponses() which has
/// a the rsp_mutex locked, so this should not be a problem).
/// </summary>
public virtual void adjustMembership()
{
Address mbr;
if (membership == null || membership.Length == 0)
{
return;
}
for (int i = 0; i < membership.Length; i++)
{
mbr = membership[i];
if ((this.members != null && !this.members.Contains(mbr)) || suspects.Contains(mbr))
{
addSuspect(mbr);
responses[i] = null;
received[i] = SUSPECTED;
}
}
}
/// <summary> Adds a member to the 'suspects' list. Removes oldest elements from 'suspects' list
/// to keep the list bounded ('max_suspects' number of elements)
/// </summary>
public virtual void addSuspect(Address suspected_mbr)
{
if (!suspects.Contains(suspected_mbr))
{
suspects.Add(suspected_mbr);
while (suspects.Count >= max_suspects && suspects.Count > 0)
suspects.RemoveAt(0); // keeps queue bounded
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Versioning;
using EnvDTE;
using Microsoft.VisualStudio.Shell;
using NuGet.VisualStudio.Resources;
using VSLangProj;
using MsBuildProject = Microsoft.Build.Evaluation.Project;
using MsBuildProjectItem = Microsoft.Build.Evaluation.ProjectItem;
using Project = EnvDTE.Project;
namespace NuGet.VisualStudio {
public class VsProjectSystem : PhysicalFileSystem, IProjectSystem, IVsProjectSystem {
private const string BinDir = "bin";
private static readonly string[] AssemblyReferencesExtensions = new[] { ".dll", ".exe" };
private FrameworkName _targetFramework;
public VsProjectSystem(Project project)
: base(project.GetFullPath()) {
Project = project;
}
protected Project Project {
get;
private set;
}
public virtual string ProjectName {
get {
return Project.Name;
}
}
public string UniqueName {
get {
return Project.UniqueName;
}
}
public FrameworkName TargetFramework {
get {
if (_targetFramework == null) {
_targetFramework = GetTargetFramework() ?? VersionUtility.DefaultTargetFramework;
}
return _targetFramework;
}
}
private FrameworkName GetTargetFramework() {
string targetFrameworkMoniker = Project.GetPropertyValue<string>("TargetFrameworkMoniker");
if (targetFrameworkMoniker != null) {
return new FrameworkName(targetFrameworkMoniker);
}
return null;
}
public override void AddFile(string path, Stream stream) {
// If the file exists on disk but not in the project then skip it
if (base.FileExists(path) && !FileExistsInProject(path)) {
Logger.Log(MessageLevel.Warning, VsResources.Warning_FileAlreadyExists, path);
}
else {
EnsureCheckedOutIfExists(path);
base.AddFile(path, stream);
AddFileToProject(path);
}
}
public override void DeleteDirectory(string path, bool recursive = false) {
// Only delete this folder if it is empty and we didn't specify that we want to recurse
if (!recursive && (base.GetFiles(path, "*.*").Any() || base.GetDirectories(path).Any())) {
Logger.Log(MessageLevel.Warning, VsResources.Warning_DirectoryNotEmpty, path);
return;
}
if (Project.DeleteProjectItem(path)) {
Logger.Log(MessageLevel.Debug, VsResources.Debug_RemovedFolder, path);
}
}
public override void DeleteFile(string path) {
if (Project.DeleteProjectItem(path)) {
string folderPath = Path.GetDirectoryName(path);
if (!String.IsNullOrEmpty(folderPath)) {
Logger.Log(MessageLevel.Debug, VsResources.Debug_RemovedFileFromFolder, Path.GetFileName(path), folderPath);
}
else {
Logger.Log(MessageLevel.Debug, VsResources.Debug_RemovedFile, Path.GetFileName(path));
}
}
}
public void AddFrameworkReference(string name) {
try {
// Add a reference to the project
AddGacReference(name);
Logger.Log(MessageLevel.Debug, VsResources.Debug_AddReference, name, ProjectName);
}
catch (Exception e) {
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, VsResources.FailedToAddGacReference, name), e);
}
}
protected virtual void AddGacReference(string name) {
Project.Object.References.Add(name);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We want to catch all exceptions")]
public virtual void AddReference(string referencePath, Stream stream) {
string name = Path.GetFileNameWithoutExtension(referencePath);
try {
// Get the full path to the reference
string fullPath = PathUtility.GetAbsolutePath(Root, referencePath);
// Add a reference to the project
Reference reference = Project.Object.References.Add(fullPath);
// Always set copy local to true for references that we add
reference.CopyLocal = true;
// This happens if the assembly appears in any of the search paths that VS uses to locate assembly references.
// Most commmonly, it happens if this assembly is in the GAC or in the output path.
if (!reference.Path.Equals(fullPath, StringComparison.OrdinalIgnoreCase)) {
// Get the msbuild project for this project
MsBuildProject buildProject = Project.AsMSBuildProject();
if (buildProject != null) {
// Get the assembly name of the reference we are trying to add
AssemblyName assemblyName = AssemblyName.GetAssemblyName(fullPath);
// Try to find the item for the assembly name
MsBuildProjectItem item = (from assemblyReferenceNode in buildProject.GetAssemblyReferences()
where AssemblyNamesMatch(assemblyName, assemblyReferenceNode.Item2)
select assemblyReferenceNode.Item1).FirstOrDefault();
if (item != null) {
// Add the <HintPath> metadata item as a relative path
item.SetMetadataValue("HintPath", referencePath);
// Save the project after we've modified it.
Project.Save();
}
}
}
Logger.Log(MessageLevel.Debug, VsResources.Debug_AddReference, name, ProjectName);
}
catch (Exception e) {
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, VsResources.FailedToAddReference, name), e);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We want to catch all exceptions")]
public virtual void RemoveReference(string name) {
try {
// Get the reference name without extension
string referenceName = Path.GetFileNameWithoutExtension(name);
// Remove the reference from the project
var reference = Project.Object.References.Item(referenceName);
if (reference != null) {
reference.Remove();
Logger.Log(MessageLevel.Debug, VsResources.Debug_RemoveReference, name, ProjectName);
}
}
catch (Exception e) {
Logger.Log(MessageLevel.Warning, e.Message);
}
}
public override bool FileExists(string path) {
// Only check the project system if the file is on disk to begin with
if (base.FileExists(path)) {
// See if the file is in the project system
return FileExistsInProject(path);
}
return false;
}
private bool FileExistsInProject(string path) {
return Project.GetProjectItem(path) != null;
}
protected virtual bool ExcludeFile(string path) {
// Exclude files from the bin directory.
return Path.GetDirectoryName(path).Equals(BinDir, StringComparison.OrdinalIgnoreCase);
}
protected virtual void AddFileToProject(string path) {
if (ExcludeFile(path)) {
return;
}
// Get the project items for the folder path
string folderPath = Path.GetDirectoryName(path);
string fullPath = GetFullPath(path);
ThreadHelper.Generic.Invoke(() => {
ProjectItems container = Project.GetProjectItems(folderPath, createIfNotExists: true);
// Add the file to the project
container.AddFromFileCopy(fullPath);
});
Logger.Log(MessageLevel.Debug, VsResources.Debug_AddedFileToProject, path, ProjectName);
}
public virtual string ResolvePath(string path) {
return path;
}
public override IEnumerable<string> GetFiles(string path, string filter) {
// Get all physical files
return from p in Project.GetChildItems(path, filter, VsConstants.VsProjectItemKindPhysicalFile)
select p.Name;
}
public override IEnumerable<string> GetDirectories(string path) {
// Get all physical folders
return from p in Project.GetChildItems(path, "*.*", VsConstants.VsProjectItemKindPhysicalFolder)
select p.Name;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We never want to fail when checking for existance")]
public virtual bool ReferenceExists(string name) {
try {
string referenceName = name;
if (AssemblyReferencesExtensions.Contains(Path.GetExtension(name), StringComparer.OrdinalIgnoreCase)) {
// Get the reference name without extension
referenceName = Path.GetFileNameWithoutExtension(name);
}
return Project.Object.References.Item(referenceName) != null;
}
catch {
}
return false;
}
public virtual dynamic GetPropertyValue(string propertyName) {
try {
Property property = Project.Properties.Item(propertyName);
if (property != null) {
return property.Value;
}
}
catch (ArgumentException) {
// If the property doesn't exist this will throw an argument exception
}
return null;
}
public virtual bool IsSupportedFile(string path) {
return !(Path.GetFileName(path).Equals("web.config", StringComparison.OrdinalIgnoreCase));
}
private void EnsureCheckedOutIfExists(string path) {
string fullPath = GetFullPath(path);
if (FileExists(path) &&
Project.DTE.SourceControl != null &&
Project.DTE.SourceControl.IsItemUnderSCC(fullPath) &&
!Project.DTE.SourceControl.IsItemCheckedOut(fullPath)) {
// Check out the item
Project.DTE.SourceControl.CheckOutItem(fullPath);
}
}
private static bool AssemblyNamesMatch(AssemblyName name1, AssemblyName name2) {
return name1.Name.Equals(name2.Name, StringComparison.OrdinalIgnoreCase) &&
EqualsIfNotNull(name1.Version, name2.Version) &&
EqualsIfNotNull(name1.CultureInfo, name2.CultureInfo) &&
EqualsIfNotNull(name1.GetPublicKeyToken(), name2.GetPublicKeyToken(), Enumerable.SequenceEqual);
}
private static bool EqualsIfNotNull<T>(T obj1, T obj2) {
return EqualsIfNotNull(obj1, obj2, (a, b) => a.Equals(b));
}
private static bool EqualsIfNotNull<T>(T obj1, T obj2, Func<T, T, bool> equals) {
// If both objects are non null do the equals
if (obj1 != null && obj2 != null) {
return equals(obj1, obj2);
}
// Otherwise consider them equal if either of the values are null
return true;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.RegionLoader.Filesystem;
using OpenSim.Framework.RegionLoader.Web;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
namespace OpenSim.ApplicationPlugins.LoadRegions
{
public class LoadRegionsPlugin : IApplicationPlugin, IRegionCreator
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public event NewRegionCreated OnNewRegionCreated;
private NewRegionCreated m_newRegionCreatedHandler;
#region IApplicationPlugin Members
// TODO: required by IPlugin, but likely not at all right
private string m_name = "LoadRegionsPlugin";
private string m_version = "0.0";
public string Version
{
get { return m_version; }
}
public string Name
{
get { return m_name; }
}
protected OpenSimBase m_openSim;
public void Initialise()
{
m_log.Error("[LOAD REGIONS PLUGIN]: " + Name + " cannot be default-initialized!");
throw new PluginNotInitialisedException(Name);
}
public void Initialise(OpenSimBase openSim)
{
m_openSim = openSim;
m_openSim.ApplicationRegistry.RegisterInterface<IRegionCreator>(this);
}
public void PostInitialise()
{
//m_log.Info("[LOADREGIONS]: Load Regions addin being initialised");
IRegionLoader regionLoader;
if (m_openSim.ConfigSource.Source.Configs["Startup"].GetString("region_info_source", "filesystem") == "filesystem")
{
m_log.Info("[LOAD REGIONS PLUGIN]: Loading region configurations from filesystem");
regionLoader = new RegionLoaderFileSystem();
}
else
{
m_log.Info("[LOAD REGIONS PLUGIN]: Loading region configurations from web");
regionLoader = new RegionLoaderWebServer();
}
regionLoader.SetIniConfigSource(m_openSim.ConfigSource.Source);
RegionInfo[] regionsToLoad = regionLoader.LoadRegions();
m_log.Info("[LOAD REGIONS PLUGIN]: Loading specific shared modules...");
//m_log.Info("[LOAD REGIONS PLUGIN]: DynamicTextureModule...");
//m_openSim.ModuleLoader.LoadDefaultSharedModule(new DynamicTextureModule());
//m_log.Info("[LOAD REGIONS PLUGIN]: LoadImageURLModule...");
//m_openSim.ModuleLoader.LoadDefaultSharedModule(new LoadImageURLModule());
//m_log.Info("[LOAD REGIONS PLUGIN]: XMLRPCModule...");
//m_openSim.ModuleLoader.LoadDefaultSharedModule(new XMLRPCModule());
// m_log.Info("[LOADREGIONSPLUGIN]: AssetTransactionModule...");
// m_openSim.ModuleLoader.LoadDefaultSharedModule(new AssetTransactionModule());
m_log.Info("[LOAD REGIONS PLUGIN]: Done.");
if (!CheckRegionsForSanity(regionsToLoad))
{
m_log.Error("[LOAD REGIONS PLUGIN]: Halting startup due to conflicts in region configurations");
Environment.Exit(1);
}
List<IScene> createdScenes = new List<IScene>();
for (int i = 0; i < regionsToLoad.Length; i++)
{
IScene scene;
m_log.Debug("[LOAD REGIONS PLUGIN]: Creating Region: " + regionsToLoad[i].RegionName + " (ThreadID: " +
Thread.CurrentThread.ManagedThreadId.ToString() +
")");
bool changed = m_openSim.PopulateRegionEstateInfo(regionsToLoad[i]);
m_openSim.CreateRegion(regionsToLoad[i], true, out scene);
createdScenes.Add(scene);
if (changed)
regionsToLoad[i].EstateSettings.Save();
}
foreach (IScene scene in createdScenes)
{
scene.Start();
m_newRegionCreatedHandler = OnNewRegionCreated;
if (m_newRegionCreatedHandler != null)
{
m_newRegionCreatedHandler(scene);
}
}
}
public void Dispose()
{
}
#endregion
/// <summary>
/// Check that region configuration information makes sense.
/// </summary>
/// <param name="regions"></param>
/// <returns>True if we're sane, false if we're insane</returns>
private bool CheckRegionsForSanity(RegionInfo[] regions)
{
if (regions.Length == 0)
return true;
foreach (RegionInfo region in regions)
{
if (region.RegionID == UUID.Zero)
{
m_log.ErrorFormat(
"[LOAD REGIONS PLUGIN]: Region {0} has invalid UUID {1}",
region.RegionName, region.RegionID);
return false;
}
}
for (int i = 0; i < regions.Length - 1; i++)
{
for (int j = i + 1; j < regions.Length; j++)
{
if (regions[i].RegionID == regions[j].RegionID)
{
m_log.ErrorFormat(
"[LOAD REGIONS PLUGIN]: Regions {0} and {1} have the same UUID {2}",
regions[i].RegionName, regions[j].RegionName, regions[i].RegionID);
return false;
}
else if (
regions[i].RegionLocX == regions[j].RegionLocX && regions[i].RegionLocY == regions[j].RegionLocY)
{
m_log.ErrorFormat(
"[LOAD REGIONS PLUGIN]: Regions {0} and {1} have the same grid location ({2}, {3})",
regions[i].RegionName, regions[j].RegionName, regions[i].RegionLocX, regions[i].RegionLocY);
return false;
}
else if (regions[i].InternalEndPoint.Port == regions[j].InternalEndPoint.Port)
{
m_log.ErrorFormat(
"[LOAD REGIONS PLUGIN]: Regions {0} and {1} have the same internal IP port {2}",
regions[i].RegionName, regions[j].RegionName, regions[i].InternalEndPoint.Port);
return false;
}
}
}
return true;
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
namespace UMA.CharacterSystem.Editors
{
[CustomPropertyDrawer(typeof(DynamicDNAConverterBehaviour.SkeletonModifier))]
public class SkeletonModifierPropertyDrawer : PropertyDrawer
{
float padding = 2f;
public List<string> hashNames = new List<string>();
//used when editing in playmode has the actual boneHashes from the avatars skeleton
public List<string> bonesInSkeleton = null;
public List<int> hashes = new List<int>();
public string[] dnaNames;
public bool enableSkelModValueEditing = false;
spValModifierPropertyDrawer thisSpValDrawer = null;
Texture warningIcon;
GUIStyle warningStyle;
public void Init(List<string> _hashNames, List<int> _hashes, string[] _dnaNames = null)
{
hashNames = _hashNames;
hashes = _hashes;
dnaNames = _dnaNames;
if(thisSpValDrawer == null)
thisSpValDrawer = new spValModifierPropertyDrawer();
thisSpValDrawer.dnaNames = dnaNames;
if (warningIcon == null)
{
warningIcon = EditorGUIUtility.FindTexture("console.warnicon.sml");
warningStyle = new GUIStyle(EditorStyles.label);
warningStyle.fixedHeight = warningIcon.height + 4f;
warningStyle.contentOffset = new Vector2(0, -2f);
}
}
public void UpdateHashNames(List<string> _hashNames, List<int> _hashes)
{
hashNames = _hashNames;
hashes = _hashes;
}
public void UpdateDnaNames(string[] newDnaNames)
{
if(thisSpValDrawer != null)
thisSpValDrawer.dnaNames = newDnaNames;
}
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
int startingIndent = EditorGUI.indentLevel;
EditorGUI.BeginProperty(position, label, property);
var valR = new Rect(position.xMin, position.yMin, position.width, EditorGUIUtility.singleLineHeight);
string betterLabel = label.text;
if (property.FindPropertyRelative("property").enumDisplayNames[property.FindPropertyRelative("property").enumValueIndex] != "")
{
betterLabel += " (" + property.FindPropertyRelative("property").enumDisplayNames[property.FindPropertyRelative("property").enumValueIndex] + ")";
}
List<string> boneNames = new List<string>();
if (bonesInSkeleton != null)
{
boneNames = new List<string>(bonesInSkeleton);
}
else
{
boneNames = new List<string>(hashNames);
}
string thisHashName = property.FindPropertyRelative("hashName").stringValue;
int hashNameIndex = boneNames.IndexOf(thisHashName);
if (hashNameIndex == -1 && bonesInSkeleton != null)
{
boneNames.Insert(0, thisHashName + " (missing)");
hashNameIndex = 0;
var warningRect = new Rect((valR.xMin), valR.yMin, 20f, valR.height);
var warningIconGUI = new GUIContent("", thisHashName + " was not a bone in the Avatars Skeleton. Please choose another bone for this modifier or delete it.");
warningIconGUI.image = warningIcon;
betterLabel += " (missing)";
GUI.Label(warningRect, warningIconGUI, warningStyle);
}
property.isExpanded = EditorGUI.Foldout(valR, property.isExpanded, betterLabel, true);
if (property.isExpanded)
{
EditorGUI.indentLevel++;
valR = new Rect(valR.xMin, valR.yMax + padding, valR.width, EditorGUIUtility.singleLineHeight);
if (boneNames.Count > 0)
{
int newHashNameIndex = hashNameIndex;
EditorGUI.BeginChangeCheck();
newHashNameIndex = EditorGUI.Popup(valR, "Hash Name", hashNameIndex, boneNames.ToArray());
if (EditorGUI.EndChangeCheck())
{
if (newHashNameIndex != hashNameIndex)
{
property.FindPropertyRelative("hashName").stringValue = boneNames[newHashNameIndex];
property.FindPropertyRelative("hash").intValue = UMAUtils.StringToHash(boneNames[newHashNameIndex]);
property.serializedObject.ApplyModifiedProperties();
}
}
}
else
{
EditorGUI.PropertyField(valR, property.FindPropertyRelative("hashName"));
}
valR = new Rect(valR.xMin, valR.yMax + padding, valR.width, EditorGUIUtility.singleLineHeight);
EditorGUI.PropertyField(valR, property.FindPropertyRelative("property"));
valR = new Rect(valR.xMin, valR.yMax + padding, valR.width, EditorGUIUtility.singleLineHeight);
var valXR = valR;
var valYR = valR;
var valZR = valR;
valXR.width = valYR.width = valZR.width = valR.width / 3;
valYR.x = valYR.x + valXR.width;
valZR.x = valZR.x + valXR.width + valYR.width;
SerializedProperty subValsToOpen = null;
var valuesX = property.FindPropertyRelative("valuesX");
var valuesY = property.FindPropertyRelative("valuesY");
var valuesZ = property.FindPropertyRelative("valuesZ");
if (valuesX.isExpanded)
{
var valXRB = valXR;
valXRB.x = valXRB.x + (EditorGUI.indentLevel * 10f);
valXRB.width = valXRB.width - (EditorGUI.indentLevel * 10f);
EditorGUI.DrawRect(valXRB, new Color32(255, 255, 255, 100));
}
valuesX.isExpanded = EditorGUI.Foldout(valXR, valuesX.isExpanded, "ValuesX", true);
if (valuesX.isExpanded)
{
valuesY.isExpanded = false;
valuesZ.isExpanded = false;
subValsToOpen = valuesX;
}
if (valuesY.isExpanded)
{
EditorGUI.DrawRect(valYR, new Color32(255, 255, 255, 100));
}
valuesY.isExpanded = EditorGUI.Foldout(valYR, valuesY.isExpanded, "ValuesY", true);
if (valuesY.isExpanded)
{
valuesX.isExpanded = false;
valuesZ.isExpanded = false;
subValsToOpen = valuesY;
}
if (valuesZ.isExpanded)
{
EditorGUI.DrawRect(valZR, new Color32(255, 255, 255, 100));
}
valuesZ.isExpanded = EditorGUI.Foldout(valZR, valuesZ.isExpanded, "ValuesZ", true);
if (valuesZ.isExpanded)
{
valuesX.isExpanded = false;
valuesY.isExpanded = false;
subValsToOpen = valuesZ;
}
if (subValsToOpen != null)
{
valR = new Rect(valR.xMin, valR.yMax + padding + 4f, valR.width, EditorGUIUtility.singleLineHeight);
valR.width = valR.width - 30;
var boxR1 = valR;
boxR1.x = boxR1.x + EditorGUI.indentLevel * 10f;
boxR1.y = boxR1.y - 6;
boxR1.height = boxR1.height + 12;
//topbox
EditorGUI.DrawRect(boxR1, new Color32(255, 255, 255, 100));
var valSXR = valR;
var valSYR = valR;
var valSZR = valR;
valSXR.width = valSYR.width = valSZR.width = valR.width / 3;
valSYR.x = valSYR.x + valSXR.width;
valSZR.x = valSZR.x + valSXR.width + valSYR.width;
var subValuesVal = subValsToOpen.FindPropertyRelative("val");
var subValuesMin = subValsToOpen.FindPropertyRelative("min");
var subValuesMax = subValsToOpen.FindPropertyRelative("max");
var valSXRF = valSXR;
valSXRF.x = valSXRF.x + 38f;
valSXRF.width = valSXRF.width - 35f;
if (!enableSkelModValueEditing) EditorGUI.BeginDisabledGroup(true);
EditorGUI.LabelField(valSXR, "Value");
subValuesVal.FindPropertyRelative("value").floatValue = EditorGUI.FloatField(valSXRF, subValuesVal.FindPropertyRelative("value").floatValue);
subValuesVal.serializedObject.ApplyModifiedProperties();
if (!enableSkelModValueEditing) EditorGUI.EndDisabledGroup();
var valSYRF = valSYR;
valSYRF.x = valSYRF.x + 30f;
valSYRF.width = valSYRF.width - 30f;
EditorGUI.LabelField(valSYR, "Min");
subValuesMin.floatValue = EditorGUI.FloatField(valSYRF, subValuesMin.floatValue);
var valSZRF = valSZR;
valSZRF.x = valSZRF.x + 30f;
valSZRF.width = valSZRF.width - 30f;
EditorGUI.LabelField(valSZR, "Max");
subValuesMax.floatValue = EditorGUI.FloatField(valSZRF, subValuesMax.floatValue);
var thisModifiersProp = subValuesVal.FindPropertyRelative("modifiers");
var modifiersi = thisModifiersProp.arraySize;
valR = new Rect(valR.xMin, valR.yMax + padding + 4f, valR.width, EditorGUIUtility.singleLineHeight);
var boxR = valR;
boxR.y = boxR.y - 2f;
boxR.x = boxR.x + EditorGUI.indentLevel * 10f;
boxR.height = boxR.height + 6f + ((EditorGUIUtility.singleLineHeight + padding) * (modifiersi + 1));
//bottombox
EditorGUI.DrawRect(boxR, new Color32(255, 255, 255, 100));
EditorGUI.LabelField(valR, "Value Modifiers");
for (int i = 0; i < modifiersi; i++)
{
valR = new Rect(valR.xMin, valR.yMax + padding, valR.width, EditorGUIUtility.singleLineHeight);
var propsR = valR;
propsR.width = valR.width;
var valRBut = new Rect((propsR.width + 35f), valR.y, 20f, EditorGUIUtility.singleLineHeight);
thisSpValDrawer.OnGUI(propsR, thisModifiersProp.GetArrayElementAtIndex(i), new GUIContent(""));
if (GUI.Button(valRBut, "X"))
{
thisModifiersProp.DeleteArrayElementAtIndex(i);
}
}
var addBut = new Rect(valR.xMin, valR.yMax + padding, valR.width, EditorGUIUtility.singleLineHeight);
addBut.x = addBut.xMax - 35f;
addBut.width = 60f;
if (GUI.Button(addBut, "Add"))
{
thisModifiersProp.InsertArrayElementAtIndex(modifiersi);
}
thisModifiersProp.serializedObject.ApplyModifiedProperties();
}
}
EditorGUI.indentLevel = startingIndent;
EditorGUI.EndProperty();
}
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
float h = EditorGUIUtility.singleLineHeight + padding;
int extraLines = 1;
float extrapix = 0;
if (property.isExpanded)
{
extraLines = extraLines + 3;
var valuesX = property.FindPropertyRelative("valuesX");
var valuesY = property.FindPropertyRelative("valuesY");
var valuesZ = property.FindPropertyRelative("valuesZ");
if (valuesX.isExpanded || valuesY.isExpanded || valuesZ.isExpanded)
{
extraLines++;
var activeValues = valuesX.isExpanded ? valuesX : (valuesY.isExpanded ? valuesY : valuesZ);
var subValuesVal = activeValues.FindPropertyRelative("val");
extraLines++;
extraLines++;
extraLines += subValuesVal.FindPropertyRelative("modifiers").arraySize;
extrapix = 10f;
}
h *= (extraLines);
h += extrapix;
}
return h;
}
}
[CustomPropertyDrawer(typeof(DynamicDNAConverterBehaviour.SkeletonModifier.spVal.spValValue.spValModifier))]
public class spValModifierPropertyDrawer : PropertyDrawer
{
public string[] dnaNames;
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
int startingIndent = EditorGUI.indentLevel;
EditorGUI.BeginProperty(position, label, property);
var valR = new Rect(position.xMin, position.yMin, position.width, EditorGUIUtility.singleLineHeight);
var ddOne = valR;
var ddTwo = valR;
ddOne.width = valR.width / 2f + ((EditorGUI.indentLevel - 1) * 10);
ddTwo.width = valR.width / 2f - ((EditorGUI.indentLevel - 1) * 10);
ddTwo.x = ddTwo.x + ddOne.width;
var modifieri = property.FindPropertyRelative("modifier").enumValueIndex;
EditorGUI.PropertyField(ddOne, property.FindPropertyRelative("modifier"), new GUIContent(""));
EditorGUI.indentLevel = 0;
if (modifieri > 3)
{
string currentVal = property.FindPropertyRelative("DNATypeName").stringValue;
if (dnaNames == null || dnaNames.Length == 0)
{
//If there are no names show a field with the dna name in it with a warning tooltip
EditorGUI.BeginDisabledGroup(true);
EditorGUI.LabelField(ddTwo, new GUIContent(property.FindPropertyRelative("DNATypeName").stringValue, "You do not have any DNA Names set up in your DNA asset. Add some names for the Skeleton Modifiers to use."), EditorStyles.textField);
EditorGUI.EndDisabledGroup();
}
else
{
int selectedIndex = -1;
List<GUIContent> niceDNANames = new List<GUIContent>();
niceDNANames.Add(new GUIContent("None"));
bool missing = currentVal != "";
for (int i = 0; i < dnaNames.Length; i++)
{
niceDNANames.Add(new GUIContent(dnaNames[i]));
if (dnaNames[i] == currentVal)
{
selectedIndex = i;
missing = false;
}
}
if (missing)
{
niceDNANames[0].text = currentVal+" (missing)";
niceDNANames[0].tooltip = currentVal+ " was not in the DNAAssets names list. This modifier wont do anything until you change the dna name it uses or you add this name to your DNA Asset names.";
}
int newSelectedIndex = selectedIndex == -1 ? 0 : selectedIndex + 1;
EditorGUI.BeginChangeCheck();
newSelectedIndex = EditorGUI.Popup(ddTwo, newSelectedIndex, niceDNANames.ToArray());
if (EditorGUI.EndChangeCheck())
{
//if its actually changed
if (newSelectedIndex != selectedIndex + 1)
{
if (newSelectedIndex == 0)
{
if(niceDNANames[0].text.IndexOf("(missing) ") < 0)
property.FindPropertyRelative("DNATypeName").stringValue = "";
}
else
{
property.FindPropertyRelative("DNATypeName").stringValue = dnaNames[newSelectedIndex - 1];
}
}
}
}
}
else
{
EditorGUI.PropertyField(ddTwo, property.FindPropertyRelative("modifierValue"), new GUIContent(""));
}
EditorGUI.indentLevel = startingIndent;
EditorGUI.EndProperty();
}
}
}
| |
using System;
using System.Globalization;
using Nop.Core;
using Nop.Core.Domain.Catalog;
using Nop.Core.Domain.Directory;
using Nop.Core.Domain.Localization;
using Nop.Core.Domain.Tax;
using Nop.Services.Directory;
using Nop.Services.Localization;
namespace Nop.Services.Catalog
{
/// <summary>
/// Price formatter
/// </summary>
public partial class PriceFormatter : IPriceFormatter
{
#region Fields
private readonly IWorkContext _workContext;
private readonly ICurrencyService _currencyService;
private readonly ILocalizationService _localizationService;
private readonly TaxSettings _taxSettings;
private readonly CurrencySettings _currencySettings;
#endregion
#region Constructors
public PriceFormatter(IWorkContext workContext,
ICurrencyService currencyService,
ILocalizationService localizationService,
TaxSettings taxSettings,
CurrencySettings currencySettings)
{
this._workContext = workContext;
this._currencyService = currencyService;
this._localizationService = localizationService;
this._taxSettings = taxSettings;
this._currencySettings = currencySettings;
}
#endregion
#region Utilities
/// <summary>
/// Gets currency string
/// </summary>
/// <param name="amount">Amount</param>
/// <returns>Currency string without exchange rate</returns>
protected virtual string GetCurrencyString(decimal amount)
{
return GetCurrencyString(amount, true, _workContext.WorkingCurrency);
}
/// <summary>
/// Gets currency string
/// </summary>
/// <param name="amount">Amount</param>
/// <param name="showCurrency">A value indicating whether to show a currency</param>
/// <param name="targetCurrency">Target currency</param>
/// <returns>Currency string without exchange rate</returns>
protected virtual string GetCurrencyString(decimal amount,
bool showCurrency, Currency targetCurrency)
{
if (targetCurrency == null)
throw new ArgumentNullException("targetCurrency");
string result = "";
if (!String.IsNullOrEmpty(targetCurrency.CustomFormatting))
{
result = amount.ToString(targetCurrency.CustomFormatting);
}
else
{
if (!String.IsNullOrEmpty(targetCurrency.DisplayLocale))
{
result = amount.ToString("C", new CultureInfo(targetCurrency.DisplayLocale));
}
else
{
result = String.Format("{0} ({1})", amount.ToString("N"), targetCurrency.CurrencyCode);
return result;
}
}
if (showCurrency && _currencySettings.DisplayCurrencyLabel)
result = String.Format("{0} ({1})", result, targetCurrency.CurrencyCode);
return result;
}
#endregion
#region Methods
/// <summary>
/// Formats the price
/// </summary>
/// <param name="price">Price</param>
/// <returns>Price</returns>
public virtual string FormatPrice(decimal price)
{
return FormatPrice(price, true, _workContext.WorkingCurrency);
}
/// <summary>
/// Formats the price
/// </summary>
/// <param name="price">Price</param>
/// <param name="showCurrency">A value indicating whether to show a currency</param>
/// <param name="targetCurrency">Target currency</param>
/// <returns>Price</returns>
public virtual string FormatPrice(decimal price, bool showCurrency, Currency targetCurrency)
{
bool priceIncludesTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax;
return FormatPrice(price, showCurrency, targetCurrency, _workContext.WorkingLanguage, priceIncludesTax);
}
/// <summary>
/// Formats the price
/// </summary>
/// <param name="price">Price</param>
/// <param name="showCurrency">A value indicating whether to show a currency</param>
/// <param name="showTax">A value indicating whether to show tax suffix</param>
/// <returns>Price</returns>
public virtual string FormatPrice(decimal price, bool showCurrency, bool showTax)
{
bool priceIncludesTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax;
return FormatPrice(price, showCurrency, _workContext.WorkingCurrency, _workContext.WorkingLanguage, priceIncludesTax, showTax);
}
/// <summary>
/// Formats the price
/// </summary>
/// <param name="price">Price</param>
/// <param name="showCurrency">A value indicating whether to show a currency</param>
/// <param name="currencyCode">Currency code</param>
/// <param name="showTax">A value indicating whether to show tax suffix</param>
/// <param name="language">Language</param>
/// <returns>Price</returns>
public virtual string FormatPrice(decimal price, bool showCurrency,
string currencyCode, bool showTax, Language language)
{
var currency = _currencyService.GetCurrencyByCode(currencyCode);
if (currency == null)
{
currency = new Currency();
currency.CurrencyCode = currencyCode;
}
bool priceIncludesTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax;
return FormatPrice(price, showCurrency, currency, language, priceIncludesTax, showTax);
}
/// <summary>
/// Formats the price
/// </summary>
/// <param name="price">Price</param>
/// <param name="showCurrency">A value indicating whether to show a currency</param>
/// <param name="currencyCode">Currency code</param>
/// <param name="language">Language</param>
/// <param name="priceIncludesTax">A value indicating whether price includes tax</param>
/// <returns>Price</returns>
public virtual string FormatPrice(decimal price, bool showCurrency,
string currencyCode, Language language, bool priceIncludesTax)
{
var currency = _currencyService.GetCurrencyByCode(currencyCode)
?? new Currency
{
CurrencyCode = currencyCode
};
return FormatPrice(price, showCurrency, currency, language, priceIncludesTax);
}
/// <summary>
/// Formats the price
/// </summary>
/// <param name="price">Price</param>
/// <param name="showCurrency">A value indicating whether to show a currency</param>
/// <param name="targetCurrency">Target currency</param>
/// <param name="language">Language</param>
/// <param name="priceIncludesTax">A value indicating whether price includes tax</param>
/// <returns>Price</returns>
public virtual string FormatPrice(decimal price, bool showCurrency,
Currency targetCurrency, Language language, bool priceIncludesTax)
{
return FormatPrice(price, showCurrency, targetCurrency, language,
priceIncludesTax, _taxSettings.DisplayTaxSuffix);
}
/// <summary>
/// Formats the price
/// </summary>
/// <param name="price">Price</param>
/// <param name="showCurrency">A value indicating whether to show a currency</param>
/// <param name="targetCurrency">Target currency</param>
/// <param name="language">Language</param>
/// <param name="priceIncludesTax">A value indicating whether price includes tax</param>
/// <param name="showTax">A value indicating whether to show tax suffix</param>
/// <returns>Price</returns>
public string FormatPrice(decimal price, bool showCurrency,
Currency targetCurrency, Language language, bool priceIncludesTax, bool showTax)
{
//round before rendering
//should we use RoundingHelper.RoundPrice here?
price = Math.Round(price, 2);
string currencyString = GetCurrencyString(price, showCurrency, targetCurrency);
if (showTax)
{
//show tax suffix
string formatStr;
if (priceIncludesTax)
{
formatStr = _localizationService.GetResource("Products.InclTaxSuffix", language.Id, false);
if (String.IsNullOrEmpty(formatStr))
formatStr = "{0} incl tax";
}
else
{
formatStr = _localizationService.GetResource("Products.ExclTaxSuffix", language.Id, false);
if (String.IsNullOrEmpty(formatStr))
formatStr = "{0} excl tax";
}
return string.Format(formatStr, currencyString);
}
return currencyString;
}
/// <summary>
/// Formats the price of rental product (with rental period)
/// </summary>
/// <param name="product">Product</param>
/// <param name="price">Price</param>
/// <returns>Rental product price with period</returns>
public virtual string FormatRentalProductPeriod(Product product, string price)
{
if (product == null)
throw new ArgumentNullException("product");
if (!product.IsRental)
return price;
if (String.IsNullOrWhiteSpace(price))
return price;
string result;
switch (product.RentalPricePeriod)
{
case RentalPricePeriod.Days:
result = string.Format(_localizationService.GetResource("Products.Price.Rental.Days"), price, product.RentalPriceLength);
break;
case RentalPricePeriod.Weeks:
result = string.Format(_localizationService.GetResource("Products.Price.Rental.Weeks"), price, product.RentalPriceLength);
break;
case RentalPricePeriod.Months:
result = string.Format(_localizationService.GetResource("Products.Price.Rental.Months"), price, product.RentalPriceLength);
break;
case RentalPricePeriod.Years:
result = string.Format(_localizationService.GetResource("Products.Price.Rental.Years"), price, product.RentalPriceLength);
break;
default:
throw new NopException("Not supported rental period");
}
return result;
}
/// <summary>
/// Formats the shipping price
/// </summary>
/// <param name="price">Price</param>
/// <param name="showCurrency">A value indicating whether to show a currency</param>
/// <returns>Price</returns>
public virtual string FormatShippingPrice(decimal price, bool showCurrency)
{
bool priceIncludesTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax;
return FormatShippingPrice(price, showCurrency, _workContext.WorkingCurrency, _workContext.WorkingLanguage, priceIncludesTax);
}
/// <summary>
/// Formats the shipping price
/// </summary>
/// <param name="price">Price</param>
/// <param name="showCurrency">A value indicating whether to show a currency</param>
/// <param name="targetCurrency">Target currency</param>
/// <param name="language">Language</param>
/// <param name="priceIncludesTax">A value indicating whether price includes tax</param>
/// <returns>Price</returns>
public virtual string FormatShippingPrice(decimal price, bool showCurrency,
Currency targetCurrency, Language language, bool priceIncludesTax)
{
bool showTax = _taxSettings.ShippingIsTaxable && _taxSettings.DisplayTaxSuffix;
return FormatShippingPrice(price, showCurrency, targetCurrency, language, priceIncludesTax, showTax);
}
/// <summary>
/// Formats the shipping price
/// </summary>
/// <param name="price">Price</param>
/// <param name="showCurrency">A value indicating whether to show a currency</param>
/// <param name="targetCurrency">Target currency</param>
/// <param name="language">Language</param>
/// <param name="priceIncludesTax">A value indicating whether price includes tax</param>
/// <param name="showTax">A value indicating whether to show tax suffix</param>
/// <returns>Price</returns>
public virtual string FormatShippingPrice(decimal price, bool showCurrency,
Currency targetCurrency, Language language, bool priceIncludesTax, bool showTax)
{
return FormatPrice(price, showCurrency, targetCurrency, language, priceIncludesTax, showTax);
}
/// <summary>
/// Formats the shipping price
/// </summary>
/// <param name="price">Price</param>
/// <param name="showCurrency">A value indicating whether to show a currency</param>
/// <param name="currencyCode">Currency code</param>
/// <param name="language">Language</param>
/// <param name="priceIncludesTax">A value indicating whether price includes tax</param>
/// <returns>Price</returns>
public virtual string FormatShippingPrice(decimal price, bool showCurrency,
string currencyCode, Language language, bool priceIncludesTax)
{
var currency = _currencyService.GetCurrencyByCode(currencyCode)
?? new Currency
{
CurrencyCode = currencyCode
};
return FormatShippingPrice(price, showCurrency, currency, language, priceIncludesTax);
}
/// <summary>
/// Formats the payment method additional fee
/// </summary>
/// <param name="price">Price</param>
/// <param name="showCurrency">A value indicating whether to show a currency</param>
/// <returns>Price</returns>
public virtual string FormatPaymentMethodAdditionalFee(decimal price, bool showCurrency)
{
bool priceIncludesTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax;
return FormatPaymentMethodAdditionalFee(price, showCurrency, _workContext.WorkingCurrency,
_workContext.WorkingLanguage, priceIncludesTax);
}
/// <summary>
/// Formats the payment method additional fee
/// </summary>
/// <param name="price">Price</param>
/// <param name="showCurrency">A value indicating whether to show a currency</param>
/// <param name="targetCurrency">Target currency</param>
/// <param name="language">Language</param>
/// <param name="priceIncludesTax">A value indicating whether price includes tax</param>
/// <returns>Price</returns>
public virtual string FormatPaymentMethodAdditionalFee(decimal price, bool showCurrency,
Currency targetCurrency, Language language, bool priceIncludesTax)
{
bool showTax = _taxSettings.PaymentMethodAdditionalFeeIsTaxable && _taxSettings.DisplayTaxSuffix;
return FormatPaymentMethodAdditionalFee(price, showCurrency, targetCurrency, language, priceIncludesTax, showTax);
}
/// <summary>
/// Formats the payment method additional fee
/// </summary>
/// <param name="price">Price</param>
/// <param name="showCurrency">A value indicating whether to show a currency</param>
/// <param name="targetCurrency">Target currency</param>
/// <param name="language">Language</param>
/// <param name="priceIncludesTax">A value indicating whether price includes tax</param>
/// <param name="showTax">A value indicating whether to show tax suffix</param>
/// <returns>Price</returns>
public virtual string FormatPaymentMethodAdditionalFee(decimal price, bool showCurrency,
Currency targetCurrency, Language language, bool priceIncludesTax, bool showTax)
{
return FormatPrice(price, showCurrency, targetCurrency, language,
priceIncludesTax, showTax);
}
/// <summary>
/// Formats the payment method additional fee
/// </summary>
/// <param name="price">Price</param>
/// <param name="showCurrency">A value indicating whether to show a currency</param>
/// <param name="currencyCode">Currency code</param>
/// <param name="language">Language</param>
/// <param name="priceIncludesTax">A value indicating whether price includes tax</param>
/// <returns>Price</returns>
public virtual string FormatPaymentMethodAdditionalFee(decimal price, bool showCurrency,
string currencyCode, Language language, bool priceIncludesTax)
{
var currency = _currencyService.GetCurrencyByCode(currencyCode)
?? new Currency
{
CurrencyCode = currencyCode
};
return FormatPaymentMethodAdditionalFee(price, showCurrency, currency,
language, priceIncludesTax);
}
/// <summary>
/// Formats a tax rate
/// </summary>
/// <param name="taxRate">Tax rate</param>
/// <returns>Formatted tax rate</returns>
public virtual string FormatTaxRate(decimal taxRate)
{
return taxRate.ToString("G29");
}
#endregion
}
}
| |
/*
* Location Intelligence APIs
*
* Incorporate our extensive geodata into everyday applications, business processes and workflows.
*
* OpenAPI spec version: 8.5.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* 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 System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace pb.locationIntelligence.Model
{
/// <summary>
/// SchoolRanking
/// </summary>
[DataContract]
public partial class SchoolRanking : IEquatable<SchoolRanking>
{
/// <summary>
/// Initializes a new instance of the <see cref="SchoolRanking" /> class.
/// </summary>
/// <param name="Current">Current.</param>
/// <param name="RankYear">RankYear.</param>
/// <param name="StateRank">StateRank.</param>
/// <param name="NumberOfSchools">NumberOfSchools.</param>
/// <param name="AvgMathScore">AvgMathScore.</param>
/// <param name="AvgReadingScore">AvgReadingScore.</param>
/// <param name="StatePercentileScore">StatePercentileScore.</param>
public SchoolRanking(string Current = null, string RankYear = null, string StateRank = null, string NumberOfSchools = null, string AvgMathScore = null, string AvgReadingScore = null, string StatePercentileScore = null)
{
this.Current = Current;
this.RankYear = RankYear;
this.StateRank = StateRank;
this.NumberOfSchools = NumberOfSchools;
this.AvgMathScore = AvgMathScore;
this.AvgReadingScore = AvgReadingScore;
this.StatePercentileScore = StatePercentileScore;
}
/// <summary>
/// Gets or Sets Current
/// </summary>
[DataMember(Name="current", EmitDefaultValue=false)]
public string Current { get; set; }
/// <summary>
/// Gets or Sets RankYear
/// </summary>
[DataMember(Name="rankYear", EmitDefaultValue=false)]
public string RankYear { get; set; }
/// <summary>
/// Gets or Sets StateRank
/// </summary>
[DataMember(Name="stateRank", EmitDefaultValue=false)]
public string StateRank { get; set; }
/// <summary>
/// Gets or Sets NumberOfSchools
/// </summary>
[DataMember(Name="numberOfSchools", EmitDefaultValue=false)]
public string NumberOfSchools { get; set; }
/// <summary>
/// Gets or Sets AvgMathScore
/// </summary>
[DataMember(Name="avgMathScore", EmitDefaultValue=false)]
public string AvgMathScore { get; set; }
/// <summary>
/// Gets or Sets AvgReadingScore
/// </summary>
[DataMember(Name="avgReadingScore", EmitDefaultValue=false)]
public string AvgReadingScore { get; set; }
/// <summary>
/// Gets or Sets StatePercentileScore
/// </summary>
[DataMember(Name="statePercentileScore", EmitDefaultValue=false)]
public string StatePercentileScore { 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 SchoolRanking {\n");
sb.Append(" Current: ").Append(Current).Append("\n");
sb.Append(" RankYear: ").Append(RankYear).Append("\n");
sb.Append(" StateRank: ").Append(StateRank).Append("\n");
sb.Append(" NumberOfSchools: ").Append(NumberOfSchools).Append("\n");
sb.Append(" AvgMathScore: ").Append(AvgMathScore).Append("\n");
sb.Append(" AvgReadingScore: ").Append(AvgReadingScore).Append("\n");
sb.Append(" StatePercentileScore: ").Append(StatePercentileScore).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as SchoolRanking);
}
/// <summary>
/// Returns true if SchoolRanking instances are equal
/// </summary>
/// <param name="other">Instance of SchoolRanking to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(SchoolRanking other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Current == other.Current ||
this.Current != null &&
this.Current.Equals(other.Current)
) &&
(
this.RankYear == other.RankYear ||
this.RankYear != null &&
this.RankYear.Equals(other.RankYear)
) &&
(
this.StateRank == other.StateRank ||
this.StateRank != null &&
this.StateRank.Equals(other.StateRank)
) &&
(
this.NumberOfSchools == other.NumberOfSchools ||
this.NumberOfSchools != null &&
this.NumberOfSchools.Equals(other.NumberOfSchools)
) &&
(
this.AvgMathScore == other.AvgMathScore ||
this.AvgMathScore != null &&
this.AvgMathScore.Equals(other.AvgMathScore)
) &&
(
this.AvgReadingScore == other.AvgReadingScore ||
this.AvgReadingScore != null &&
this.AvgReadingScore.Equals(other.AvgReadingScore)
) &&
(
this.StatePercentileScore == other.StatePercentileScore ||
this.StatePercentileScore != null &&
this.StatePercentileScore.Equals(other.StatePercentileScore)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Current != null)
hash = hash * 59 + this.Current.GetHashCode();
if (this.RankYear != null)
hash = hash * 59 + this.RankYear.GetHashCode();
if (this.StateRank != null)
hash = hash * 59 + this.StateRank.GetHashCode();
if (this.NumberOfSchools != null)
hash = hash * 59 + this.NumberOfSchools.GetHashCode();
if (this.AvgMathScore != null)
hash = hash * 59 + this.AvgMathScore.GetHashCode();
if (this.AvgReadingScore != null)
hash = hash * 59 + this.AvgReadingScore.GetHashCode();
if (this.StatePercentileScore != null)
hash = hash * 59 + this.StatePercentileScore.GetHashCode();
return hash;
}
}
}
}
| |
//BSD, 2014-present, WinterDev
//MatterHackers
//----------------------------------------------------------------------------
// Anti-Grain Geometry - Version 2.4
// Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com)
//
// C# Port port by: Lars Brubaker
// [email protected]
// Copyright (C) 2007
//
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
//
//----------------------------------------------------------------------------
// Contact: [email protected]
// [email protected]
// http://www.antigrain.com
//----------------------------------------------------------------------------
#if true
using System;
using PixelFarm.Drawing;
using PixelFarm.CpuBlit.VertexProcessing;
using PixelFarm.CpuBlit.PixelProcessing;
namespace PixelFarm.CpuBlit.Rasterization.Lines
{
/*
//========================================================line_image_scale
public class line_image_scale
{
IImage m_source;
double m_height;
double m_scale;
public line_image_scale(IImage src, double height)
{
m_source = (src);
m_height = (height);
m_scale = (src.height() / height);
}
public double width() { return m_source.width(); }
public double height() { return m_height; }
public RGBA_Bytes pixel(int x, int y)
{
double src_y = (y + 0.5) * m_scale - 0.5;
int h = m_source.height() - 1;
int y1 = ufloor(src_y);
int y2 = y1 + 1;
RGBA_Bytes pix1 = (y1 < 0) ? new no_color() : m_source.pixel(x, y1);
RGBA_Bytes pix2 = (y2 > h) ? no_color() : m_source.pixel(x, y2);
return pix1.gradient(pix2, src_y - y1);
}
};
*/
//======================================================line_image_pattern
public class LineImagePattern
{
IPatternFilter _filter;
int _dilation;
int _dilation_hr;
SubBitmapBlender _buf;
TempMemPtr _data;
int _DataSizeInBytes = 0;
int _width;
int _height;
int _width_hr;
int _half_height_hr;
int _offset_y_hr;
//--------------------------------------------------------------------
public LineImagePattern(IPatternFilter filter)
{
_filter = filter;
_dilation = (filter.Dilation + 1);
_dilation_hr = (_dilation << LineAA.SUBPIXEL_SHIFT);
_width = (0);
_height = (0);
_width_hr = (0);
_half_height_hr = (0);
_offset_y_hr = (0);
}
public BitmapBlenderBase MyBuffer
{
get
{
throw new NotSupportedException();
}
}
~LineImagePattern()
{
//TODO: review here, remove finalizer
if (_DataSizeInBytes > 0)
{
_data.Dispose();
}
}
// Create
//--------------------------------------------------------------------
public LineImagePattern(IPatternFilter filter, LineImagePattern src)
{
_filter = (filter);
_dilation = (filter.Dilation + 1);
_dilation_hr = (_dilation << LineAA.SUBPIXEL_SHIFT);
_width = 0;
_height = 0;
_width_hr = 0;
_half_height_hr = 0;
_offset_y_hr = (0);
Create(src.MyBuffer);
}
// Create
//--------------------------------------------------------------------
public void Create(IBitmapSrc src)
{
// we are going to create a dialated image for filtering
// we add m_dilation pixels to every side of the image and then copy the image in the x
// dirrection into each end so that we can sample into this image to get filtering on x repeating
// if the original image look like this
//
// 123456
//
// the new image would look like this
//
// 0000000000
// 0000000000
// 5612345612
// 0000000000
// 0000000000
_height = (int)AggMath.uceil(src.Height);
_width = (int)AggMath.uceil(src.Width);
_width_hr = (int)AggMath.uround(src.Width * LineAA.SUBPIXEL_SCALE);
_half_height_hr = (int)AggMath.uround(src.Height * LineAA.SUBPIXEL_SCALE / 2);
_offset_y_hr = _dilation_hr + _half_height_hr - LineAA.SUBPIXEL_SCALE / 2;
_half_height_hr += LineAA.SUBPIXEL_SCALE / 2;
int bufferWidth = _width + _dilation * 2;
int bufferHeight = _height + _dilation * 2;
int bytesPerPixel = src.BitDepth / 8;
int newSizeInBytes = bufferWidth * bufferHeight * bytesPerPixel;
if (_DataSizeInBytes < newSizeInBytes)
{
_DataSizeInBytes = newSizeInBytes;
_data.Dispose();
IntPtr nativeBuff = System.Runtime.InteropServices.Marshal.AllocHGlobal(_DataSizeInBytes);
_data = new TempMemPtr(nativeBuff, _DataSizeInBytes);
}
_buf = new PixelProcessing.SubBitmapBlender(_data, 0, bufferWidth, bufferHeight, bufferWidth * bytesPerPixel, src.BitDepth, bytesPerPixel);
unsafe
{
using (TempMemPtr destMemPtr = _buf.GetBufferPtr())
using (TempMemPtr srcMemPtr = src.GetBufferPtr())
{
int* destBuffer = (int*)destMemPtr.Ptr;
int* srcBuffer = (int*)srcMemPtr.Ptr;
// copy the image into the middle of the dest
for (int y = 0; y < _height; y++)
{
for (int x = 0; x < _width; x++)
{
int sourceOffset = src.GetBufferOffsetXY32(x, y);
int destOffset = _buf.GetBufferOffsetXY32(_dilation, y + _dilation);
destBuffer[destOffset] = srcBuffer[sourceOffset];
}
}
// copy the first two pixels form the end into the begining and from the begining into the end
for (int y = 0; y < _height; y++)
{
int s1Offset = src.GetBufferOffsetXY32(0, y);
int d1Offset = _buf.GetBufferOffsetXY32(_dilation + _width, y);
int s2Offset = src.GetBufferOffsetXY32(_width - _dilation, y);
int d2Offset = _buf.GetBufferOffsetXY32(0, y);
for (int x = 0; x < _dilation; x++)
{
destBuffer[d1Offset++] = srcBuffer[s1Offset++];
destBuffer[d2Offset++] = srcBuffer[s2Offset++];
}
}
}
}
}
//--------------------------------------------------------------------
public int PatternWidth => _width_hr;
public int LineWidth => _half_height_hr;
public double Width => _height;
public IPatternFilter PatternFilter => _filter;
//--------------------------------------------------------------------
public void Pixel(Color[] destBuffer, int destBufferOffset, int x, int y)
{
_filter.SetPixelHighRes(_buf, destBuffer, destBufferOffset,
x % _width_hr + _dilation_hr,
y + _offset_y_hr);
}
}
/*
//=================================================line_image_pattern_pow2
public class line_image_pattern_pow2 :
line_image_pattern<IPatternFilter>
{
uint m_mask;
//--------------------------------------------------------------------
public line_image_pattern_pow2(IPatternFilter filter) :
line_image_pattern<IPatternFilter>(filter), m_mask(line_subpixel_mask) {}
//--------------------------------------------------------------------
public line_image_pattern_pow2(IPatternFilter filter, ImageBuffer src) :
line_image_pattern<IPatternFilter>(filter), m_mask(line_subpixel_mask)
{
create(src);
}
//--------------------------------------------------------------------
public void create(ImageBuffer src)
{
line_image_pattern<IPatternFilter>::create(src);
m_mask = 1;
while(m_mask < base_type::m_width)
{
m_mask <<= 1;
m_mask |= 1;
}
m_mask <<= line_subpixel_shift - 1;
m_mask |= line_subpixel_mask;
base_type::m_width_hr = m_mask + 1;
}
//--------------------------------------------------------------------
public void pixel(RGBA_Bytes* p, int x, int y)
{
base_type::m_filter->pixel_high_res(
base_type::m_buf.rows(),
p,
(x & m_mask) + base_type::m_dilation_hr,
y + base_type::m_offset_y_hr);
}
};
*/
//===================================================distance_interpolator4
#if true
#if false
//==================================================line_interpolator_image
public class line_interpolator_image
{
line_parameters m_lp;
dda2_line_interpolator m_li;
distance_interpolator4 m_di;
IImageByte m_ren;
int m_plen;
int m_x;
int m_y;
int m_old_x;
int m_old_y;
int m_width;
int m_max_extent;
int m_start;
int m_step;
int[] m_dist_pos = new int[max_half_width + 1];
RGBA_Bytes[] m_colors = new RGBA_Bytes[max_half_width * 2 + 4];
//---------------------------------------------------------------------
public const int max_half_width = 64;
//---------------------------------------------------------------------
public line_interpolator_image(renderer_outline_aa ren, line_parameters lp,
int sx, int sy, int ex, int ey,
int pattern_start,
double scale_x)
{
throw new NotImplementedException();
/*
m_lp=(lp);
m_li = new dda2_line_interpolator(lp.vertical ? LineAABasics.line_dbl_hr(lp.x2 - lp.x1) :
LineAABasics.line_dbl_hr(lp.y2 - lp.y1),
lp.vertical ? Math.Abs(lp.y2 - lp.y1) :
Math.Abs(lp.x2 - lp.x1) + 1);
m_di = new distance_interpolator4(lp.x1, lp.y1, lp.x2, lp.y2, sx, sy, ex, ey, lp.len, scale_x,
lp.x1 & ~LineAABasics.line_subpixel_mask, lp.y1 & ~LineAABasics.line_subpixel_mask);
m_ren=ren;
m_x = (lp.x1 >> LineAABasics.line_subpixel_shift);
m_y = (lp.y1 >> LineAABasics.line_subpixel_shift);
m_old_x=(m_x);
m_old_y=(m_y);
m_count = ((lp.vertical ? Math.Abs((lp.y2 >> LineAABasics.line_subpixel_shift) - m_y) :
Math.Abs((lp.x2 >> LineAABasics.line_subpixel_shift) - m_x)));
m_width=(ren.subpixel_width());
//m_max_extent(m_width >> (LineAABasics.line_subpixel_shift - 2));
m_max_extent = ((m_width + LineAABasics.line_subpixel_scale) >> LineAABasics.line_subpixel_shift);
m_start=(pattern_start + (m_max_extent + 2) * ren.pattern_width());
m_step=(0);
dda2_line_interpolator li = new dda2_line_interpolator(0, lp.vertical ?
(lp.dy << LineAABasics.line_subpixel_shift) :
(lp.dx << LineAABasics.line_subpixel_shift),
lp.len);
uint i;
int stop = m_width + LineAABasics.line_subpixel_scale * 2;
for(i = 0; i < max_half_width; ++i)
{
m_dist_pos[i] = li.y();
if(m_dist_pos[i] >= stop) break;
++li;
}
m_dist_pos[i] = 0x7FFF0000;
int dist1_start;
int dist2_start;
int npix = 1;
if(lp.vertical)
{
do
{
--m_li;
m_y -= lp.inc;
m_x = (m_lp.x1 + m_li.y()) >> LineAABasics.line_subpixel_shift;
if(lp.inc > 0) m_di.dec_y(m_x - m_old_x);
else m_di.inc_y(m_x - m_old_x);
m_old_x = m_x;
dist1_start = dist2_start = m_di.dist_start();
int dx = 0;
if(dist1_start < 0) ++npix;
do
{
dist1_start += m_di.dy_start();
dist2_start -= m_di.dy_start();
if(dist1_start < 0) ++npix;
if(dist2_start < 0) ++npix;
++dx;
}
while(m_dist_pos[dx] <= m_width);
if(npix == 0) break;
npix = 0;
}
while(--m_step >= -m_max_extent);
}
else
{
do
{
--m_li;
m_x -= lp.inc;
m_y = (m_lp.y1 + m_li.y()) >> LineAABasics.line_subpixel_shift;
if(lp.inc > 0) m_di.dec_x(m_y - m_old_y);
else m_di.inc_x(m_y - m_old_y);
m_old_y = m_y;
dist1_start = dist2_start = m_di.dist_start();
int dy = 0;
if(dist1_start < 0) ++npix;
do
{
dist1_start -= m_di.dx_start();
dist2_start += m_di.dx_start();
if(dist1_start < 0) ++npix;
if(dist2_start < 0) ++npix;
++dy;
}
while(m_dist_pos[dy] <= m_width);
if(npix == 0) break;
npix = 0;
}
while(--m_step >= -m_max_extent);
}
m_li.adjust_forward();
m_step -= m_max_extent;
*/
}
//---------------------------------------------------------------------
public bool step_hor()
{
throw new NotImplementedException();
/*
++m_li;
m_x += m_lp.inc;
m_y = (m_lp.y1 + m_li.y()) >> LineAABasics.line_subpixel_shift;
if(m_lp.inc > 0) m_di.inc_x(m_y - m_old_y);
else m_di.dec_x(m_y - m_old_y);
m_old_y = m_y;
int s1 = m_di.dist() / m_lp.len;
int s2 = -s1;
if(m_lp.inc < 0) s1 = -s1;
int dist_start;
int dist_pict;
int dist_end;
int dy;
int dist;
dist_start = m_di.dist_start();
dist_pict = m_di.dist_pict() + m_start;
dist_end = m_di.dist_end();
RGBA_Bytes* p0 = m_colors + max_half_width + 2;
RGBA_Bytes* p1 = p0;
int npix = 0;
p1->clear();
if(dist_end > 0)
{
if(dist_start <= 0)
{
m_ren.pixel(p1, dist_pict, s2);
}
++npix;
}
++p1;
dy = 1;
while((dist = m_dist_pos[dy]) - s1 <= m_width)
{
dist_start -= m_di.dx_start();
dist_pict -= m_di.dx_pict();
dist_end -= m_di.dx_end();
p1->clear();
if(dist_end > 0 && dist_start <= 0)
{
if(m_lp.inc > 0) dist = -dist;
m_ren.pixel(p1, dist_pict, s2 - dist);
++npix;
}
++p1;
++dy;
}
dy = 1;
dist_start = m_di.dist_start();
dist_pict = m_di.dist_pict() + m_start;
dist_end = m_di.dist_end();
while((dist = m_dist_pos[dy]) + s1 <= m_width)
{
dist_start += m_di.dx_start();
dist_pict += m_di.dx_pict();
dist_end += m_di.dx_end();
--p0;
p0->clear();
if(dist_end > 0 && dist_start <= 0)
{
if(m_lp.inc > 0) dist = -dist;
m_ren.pixel(p0, dist_pict, s2 + dist);
++npix;
}
++dy;
}
m_ren.blend_color_vspan(m_x,
m_y - dy + 1,
(uint)(p1 - p0),
p0);
return npix && ++m_step < m_count;
*/
}
//---------------------------------------------------------------------
public bool step_ver()
{
throw new NotImplementedException();
/*
++m_li;
m_y += m_lp.inc;
m_x = (m_lp.x1 + m_li.y()) >> LineAABasics.line_subpixel_shift;
if(m_lp.inc > 0) m_di.inc_y(m_x - m_old_x);
else m_di.dec_y(m_x - m_old_x);
m_old_x = m_x;
int s1 = m_di.dist() / m_lp.len;
int s2 = -s1;
if(m_lp.inc > 0) s1 = -s1;
int dist_start;
int dist_pict;
int dist_end;
int dist;
int dx;
dist_start = m_di.dist_start();
dist_pict = m_di.dist_pict() + m_start;
dist_end = m_di.dist_end();
RGBA_Bytes* p0 = m_colors + max_half_width + 2;
RGBA_Bytes* p1 = p0;
int npix = 0;
p1->clear();
if(dist_end > 0)
{
if(dist_start <= 0)
{
m_ren.pixel(p1, dist_pict, s2);
}
++npix;
}
++p1;
dx = 1;
while((dist = m_dist_pos[dx]) - s1 <= m_width)
{
dist_start += m_di.dy_start();
dist_pict += m_di.dy_pict();
dist_end += m_di.dy_end();
p1->clear();
if(dist_end > 0 && dist_start <= 0)
{
if(m_lp.inc > 0) dist = -dist;
m_ren.pixel(p1, dist_pict, s2 + dist);
++npix;
}
++p1;
++dx;
}
dx = 1;
dist_start = m_di.dist_start();
dist_pict = m_di.dist_pict() + m_start;
dist_end = m_di.dist_end();
while((dist = m_dist_pos[dx]) + s1 <= m_width)
{
dist_start -= m_di.dy_start();
dist_pict -= m_di.dy_pict();
dist_end -= m_di.dy_end();
--p0;
p0->clear();
if(dist_end > 0 && dist_start <= 0)
{
if(m_lp.inc > 0) dist = -dist;
m_ren.pixel(p0, dist_pict, s2 - dist);
++npix;
}
++dx;
}
m_ren.blend_color_hspan(m_x - dx + 1,
m_y,
(uint)(p1 - p0),
p0);
return npix && ++m_step < m_count;
*/
}
//---------------------------------------------------------------------
public int pattern_end() { return m_start + m_di.len(); }
//---------------------------------------------------------------------
public bool vertical() { return m_lp.vertical; }
public int width() { return m_width; }
}
#endif
//===================================================renderer_outline_image
//template<class BaseRenderer, class ImagePattern>
public class ImageLineRenderer : LineRenderer
{
PixelProcessing.IBitmapBlender _ren;
LineImagePattern _pattern;
int _start;
double _scale_x;
Q1Rect _clip_box;
bool _clipping;
//---------------------------------------------------------------------
//typedef renderer_outline_image<BaseRenderer, ImagePattern> self_type;
//---------------------------------------------------------------------
public ImageLineRenderer(PixelProcessing.IBitmapBlender ren, LineImagePattern patt)
{
_ren = ren;
_pattern = patt;
_start = (0);
_scale_x = (1.0);
_clip_box = new Q1Rect(0, 0, 0, 0);
_clipping = (false);
}
public void Attach(PixelProcessing.IBitmapBlender ren) { _ren = ren; }
//---------------------------------------------------------------------
public LineImagePattern Pattern
{
get => _pattern;
set => _pattern = value;
}
//---------------------------------------------------------------------
public void ResetClipping() => _clipping = false;
public void SetClipBox(double x1, double y1, double x2, double y2)
{
_clip_box = new Q1Rect(
LineCoordSat.Convert(x1), LineCoordSat.Convert(y1),
LineCoordSat.Convert(x2), LineCoordSat.Convert(y2)
);
_clipping = true;
}
//---------------------------------------------------------------------
public double ScaleX
{
get => _scale_x;
set => _scale_x = value;
}
public double StartX
{
get => (double)(_start) / LineAA.SUBPIXEL_SCALE;
set => _start = AggMath.iround(value * LineAA.SUBPIXEL_SCALE);
}
//---------------------------------------------------------------------
public int SubPixelWidth => _pattern.LineWidth;
public int PatternWidth => _pattern.PatternWidth;
public double Width => (double)(SubPixelWidth) / LineAA.SUBPIXEL_SCALE;
public void Pixel(Color[] p, int offset, int x, int y)
{
throw new NotImplementedException();
//m_pattern.pixel(p, x, y);
}
public void BlendColorHSpan(int x, int y, uint len, Color[] colors, int colorsOffset)
{
throw new NotImplementedException();
// m_ren.blend_color_hspan(x, y, len, colors, null, 0);
}
public void BlendColorVSpan(int x, int y, uint len, Color[] colors, int colorsOffset)
{
throw new NotImplementedException();
// m_ren.blend_color_vspan(x, y, len, colors, null, 0);
}
public static bool AccurateJoinOnly => true;
public override void SemiDot(CompareFunction cmp, int xc1, int yc1, int xc2, int yc2)
{
}
public override void SemiDotHLine(CompareFunction cmp,
int xc1, int yc1, int xc2, int yc2,
int x1, int y1, int x2)
{
}
public override void Pie(int xc, int yc, int x1, int y1, int x2, int y2)
{
}
public override void Line0(in LineParameters lp)
{
}
public override void Line1(in LineParameters lp, int sx, int sy)
{
}
public override void Line2(in LineParameters lp, int ex, int ey)
{
}
public void Line3NoClip(in LineParameters lp,
int sx, int sy, int ex, int ey)
{
throw new NotImplementedException();
/*
if(lp.len > LineAABasics.line_max_length)
{
line_parameters lp1, lp2;
lp.divide(lp1, lp2);
int mx = lp1.x2 + (lp1.y2 - lp1.y1);
int my = lp1.y2 - (lp1.x2 - lp1.x1);
line3_no_clip(lp1, (lp.x1 + sx) >> 1, (lp.y1 + sy) >> 1, mx, my);
line3_no_clip(lp2, mx, my, (lp.x2 + ex) >> 1, (lp.y2 + ey) >> 1);
return;
}
LineAABasics.fix_degenerate_bisectrix_start(lp, ref sx, ref sy);
LineAABasics.fix_degenerate_bisectrix_end(lp, ref ex, ref ey);
line_interpolator_image li = new line_interpolator_image(this, lp,
sx, sy,
ex, ey,
m_start, m_scale_x);
if(li.vertical())
{
while(li.step_ver());
}
else
{
while(li.step_hor());
}
m_start += uround(lp.len / m_scale_x);
*/
}
public override void Line3(in LineParameters lp,
int sx, int sy, int ex, int ey)
{
throw new NotImplementedException();
/*
if(m_clipping)
{
int x1 = lp.x1;
int y1 = lp.y1;
int x2 = lp.x2;
int y2 = lp.y2;
uint flags = clip_line_segment(&x1, &y1, &x2, &y2, m_clip_box);
int start = m_start;
if((flags & 4) == 0)
{
if(flags)
{
line_parameters lp2(x1, y1, x2, y2,
uround(calc_distance(x1, y1, x2, y2)));
if(flags & 1)
{
m_start += uround(calc_distance(lp.x1, lp.y1, x1, y1) / m_scale_x);
sx = x1 + (y2 - y1);
sy = y1 - (x2 - x1);
}
else
{
while(Math.Abs(sx - lp.x1) + Math.Abs(sy - lp.y1) > lp2.len)
{
sx = (lp.x1 + sx) >> 1;
sy = (lp.y1 + sy) >> 1;
}
}
if(flags & 2)
{
ex = x2 + (y2 - y1);
ey = y2 - (x2 - x1);
}
else
{
while(Math.Abs(ex - lp.x2) + Math.Abs(ey - lp.y2) > lp2.len)
{
ex = (lp.x2 + ex) >> 1;
ey = (lp.y2 + ey) >> 1;
}
}
line3_no_clip(lp2, sx, sy, ex, ey);
}
else
{
line3_no_clip(lp, sx, sy, ex, ey);
}
}
m_start = start + uround(lp.len / m_scale_x);
}
else
{
line3_no_clip(lp, sx, sy, ex, ey);
}
*/
}
}
#endif
}
#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 System.Xml;
using System.Collections.Generic;
using NPOI.SS.Util;
using System;
using NPOI.OpenXml4Net.OPC;
using System.IO;
using NPOI.OpenXmlFormats.Spreadsheet;
using NPOI.Util;
using System.Collections;
using NPOI.XSSF.UserModel.Helpers;
namespace NPOI.XSSF.UserModel
{
/**
*
* This class : the Table Part (Open Office XML Part 4:
* chapter 3.5.1)
*
* This implementation works under the assumption that a table Contains mappings to a subtree of an XML.
* The root element of this subtree an occur multiple times (one for each row of the table). The child nodes
* of the root element can be only attributes or element with maxOccurs=1 property set
*
*
* @author Roberto Manicardi
*/
public class XSSFTable : POIXMLDocumentPart
{
private CT_Table ctTable;
private List<XSSFXmlColumnPr> xmlColumnPr;
private CellReference startCellReference;
private CellReference endCellReference;
private String commonXPath;
public XSSFTable()
: base()
{
ctTable = new CT_Table();
}
internal XSSFTable(PackagePart part, PackageRelationship rel)
: base(part, rel)
{
XmlDocument xml = ConvertStreamToXml(part.GetInputStream());
ReadFrom(xml);
}
public void ReadFrom(XmlDocument xmlDoc)
{
try
{
TableDocument doc = TableDocument.Parse(xmlDoc, NamespaceManager);
ctTable = doc.GetTable();
}
catch (XmlException e)
{
throw new IOException(e.Message);
}
}
public XSSFSheet GetXSSFSheet()
{
return (XSSFSheet)GetParent();
}
public void WriteTo(Stream out1)
{
UpdateHeaders();
TableDocument doc = new TableDocument();
doc.SetTable(ctTable);
doc.Save(out1);
}
protected override void Commit()
{
PackagePart part = GetPackagePart();
Stream out1 = part.GetOutputStream();
WriteTo(out1);
out1.Close();
}
public CT_Table GetCTTable()
{
return ctTable;
}
/**
* Checks if this Table element Contains even a single mapping to the map identified by id
* @param id the XSSFMap ID
* @return true if the Table element contain mappings
*/
public bool MapsTo(long id)
{
bool maps = false;
List<XSSFXmlColumnPr> pointers = GetXmlColumnPrs();
foreach (XSSFXmlColumnPr pointer in pointers)
{
if (pointer.GetMapId() == id)
{
maps = true;
break;
}
}
return maps;
}
/**
*
* Calculates the xpath of the root element for the table. This will be the common part
* of all the mapping's xpaths
*
* @return the xpath of the table's root element
*/
public String GetCommonXpath()
{
if (commonXPath == null)
{
Array commonTokens = null;
foreach (CT_TableColumn column in ctTable.tableColumns.tableColumn)
{
if (column.xmlColumnPr != null)
{
String xpath = column.xmlColumnPr.xpath;
String[] tokens = xpath.Split(new char[] { '/' });
if (commonTokens==null)
{
commonTokens = tokens;
}
else
{
int maxLenght = commonTokens.Length > tokens.Length ? tokens.Length : commonTokens.Length;
for (int i = 0; i < maxLenght; i++)
{
if (!commonTokens.GetValue(i).Equals(tokens[i]))
{
ArrayList subCommonTokens = Arrays.AsList(commonTokens).GetRange(0, i);
commonTokens = subCommonTokens.ToArray(typeof(string));
break;
}
}
}
}
}
commonXPath = "";
for (int i = 1; i < commonTokens.Length; i++)
{
commonXPath += "/" + commonTokens.GetValue(i);
}
}
return commonXPath;
}
public List<XSSFXmlColumnPr> GetXmlColumnPrs()
{
if (xmlColumnPr == null)
{
xmlColumnPr = new List<XSSFXmlColumnPr>();
foreach (CT_TableColumn column in ctTable.tableColumns.tableColumn)
{
if (column.xmlColumnPr != null)
{
XSSFXmlColumnPr columnPr = new XSSFXmlColumnPr(this, column, column.xmlColumnPr);
xmlColumnPr.Add(columnPr);
}
}
}
return xmlColumnPr;
}
/**
* @return the name of the Table, if set
*/
public String Name
{
get
{
return ctTable.name;
}
set
{
ctTable.name = value;
}
}
/**
* @return the display name of the Table, if set
*/
public String DisplayName
{
get
{
return ctTable.displayName;
}
set
{
ctTable.displayName = value;
}
}
/**
* @return the number of mapped table columns (see Open Office XML Part 4: chapter 3.5.1.4)
*/
public long NumberOfMappedColumns
{
get
{
return ctTable.tableColumns.count;
}
}
/**
* @return The reference for the cell in the top-left part of the table
* (see Open Office XML Part 4: chapter 3.5.1.2, attribute ref)
*
*/
public CellReference GetStartCellReference()
{
if (startCellReference == null)
{
String ref1 = ctTable.@ref;
if(ref1 != null) {
String[] boundaries = ref1.Split(":".ToCharArray());
String from = boundaries[0];
startCellReference = new CellReference(from);
}
}
return startCellReference;
}
/**
* @return The reference for the cell in the bottom-right part of the table
* (see Open Office XML Part 4: chapter 3.5.1.2, attribute ref)
*
*/
public CellReference GetEndCellReference()
{
if (endCellReference == null)
{
String ref1 = ctTable.@ref;
String[] boundaries = ref1.Split(new char[] { ':' });
String from = boundaries[1];
endCellReference = new CellReference(from);
}
return endCellReference;
}
/**
* @return the total number of rows in the selection. (Note: in this version autofiltering is ignored)
*
*/
public int RowCount
{
get
{
CellReference from = GetStartCellReference();
CellReference to = GetEndCellReference();
int rowCount = -1;
if (from != null && to != null)
{
rowCount = to.Row - from.Row;
}
return rowCount;
}
}
/**
* Synchronize table headers with cell values in the parent sheet.
* Headers <em>must</em> be in sync, otherwise Excel will display a
* "Found unreadable content" message on startup.
*/
public void UpdateHeaders()
{
XSSFSheet sheet = (XSSFSheet)GetParent();
CellReference ref1 = GetStartCellReference() as CellReference;
if (ref1 == null) return;
int headerRow = ref1.Row;
int firstHeaderColumn = ref1.Col;
XSSFRow row = sheet.GetRow(headerRow) as XSSFRow;
if (row != null) foreach (CT_TableColumn col in GetCTTable().tableColumns.tableColumn)
{
int colIdx = (int)col.id - 1 + firstHeaderColumn;
XSSFCell cell = row.GetCell(colIdx) as XSSFCell;
if (cell != null)
{
col.name = (cell.StringCellValue);
}
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Newtonsoft.Json;
using RestSharp;
namespace DocDBAPIRest
{
/// <summary>
/// API client is mainly responible for making the HTTP call to the API backend.
/// </summary>
public class ApiClient
{
/// <summary>
/// Gets or sets the default API client for making HTTP calls.
/// </summary>
/// <value>The default API client.</value>
public static ApiClient Default = new ApiClient(Configuration.Default);
/// <summary>
/// Initializes a new instance of the <see cref="ApiClient" /> class
/// with default configuration and base path (https://databaseaccount.documents.azure.com:443/dbs).
/// </summary>
public ApiClient()
{
Configuration = Configuration.Default;
RestClient = new RestClient("https://databaseaccount.documents.azure.com:443/dbs");
}
/// <summary>
/// Initializes a new instance of the <see cref="ApiClient" /> class
/// with default base path (https://databaseaccount.documents.azure.com:443/dbs).
/// </summary>
/// <param name="config">An instance of Configuration.</param>
public ApiClient(Configuration config = null)
{
Configuration = config ?? Configuration.Default;
RestClient = new RestClient("https://databaseaccount.documents.azure.com:443/dbs");
}
/// <summary>
/// Initializes a new instance of the <see cref="ApiClient" /> class
/// with default configuration.
/// </summary>
/// <param name="basePath">The base path.</param>
public ApiClient(string basePath = "https://databaseaccount.documents.azure.com:443/dbs")
{
if (string.IsNullOrEmpty(basePath))
throw new ArgumentException("basePath cannot be empty");
RestClient = new RestClient(basePath);
Configuration = Configuration.Default;
}
/// <summary>
/// Gets or sets the Configuration.
/// </summary>
/// <value>An instance of the Configuration.</value>
public Configuration Configuration { get; set; }
/// <summary>
/// Gets or sets the RestClient.
/// </summary>
/// <value>An instance of the RestClient</value>
public RestClient RestClient { get; set; }
// Creates and sets up a RestRequest prior to a call.
private RestRequest PrepareRequest(
string path, Method method, Dictionary<string, string> queryParams, string postBody,
Dictionary<string, string> headerParams, Dictionary<string, string> formParams,
Dictionary<string, FileParameter> fileParams, Dictionary<string, string> pathParams)
{
var request = new RestRequest(path, method);
// add path parameter, if any
foreach (var param in pathParams)
request.AddParameter(param.Key, param.Value, ParameterType.UrlSegment);
// add header parameter, if any
foreach (var param in headerParams)
request.AddHeader(param.Key, param.Value);
// add query parameter, if any
foreach (var param in queryParams)
request.AddQueryParameter(param.Key, param.Value);
// add form parameter, if any
foreach (var param in formParams)
request.AddParameter(param.Key, param.Value);
// add file parameter, if any
foreach (var param in fileParams)
request.AddFile(param.Value.Name, param.Value.Writer, param.Value.FileName, param.Value.ContentType);
if (postBody != null) // http body (model) parameter
request.AddParameter("application/json", postBody, ParameterType.RequestBody);
return request;
}
/// <summary>
/// Makes the HTTP request (Sync).
/// </summary>
/// <param name="path">URL path.</param>
/// <param name="method">HTTP method.</param>
/// <param name="queryParams">Query parameters.</param>
/// <param name="postBody">HTTP body (POST request).</param>
/// <param name="headerParams">Header parameters.</param>
/// <param name="formParams">Form parameters.</param>
/// <param name="fileParams">File parameters.</param>
/// <param name="pathParams">Path parameters.</param>
/// <returns>Object</returns>
public object CallApi(
string path, Method method, Dictionary<string, string> queryParams, string postBody,
Dictionary<string, string> headerParams, Dictionary<string, string> formParams,
Dictionary<string, FileParameter> fileParams, Dictionary<string, string> pathParams)
{
var request = PrepareRequest(
path, method, queryParams, postBody, headerParams, formParams, fileParams, pathParams);
var response = RestClient.Execute(request);
return response;
}
/// <summary>
/// Makes the asynchronous HTTP request.
/// </summary>
/// <param name="path">URL path.</param>
/// <param name="method">HTTP method.</param>
/// <param name="queryParams">Query parameters.</param>
/// <param name="postBody">HTTP body (POST request).</param>
/// <param name="headerParams">Header parameters.</param>
/// <param name="formParams">Form parameters.</param>
/// <param name="fileParams">File parameters.</param>
/// <param name="pathParams">Path parameters.</param>
/// <returns>The Task instance.</returns>
public async Task<object> CallApiAsync(
string path, Method method, Dictionary<string, string> queryParams, string postBody,
Dictionary<string, string> headerParams, Dictionary<string, string> formParams,
Dictionary<string, FileParameter> fileParams, Dictionary<string, string> pathParams)
{
var request = PrepareRequest(
path, method, queryParams, postBody, headerParams, formParams, fileParams, pathParams);
var response = await RestClient.ExecuteTaskAsync(request);
return (object) response;
}
/// <summary>
/// Escape string (url-encoded).
/// </summary>
/// <param name="str">String to be escaped.</param>
/// <returns>Escaped string.</returns>
public string EscapeString(string str)
{
return UrlEncode(str);
}
/// <summary>
/// Create FileParameter based on Stream.
/// </summary>
/// <param name="name">Parameter name.</param>
/// <param name="stream">Input stream.</param>
/// <returns>FileParameter.</returns>
public FileParameter ParameterToFile(string name, Stream stream)
{
var fileStream = stream as FileStream;
return fileStream != null ? FileParameter.Create(name, ReadAsBytes(fileStream), Path.GetFileName(fileStream.Name)) : FileParameter.Create(name, ReadAsBytes(stream), "no_file_name_provided");
}
/// <summary>
/// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with
/// Configuration.DateTime.
/// If parameter is a list, join the list with ",".
/// Otherwise just return the string.
/// </summary>
/// <param name="obj">The parameter (header, path, query, form).</param>
/// <returns>Formatted string.</returns>
public string ParameterToString(object obj)
{
if (obj is DateTime)
// Return a formatted date string - Can be customized with Configuration.DateTimeFormat
// Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o")
// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8
// For example: 2009-06-15T13:45:30.0000000
return ((DateTime) obj).ToString(Configuration.DateTimeFormat);
var list = obj as IList;
if (list == null) return Convert.ToString(obj);
var flattenedString = new StringBuilder();
foreach (var param in list)
{
if (flattenedString.Length > 0)
flattenedString.Append(",");
flattenedString.Append(param);
}
return flattenedString.ToString();
}
/// <summary>
/// Deserialize the JSON string into a proper object.
/// </summary>
/// <param name="response">The HTTP response.</param>
/// <param name="type">Object type.</param>
/// <returns>Object representation of the JSON string.</returns>
public object Deserialize(IRestResponse response, Type type)
{
var data = response.RawBytes;
var content = response.Content;
var headers = response.Headers;
if (type == typeof (object)) // return an object
{
return content;
}
if (type == typeof (Stream))
{
if (headers != null)
{
var filePath = string.IsNullOrEmpty(Configuration.TempFolderPath)
? Path.GetTempPath()
: Configuration.TempFolderPath;
var regex = new Regex(@"Content-Disposition=.*filename=['""]?([^'""\s]+)['""]?$");
foreach (var header in headers)
{
var match = regex.Match(header.ToString());
if (match.Success)
{
var fileName = filePath + match.Groups[1].Value.Replace("\"", "").Replace("'", "");
File.WriteAllBytes(fileName, data);
return new FileStream(fileName, FileMode.Open);
}
}
}
var stream = new MemoryStream(data);
return stream;
}
if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object
{
return DateTime.Parse(content, null, DateTimeStyles.RoundtripKind);
}
if (type == typeof (string) || type.Name.StartsWith("System.Nullable")) // return primitive type
{
return ConvertType(content, type);
}
// at this point, it must be a model (json)
try
{
return JsonConvert.DeserializeObject(content, type);
}
catch (Exception e)
{
throw new ApiException(500, e.Message);
}
}
/// <summary>
/// Serialize an object into JSON string.
/// </summary>
/// <param name="obj">Object.</param>
/// <returns>JSON string.</returns>
public string Serialize(object obj)
{
try
{
return obj != null ? JsonConvert.SerializeObject(obj) : null;
}
catch (Exception e)
{
throw new ApiException(500, e.Message);
}
}
/// <summary>
/// Select the Accept header's value from the given accepts array:
/// if JSON exists in the given array, use it;
/// otherwise use all of them (joining into a string)
/// </summary>
/// <param name="accepts">The accepts array to select from.</param>
/// <returns>The Accept header to use.</returns>
public string SelectHeaderAccept(string[] accepts)
{
if (accepts.Length == 0)
return null;
return accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase) ? "application/json" : string.Join(",", accepts);
}
/// <summary>
/// Encode string in base64 format.
/// </summary>
/// <param name="text">String to be encoded.</param>
/// <returns>Encoded string.</returns>
public static string Base64Encode(string text)
{
return Convert.ToBase64String(Encoding.UTF8.GetBytes(text));
}
/// <summary>
/// Dynamically cast the object into target type.
/// Ref: http://stackoverflow.com/questions/4925718/c-dynamic-runtime-cast
/// </summary>
/// <param name="source">Object to be casted</param>
/// <param name="dest">Target type</param>
/// <returns>Casted object</returns>
public static dynamic ConvertType(dynamic source, Type dest)
{
return Convert.ChangeType(source, dest);
}
/// <summary>
/// Convert stream to byte array
/// Credit/Ref: http://stackoverflow.com/a/221941/677735
/// </summary>
/// <param name="input">Input stream to be converted</param>
/// <returns>Byte array</returns>
public static byte[] ReadAsBytes(Stream input)
{
var buffer = new byte[16*1024];
using (var ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
/// <summary>
/// URL encode a string
/// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50
/// </summary>
/// <param name="input">String to be URL encoded</param>
/// <returns>Byte array</returns>
public static string UrlEncode(string input)
{
const int maxLength = 32766;
if (input == null)
{
throw new ArgumentNullException(nameof(input));
}
if (input.Length <= maxLength)
{
return Uri.EscapeDataString(input);
}
var sb = new StringBuilder(input.Length*2);
var index = 0;
while (index < input.Length)
{
var length = Math.Min(input.Length - index, maxLength);
var subString = input.Substring(index, length);
sb.Append(Uri.EscapeDataString(subString));
index += subString.Length;
}
return sb.ToString();
}
}
}
| |
/*
* NPlot - A charting library for .NET
*
* SequenceAdapter.cs
* Copyright (C) 2003-2006 Matt Howlett and others.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Data;
using System.Text;
namespace NPlot
{
/// <summary>
/// This class is responsible for interpreting the various ways you can
/// specify data to plot objects using the DataSource, DataMember, ordinateData
/// and AbscissaData properties. It is a bridge that provides access to this
/// data via a single interface.
/// </summary>
public class SequenceAdapter
{
private readonly AdapterUtils.IAxisSuggester XAxisSuggester_;
private readonly AdapterUtils.IAxisSuggester YAxisSuggester_;
private readonly AdapterUtils.ICounter counter_;
private readonly AdapterUtils.IDataGetter xDataGetter_;
private readonly AdapterUtils.IDataGetter yDataGetter_;
/// <summary>
/// Constructor. The data source specifiers must be specified here.
/// </summary>
/// <param name="dataSource">The source containing a list of values to plot.</param>
/// <param name="dataMember">The specific data member in a multimember data source to get data from.</param>
/// <param name="ordinateData">The source containing a list of values to plot on the ordinate axis, or a the name of the column to use for this data.</param>
/// <param name="abscissaData">The source containing a list of values to plot on the abscissa axis, or a the name of the column to use for this data.</param>
public SequenceAdapter(object dataSource, string dataMember, object ordinateData, object abscissaData)
{
if (dataSource == null && dataMember == null)
{
if (ordinateData is IList)
{
YAxisSuggester_ = new AdapterUtils.AxisSuggester_IList((IList) ordinateData);
if (ordinateData is Double[])
yDataGetter_ = new AdapterUtils.DataGetter_DoublesArray((Double[]) ordinateData);
else
yDataGetter_ = new AdapterUtils.DataGetter_IList((IList) ordinateData);
counter_ = new AdapterUtils.Counter_IList((IList) ordinateData);
if (abscissaData is IList)
{
XAxisSuggester_ = new AdapterUtils.AxisSuggester_IList((IList) abscissaData);
if (abscissaData is Double[])
xDataGetter_ = new AdapterUtils.DataGetter_DoublesArray((Double[]) abscissaData);
else
xDataGetter_ = new AdapterUtils.DataGetter_IList((IList) abscissaData);
return;
}
else if (abscissaData is StartStep)
{
XAxisSuggester_ = new AdapterUtils.AxisSuggester_StartStep((StartStep) abscissaData, (IList) ordinateData);
xDataGetter_ = new AdapterUtils.DataGetter_StartStep((StartStep) abscissaData);
return;
}
else if (abscissaData == null)
{
XAxisSuggester_ = new AdapterUtils.AxisSuggester_Auto((IList) ordinateData);
xDataGetter_ = new AdapterUtils.DataGetter_Count();
return;
}
}
else if (ordinateData == null)
{
if (abscissaData == null)
{
XAxisSuggester_ = new AdapterUtils.AxisSuggester_Null();
YAxisSuggester_ = new AdapterUtils.AxisSuggester_Null();
counter_ = new AdapterUtils.Counter_Null();
xDataGetter_ = new AdapterUtils.DataGetter_Null();
yDataGetter_ = new AdapterUtils.DataGetter_Null();
return;
}
else if (abscissaData is IList)
{
XAxisSuggester_ = new AdapterUtils.AxisSuggester_IList((IList) abscissaData);
YAxisSuggester_ = new AdapterUtils.AxisSuggester_Auto((IList) abscissaData);
counter_ = new AdapterUtils.Counter_IList((IList) abscissaData);
if (abscissaData is Double[])
xDataGetter_ = new AdapterUtils.DataGetter_DoublesArray((Double[]) abscissaData);
else
xDataGetter_ = new AdapterUtils.DataGetter_IList((IList) abscissaData);
yDataGetter_ = new AdapterUtils.DataGetter_Count();
return;
}
else
{
// unknown.
}
}
else
{
// unknown
}
}
else if (dataSource is IList && dataMember == null)
{
if (dataSource is DataView)
{
DataView data = (DataView) dataSource;
counter_ = new AdapterUtils.Counter_DataView(data);
xDataGetter_ = new AdapterUtils.DataGetter_DataView(data, (string) abscissaData);
yDataGetter_ = new AdapterUtils.DataGetter_DataView(data, (string) ordinateData);
XAxisSuggester_ = new AdapterUtils.AxisSuggester_DataView(data, (string) abscissaData);
YAxisSuggester_ = new AdapterUtils.AxisSuggester_DataView(data, (string) ordinateData);
return;
}
else
{
YAxisSuggester_ = new AdapterUtils.AxisSuggester_IList((IList) dataSource);
counter_ = new AdapterUtils.Counter_IList((IList) dataSource);
yDataGetter_ = new AdapterUtils.DataGetter_IList((IList) dataSource);
if ((ordinateData == null) && (abscissaData == null))
{
XAxisSuggester_ = new AdapterUtils.AxisSuggester_Auto((IList) dataSource);
xDataGetter_ = new AdapterUtils.DataGetter_Count();
return;
}
else if ((ordinateData == null) && (abscissaData is StartStep))
{
XAxisSuggester_ = new AdapterUtils.AxisSuggester_StartStep((StartStep) abscissaData, (IList) ordinateData);
xDataGetter_ = new AdapterUtils.DataGetter_StartStep((StartStep) abscissaData);
return;
}
else if ((ordinateData == null) && (abscissaData is IList))
{
XAxisSuggester_ = new AdapterUtils.AxisSuggester_IList((IList) abscissaData);
xDataGetter_ = new AdapterUtils.DataGetter_IList((IList) abscissaData);
return;
}
else
{
// unknown.
}
}
}
else if (((dataSource is DataTable) && (dataMember == null)) || (dataSource is DataSet))
{
DataRowCollection rows = null;
if (dataSource is DataSet)
{
if (dataMember != null)
{
rows = (((DataSet) dataSource).Tables[dataMember]).Rows;
}
else
{
rows = (((DataSet) dataSource).Tables[0]).Rows;
}
}
else
{
rows = ((DataTable) dataSource).Rows;
}
yDataGetter_ = new AdapterUtils.DataGetter_Rows(rows, (string) ordinateData);
YAxisSuggester_ = new AdapterUtils.AxisSuggester_Rows(rows, (string) ordinateData);
counter_ = new AdapterUtils.Counter_Rows(rows);
if ((abscissaData is string) && (ordinateData is string))
{
XAxisSuggester_ = new AdapterUtils.AxisSuggester_Rows(rows, (string) abscissaData);
xDataGetter_ = new AdapterUtils.DataGetter_Rows(rows, (string) abscissaData);
return;
}
else if ((abscissaData == null) && (ordinateData is string))
{
XAxisSuggester_ = new AdapterUtils.AxisSuggester_RowAuto(rows);
xDataGetter_ = new AdapterUtils.DataGetter_Count();
return;
}
else
{
// unknown.
}
}
else
{
// unknown.
}
throw new NPlotException("Do not know how to interpret data provided to chart.");
}
/// <summary>
/// Returns the number of points.
/// </summary>
public int Count
{
get { return counter_.Count; }
}
/// <summary>
/// Returns the ith point.
/// </summary>
public PointD this[int i]
{
get { return new PointD(xDataGetter_.Get(i), yDataGetter_.Get(i)); }
}
/// <summary>
/// Returns an x-axis that is suitable for drawing the data.
/// </summary>
/// <returns>A suitable x-axis.</returns>
public Axis SuggestXAxis()
{
Axis a = XAxisSuggester_.Get();
// The world length should never be returned as 0
// This would result in an axis with a span of 0 units
// which can not be properly displayed.
if (a.WorldLength == 0.0)
{
// TODO make 0.08 a parameter.
a.IncreaseRange(0.08);
}
return a;
}
/// <summary>
/// Returns a y-axis that is suitable for drawing the data.
/// </summary>
/// <returns>A suitable y-axis.</returns>
public Axis SuggestYAxis()
{
Axis a = YAxisSuggester_.Get();
// TODO make 0.08 a parameter.
a.IncreaseRange(0.08);
return a;
}
/// <summary>
/// Writes data out as text.
/// </summary>
/// <param name="sb">StringBuilder to write to.</param>
/// <param name="region">Only write out data in this region if onlyInRegion is true.</param>
/// <param name="onlyInRegion">If true, only data in region is written, else all data is written.</param>
public void WriteData(StringBuilder sb, RectangleD region, bool onlyInRegion)
{
for (int i = 0; i < Count; ++i)
{
if (!(onlyInRegion &&
(this[i].X >= region.X && this[i].X <= region.X + region.Width) &&
(this[i].Y >= region.Y && this[i].Y <= region.Y + region.Height)))
continue;
sb.Append(this[i].ToString());
sb.Append("\r\n");
}
}
}
}
| |
// Copyright (c) Alexandre Mutel. All rights reserved.
// This file is licensed under the BSD-Clause 2 license.
// See the license.txt file in the project root for more information.
using Markdig.Helpers;
using Markdig.Parsers;
using Markdig.Syntax;
using Markdig.Syntax.Inlines;
namespace Markdig.Extensions.Footnotes
{
/// <summary>
/// The block parser for a <see cref="Footnote"/>.
/// </summary>
/// <seealso cref="Markdig.Parsers.BlockParser" />
public class FootnoteParser : BlockParser
{
/// <summary>
/// The key used to store at the document level the pending <see cref="FootnoteGroup"/>
/// </summary>
private static readonly object DocumentKey = typeof(Footnote);
public FootnoteParser()
{
OpeningCharacters = new [] {'['};
}
public override BlockState TryOpen(BlockProcessor processor)
{
return TryOpen(processor, false);
}
private BlockState TryOpen(BlockProcessor processor, bool isContinue)
{
// We expect footnote to appear only at document level and not indented more than a code indent block
if (processor.IsCodeIndent || (!isContinue && processor.CurrentContainer.GetType() != typeof(MarkdownDocument)) || (isContinue && !(processor.CurrentContainer is Footnote)))
{
return BlockState.None;
}
var saved = processor.Column;
string label;
int start = processor.Start;
SourceSpan labelSpan;
if (!LinkHelper.TryParseLabel(ref processor.Line, false, out label, out labelSpan) || !label.StartsWith("^") || processor.CurrentChar != ':')
{
processor.GoToColumn(saved);
return BlockState.None;
}
// Advance the column
int deltaColumn = processor.Start - start;
processor.Column = processor.Column + deltaColumn;
processor.NextChar(); // Skip ':'
var footnote = new Footnote(this)
{
Label = label,
LabelSpan = labelSpan,
};
// Maintain a list of all footnotes at document level
var footnotes = processor.Document.GetData(DocumentKey) as FootnoteGroup;
if (footnotes == null)
{
footnotes = new FootnoteGroup(this);
processor.Document.Add(footnotes);
processor.Document.SetData(DocumentKey, footnotes);
processor.Document.ProcessInlinesEnd += Document_ProcessInlinesEnd;
}
footnotes.Add(footnote);
var linkRef = new FootnoteLinkReferenceDefinition()
{
Footnote = footnote,
CreateLinkInline = CreateLinkToFootnote
};
processor.Document.SetLinkReferenceDefinition(footnote.Label, linkRef);
processor.NewBlocks.Push(footnote);
return BlockState.Continue;
}
public override BlockState TryContinue(BlockProcessor processor, Block block)
{
var footnote = (Footnote) block;
if (processor.CurrentBlock == null || processor.CurrentBlock.IsBreakable)
{
if (processor.IsBlankLine)
{
footnote.IsLastLineEmpty = true;
return BlockState.ContinueDiscard;
}
if (processor.Column == 0)
{
if (footnote.IsLastLineEmpty)
{
// Close the current footnote
processor.Close(footnote);
// Parse any opening footnote
return TryOpen(processor);
}
// Make sure that consecutive footnotes without a blanklines are parsed correctly
if (TryOpen(processor, true) == BlockState.Continue)
{
processor.Close(footnote);
return BlockState.Continue;
}
}
}
footnote.IsLastLineEmpty = false;
if (processor.IsCodeIndent)
{
processor.GoToCodeIndent();
}
return BlockState.Continue;
}
/// <summary>
/// Add footnotes to the end of the document
/// </summary>
/// <param name="state">The processor.</param>
/// <param name="inline">The inline.</param>
private void Document_ProcessInlinesEnd(InlineProcessor state, Inline inline)
{
// Unregister
state.Document.ProcessInlinesEnd -= Document_ProcessInlinesEnd;
var footnotes = ((FootnoteGroup)state.Document.GetData(DocumentKey));
// Remove the footnotes from the document and readd them at the end
state.Document.Remove(footnotes);
state.Document.Add(footnotes);
state.Document.RemoveData(DocumentKey);
footnotes.Sort(
(leftObj, rightObj) =>
{
var left = (Footnote)leftObj;
var right = (Footnote)rightObj;
return left.Order >= 0 && right.Order >= 0
? left.Order.CompareTo(right.Order)
: 0;
});
int linkIndex = 0;
for (int i = 0; i < footnotes.Count; i++)
{
var footnote = (Footnote)footnotes[i];
if (footnote.Order < 0)
{
// Remove this footnote if it doesn't have any links
footnotes.RemoveAt(i);
i--;
continue;
}
// Insert all footnote backlinks
var paragraphBlock = footnote.LastChild as ParagraphBlock;
if (paragraphBlock == null)
{
paragraphBlock = new ParagraphBlock();
footnote.Add(paragraphBlock);
}
if (paragraphBlock.Inline == null)
{
paragraphBlock.Inline = new ContainerInline();
}
foreach (var link in footnote.Links)
{
linkIndex++;
link.Index = linkIndex;
var backLink = new FootnoteLink()
{
Index = linkIndex,
IsBackLink = true,
Footnote = footnote
};
paragraphBlock.Inline.AppendChild(backLink);
}
}
}
private static Inline CreateLinkToFootnote(InlineProcessor state, LinkReferenceDefinition linkRef, Inline child)
{
var footnote = ((FootnoteLinkReferenceDefinition)linkRef).Footnote;
if (footnote.Order < 0)
{
var footnotes = (FootnoteGroup)state.Document.GetData(DocumentKey);
footnotes.CurrentOrder++;
footnote.Order = footnotes.CurrentOrder;
}
var link = new FootnoteLink() {Footnote = footnote};
footnote.Links.Add(link);
return link;
}
}
}
| |
// SF API version v50.0
// Custom fields included: False
// Relationship objects included: True
using System;
using NetCoreForce.Client.Models;
using NetCoreForce.Client.Attributes;
using Newtonsoft.Json;
namespace NetCoreForce.Models
{
///<summary>
/// Mobile Application Detail
///<para>SObject Name: MobileApplicationDetail</para>
///<para>Custom Object: False</para>
///</summary>
public class SfMobileApplicationDetail : SObject
{
[JsonIgnore]
public static string SObjectTypeName
{
get { return "MobileApplicationDetail"; }
}
///<summary>
/// Mobile Application Detail Id
/// <para>Name: Id</para>
/// <para>SF Type: id</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "id")]
[Updateable(false), Createable(false)]
public string Id { get; set; }
///<summary>
/// Deleted
/// <para>Name: IsDeleted</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isDeleted")]
[Updateable(false), Createable(false)]
public bool? IsDeleted { get; set; }
///<summary>
/// Name
/// <para>Name: DeveloperName</para>
/// <para>SF Type: string</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "developerName")]
public string DeveloperName { get; set; }
///<summary>
/// Master Language
/// <para>Name: Language</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "language")]
public string Language { get; set; }
///<summary>
/// Master Label
/// <para>Name: MasterLabel</para>
/// <para>SF Type: string</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "masterLabel")]
public string MasterLabel { get; set; }
///<summary>
/// Namespace Prefix
/// <para>Name: NamespacePrefix</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "namespacePrefix")]
[Updateable(false), Createable(false)]
public string NamespacePrefix { get; set; }
///<summary>
/// Created Date
/// <para>Name: CreatedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? CreatedDate { get; set; }
///<summary>
/// Created By ID
/// <para>Name: CreatedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdById")]
[Updateable(false), Createable(false)]
public string CreatedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: CreatedBy</para>
///</summary>
[JsonProperty(PropertyName = "createdBy")]
[Updateable(false), Createable(false)]
public SfUser CreatedBy { get; set; }
///<summary>
/// Last Modified Date
/// <para>Name: LastModifiedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? LastModifiedDate { get; set; }
///<summary>
/// Last Modified By ID
/// <para>Name: LastModifiedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedById")]
[Updateable(false), Createable(false)]
public string LastModifiedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: LastModifiedBy</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedBy")]
[Updateable(false), Createable(false)]
public SfUser LastModifiedBy { get; set; }
///<summary>
/// System Modstamp
/// <para>Name: SystemModstamp</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "systemModstamp")]
[Updateable(false), Createable(false)]
public DateTimeOffset? SystemModstamp { get; set; }
///<summary>
/// Version
/// <para>Name: Version</para>
/// <para>SF Type: string</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "version")]
public string Version { get; set; }
///<summary>
/// Device Platform
/// <para>Name: DevicePlatform</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "devicePlatform")]
public string DevicePlatform { get; set; }
///<summary>
/// Minimum OS Version
/// <para>Name: MinimumOsVersion</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "minimumOsVersion")]
public string MinimumOsVersion { get; set; }
///<summary>
/// Device Type
/// <para>Name: DeviceType</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "deviceType")]
public string DeviceType { get; set; }
///<summary>
/// Application File Length
/// <para>Name: ApplicationFileLength</para>
/// <para>SF Type: int</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "applicationFileLength")]
[Updateable(false), Createable(false)]
public int? ApplicationFileLength { get; set; }
///<summary>
/// Application Icon
/// <para>Name: ApplicationIcon</para>
/// <para>SF Type: textarea</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "applicationIcon")]
public string ApplicationIcon { get; set; }
///<summary>
/// Enterprise Application
/// <para>Name: IsEnterpriseApp</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isEnterpriseApp")]
public bool? IsEnterpriseApp { get; set; }
///<summary>
/// Installation URL
/// <para>Name: AppInstallUrl</para>
/// <para>SF Type: url</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "appInstallUrl")]
public string AppInstallUrl { get; set; }
///<summary>
/// Application Bundle Identifier
/// <para>Name: ApplicationBundleIdentifier</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "applicationBundleIdentifier")]
public string ApplicationBundleIdentifier { get; set; }
///<summary>
/// Application Binary File Name
/// <para>Name: ApplicationBinaryFileName</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "applicationBinaryFileName")]
public string ApplicationBinaryFileName { get; set; }
///<summary>
/// Application Icon File Name
/// <para>Name: ApplicationIconFileName</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "applicationIconFileName")]
public string ApplicationIconFileName { get; set; }
///<summary>
/// Application Binary
/// <para>Name: ApplicationBinary</para>
/// <para>SF Type: base64</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "applicationBinary")]
public string ApplicationBinary { get; set; }
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading;
namespace System
{
// Provides Unix-based support for System.Console.
//
// NOTE: The test class reflects over this class to run the tests due to limitations in
// the test infrastructure that prevent OS-specific builds of test binaries. If you
// change any of the class / struct / function names, parameters, etc then you need
// to also change the test class.
internal static class ConsolePal
{
public static Stream OpenStandardInput()
{
return new UnixConsoleStream(SafeFileHandle.Open(() => Interop.Sys.Dup(Interop.Sys.FileDescriptors.STDIN_FILENO)), FileAccess.Read);
}
public static Stream OpenStandardOutput()
{
return new UnixConsoleStream(SafeFileHandle.Open(() => Interop.Sys.Dup(Interop.Sys.FileDescriptors.STDOUT_FILENO)), FileAccess.Write);
}
public static Stream OpenStandardError()
{
return new UnixConsoleStream(SafeFileHandle.Open(() => Interop.Sys.Dup(Interop.Sys.FileDescriptors.STDERR_FILENO)), FileAccess.Write);
}
public static Encoding InputEncoding
{
get { return GetConsoleEncoding(); }
}
public static Encoding OutputEncoding
{
get { return GetConsoleEncoding(); }
}
private static SyncTextReader s_stdInReader;
private const int DefaultBufferSize = 255;
private static SyncTextReader StdInReader
{
get
{
EnsureInitialized();
return Volatile.Read(ref s_stdInReader) ??
Console.EnsureInitialized(
ref s_stdInReader,
() => SyncTextReader.GetSynchronizedTextReader(
new StdInStreamReader(
stream: OpenStandardInput(),
encoding: new ConsoleEncoding(Console.InputEncoding), // This ensures no prefix is written to the stream.
bufferSize: DefaultBufferSize)));
}
}
private const int DefaultConsoleBufferSize = 256; // default size of buffer used in stream readers/writers
internal static TextReader GetOrCreateReader()
{
if (Console.IsInputRedirected)
{
Stream inputStream = OpenStandardInput();
return SyncTextReader.GetSynchronizedTextReader(
inputStream == Stream.Null ?
StreamReader.Null :
new StreamReader(
stream: inputStream,
encoding: new ConsoleEncoding(Console.InputEncoding), // This ensures no prefix is written to the stream.
detectEncodingFromByteOrderMarks: false,
bufferSize: DefaultConsoleBufferSize,
leaveOpen: true)
);
}
else
{
return StdInReader;
}
}
public static bool KeyAvailable { get { return StdInReader.KeyAvailable; } }
public static ConsoleKeyInfo ReadKey(bool intercept)
{
if (Console.IsInputRedirected)
{
// We could leverage Console.Read() here however
// windows fails when stdin is redirected.
throw new InvalidOperationException(SR.InvalidOperation_ConsoleReadKeyOnFile);
}
bool previouslyProcessed;
ConsoleKeyInfo keyInfo = StdInReader.ReadKey(out previouslyProcessed);
if (!intercept && !previouslyProcessed) Console.Write(keyInfo.KeyChar);
return keyInfo;
}
private const ConsoleColor UnknownColor = (ConsoleColor)(-1);
private static ConsoleColor s_trackedForegroundColor = UnknownColor;
private static ConsoleColor s_trackedBackgroundColor = UnknownColor;
public static ConsoleColor ForegroundColor
{
get { return s_trackedForegroundColor; }
set { RefreshColors(ref s_trackedForegroundColor, value); }
}
public static ConsoleColor BackgroundColor
{
get { return s_trackedBackgroundColor; }
set { RefreshColors(ref s_trackedBackgroundColor, value); }
}
public static void ResetColor()
{
lock (Console.Out) // synchronize with other writers
{
s_trackedForegroundColor = UnknownColor;
s_trackedBackgroundColor = UnknownColor;
WriteResetColorString();
}
}
public static int CursorSize
{
get { return 100; }
set { throw new PlatformNotSupportedException(); }
}
public static string Title
{
get { throw new PlatformNotSupportedException(); }
set
{
if (Console.IsOutputRedirected)
return;
string titleFormat = TerminalFormatStrings.Instance.Title;
if (!string.IsNullOrEmpty(titleFormat))
{
string ansiStr = TermInfo.ParameterizedStrings.Evaluate(titleFormat, value);
WriteStdoutAnsiString(ansiStr);
}
}
}
public static void Beep()
{
if (!Console.IsOutputRedirected)
{
WriteStdoutAnsiString(TerminalFormatStrings.Instance.Bell);
}
}
public static void Beep(int frequency, int duration)
{
throw new PlatformNotSupportedException();
}
public static void Clear()
{
if (!Console.IsOutputRedirected)
{
WriteStdoutAnsiString(TerminalFormatStrings.Instance.Clear);
}
}
public static void SetCursorPosition(int left, int top)
{
if (Console.IsOutputRedirected)
return;
string cursorAddressFormat = TerminalFormatStrings.Instance.CursorAddress;
if (!string.IsNullOrEmpty(cursorAddressFormat))
{
string ansiStr = TermInfo.ParameterizedStrings.Evaluate(cursorAddressFormat, top, left);
WriteStdoutAnsiString(ansiStr);
}
}
public static int BufferWidth
{
get { return WindowWidth; }
set { throw new PlatformNotSupportedException(); }
}
public static int BufferHeight
{
get { return WindowHeight; }
set { throw new PlatformNotSupportedException(); }
}
public static void SetBufferSize(int width, int height)
{
throw new PlatformNotSupportedException();
}
public static int LargestWindowWidth
{
get { return WindowWidth; }
set { throw new PlatformNotSupportedException(); }
}
public static int LargestWindowHeight
{
get { return WindowHeight; }
set { throw new PlatformNotSupportedException(); }
}
public static int WindowLeft
{
get { return 0; }
set { throw new PlatformNotSupportedException(); }
}
public static int WindowTop
{
get { return 0; }
set { throw new PlatformNotSupportedException(); }
}
public static int WindowWidth
{
get
{
Interop.Sys.WinSize winsize;
return Interop.Sys.GetWindowSize(out winsize) == 0 ?
winsize.Col :
TerminalFormatStrings.Instance.Columns;
}
set { throw new PlatformNotSupportedException(); }
}
public static int WindowHeight
{
get
{
Interop.Sys.WinSize winsize;
return Interop.Sys.GetWindowSize(out winsize) == 0 ?
winsize.Row :
TerminalFormatStrings.Instance.Lines;
}
set { throw new PlatformNotSupportedException(); }
}
public static void SetWindowPosition(int left, int top)
{
throw new PlatformNotSupportedException();
}
public static void SetWindowSize(int width, int height)
{
throw new PlatformNotSupportedException();
}
public static bool CursorVisible
{
get { throw new PlatformNotSupportedException(); }
set
{
if (!Console.IsOutputRedirected)
{
WriteStdoutAnsiString(value ?
TerminalFormatStrings.Instance.CursorVisible :
TerminalFormatStrings.Instance.CursorInvisible);
}
}
}
// TODO: It's quite expensive to use the request/response protocol each time CursorLeft/Top is accessed.
// We should be able to (mostly) track the position of the cursor in locals, doing the request/response infrequently.
public static int CursorLeft
{
get
{
int left, top;
GetCursorPosition(out left, out top);
return left;
}
}
public static int CursorTop
{
get
{
int left, top;
GetCursorPosition(out left, out top);
return top;
}
}
/// <summary>Gets the current cursor position. This involves both writing to stdout and reading stdin.</summary>
private static unsafe void GetCursorPosition(out int left, out int top)
{
left = top = 0;
// Getting the cursor position involves both writing out a request string and
// parsing a response string from the terminal. So if anything is redirected, bail.
if (Console.IsInputRedirected || Console.IsOutputRedirected)
return;
// Get the cursor position request format string.
Debug.Assert(!string.IsNullOrEmpty(TerminalFormatStrings.CursorPositionReport));
// Synchronize with all other stdin readers. We need to do this in case multiple threads are
// trying to read/write concurrently, and to minimize the chances of resulting conflicts.
// This does mean that Console.get_CursorLeft/Top can't be used concurrently Console.Read*, etc.;
// attempting to do so will block one of them until the other completes, but in doing so we prevent
// one thread's get_CursorLeft/Top from providing input to the other's Console.Read*.
lock (StdInReader)
{
Interop.Sys.InitializeConsoleBeforeRead(minChars: 0, decisecondsTimeout: 10);
try
{
// Write out the cursor position report request.
WriteStdoutAnsiString(TerminalFormatStrings.CursorPositionReport);
// Read the response. There's a race condition here if the user is typing,
// or if other threads are accessing the console; there's relatively little
// we can do about that, but we try not to lose any data.
StdInStreamReader r = StdInReader.Inner;
const int BufferSize = 1024;
byte* bytes = stackalloc byte[BufferSize];
int bytesRead = 0, i = 0;
// Response expected in the form "\ESC[row;colR". However, user typing concurrently
// with the request/response sequence can result in other characters, and potentially
// other escape sequences (e.g. for an arrow key) being entered concurrently with
// the response. To avoid garbage showing up in the user's input, we are very liberal
// with regards to eating all input from this point until all aspects of the sequence
// have been consumed.
// Find the ESC as the start of the sequence.
if (!ReadStdinUntil(r, bytes, BufferSize, ref bytesRead, ref i, b => b == 0x1B)) return;
i++; // move past the ESC
// Find the '['
if (!ReadStdinUntil(r, bytes, BufferSize, ref bytesRead, ref i, b => b == '[')) return;
// Find the first Int32 and parse it.
if (!ReadStdinUntil(r, bytes, BufferSize, ref bytesRead, ref i, b => IsDigit((char)b))) return;
int row = ParseInt32(bytes, bytesRead, ref i);
if (row >= 1) top = row - 1;
// Find the second Int32 and parse it.
if (!ReadStdinUntil(r, bytes, BufferSize, ref bytesRead, ref i, b => IsDigit((char)b))) return;
int col = ParseInt32(bytes, bytesRead, ref i);
if (col >= 1) left = col - 1;
// Find the ending 'R'
if (!ReadStdinUntil(r, bytes, BufferSize, ref bytesRead, ref i, b => b == 'R')) return;
}
finally
{
Interop.Sys.UninitializeConsoleAfterRead();
}
}
}
public static void MoveBufferArea(int sourceLeft, int sourceTop, int sourceWidth, int sourceHeight, int targetLeft, int targetTop)
{
throw new PlatformNotSupportedException();
}
public static void MoveBufferArea(int sourceLeft, int sourceTop, int sourceWidth, int sourceHeight, int targetLeft, int targetTop, char sourceChar, ConsoleColor sourceForeColor, ConsoleColor sourceBackColor)
{
throw new PlatformNotSupportedException();
}
/// <summary>Reads from the stdin reader, unbuffered, until the specified condition is met.</summary>
/// <returns>true if the condition was met; otherwise, false.</returns>
private static unsafe bool ReadStdinUntil(
StdInStreamReader reader,
byte* buffer, int bufferSize,
ref int bytesRead, ref int pos,
Func<byte, bool> condition)
{
while (true)
{
for (; pos < bytesRead && !condition(buffer[pos]); pos++) ;
if (pos < bytesRead) return true;
bytesRead = reader.ReadStdin(buffer, bufferSize);
if (bytesRead == 0) return false;
pos = 0;
}
}
/// <summary>Parses the Int32 at the specified position in the buffer.</summary>
/// <param name="buffer">The buffer.</param>
/// <param name="bufferSize">The length of the buffer.</param>
/// <param name="pos">The current position in the buffer.</param>
/// <returns>The parsed result, or 0 if nothing could be parsed.</returns>
private static unsafe int ParseInt32(byte* buffer, int bufferSize, ref int pos)
{
int result = 0;
for (; pos < bufferSize; pos++)
{
char c = (char)buffer[pos];
if (!IsDigit(c)) break;
result = (result * 10) + (c - '0');
}
return result;
}
/// <summary>Gets whether the specified character is a digit 0-9.</summary>
private static bool IsDigit(char c) { return c >= '0' && c <= '9'; }
/// <summary>
/// Gets whether the specified file descriptor was redirected.
/// It's considered redirected if it doesn't refer to a terminal.
/// </summary>
private static bool IsHandleRedirected(SafeFileHandle fd)
{
return !Interop.Sys.IsATty(fd);
}
/// <summary>
/// Gets whether Console.In is redirected.
/// We approximate the behaviorby checking whether the underlying stream is our UnixConsoleStream and it's wrapping a character device.
/// </summary>
public static bool IsInputRedirectedCore()
{
return IsHandleRedirected(Interop.Sys.FileDescriptors.STDIN_FILENO);
}
/// <summary>Gets whether Console.Out is redirected.
/// We approximate the behaviorby checking whether the underlying stream is our UnixConsoleStream and it's wrapping a character device.
/// </summary>
public static bool IsOutputRedirectedCore()
{
return IsHandleRedirected(Interop.Sys.FileDescriptors.STDOUT_FILENO);
}
/// <summary>Gets whether Console.Error is redirected.
/// We approximate the behaviorby checking whether the underlying stream is our UnixConsoleStream and it's wrapping a character device.
/// </summary>
public static bool IsErrorRedirectedCore()
{
return IsHandleRedirected(Interop.Sys.FileDescriptors.STDERR_FILENO);
}
/// <summary>Creates an encoding from the current environment.</summary>
/// <returns>The encoding.</returns>
private static Encoding GetConsoleEncoding()
{
Encoding enc = EncodingHelper.GetEncodingFromCharset();
return enc ?? new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
}
public static void SetConsoleInputEncoding(Encoding enc)
{
// No-op.
// There is no good way to set the terminal console encoding.
}
public static void SetConsoleOutputEncoding(Encoding enc)
{
// No-op.
// There is no good way to set the terminal console encoding.
}
/// <summary>
/// Refreshes the foreground and background colors in use by the terminal by resetting
/// the colors and then reissuing commands for both foreground and background, if necessary.
/// Before doing so, the <paramref name="toChange"/> ref is changed to <paramref name="value"/>
/// if <paramref name="value"/> is valid.
/// </summary>
private static void RefreshColors(ref ConsoleColor toChange, ConsoleColor value)
{
if (((int)value & ~0xF) != 0 && value != UnknownColor)
{
throw new ArgumentException(SR.Arg_InvalidConsoleColor);
}
lock (Console.Out)
{
toChange = value; // toChange is either s_trackedForegroundColor or s_trackedBackgroundColor
WriteResetColorString();
if (s_trackedForegroundColor != UnknownColor)
{
WriteSetColorString(foreground: true, color: s_trackedForegroundColor);
}
if (s_trackedBackgroundColor != UnknownColor)
{
WriteSetColorString(foreground: false, color: s_trackedBackgroundColor);
}
}
}
/// <summary>Outputs the format string evaluated and parameterized with the color.</summary>
/// <param name="foreground">true for foreground; false for background.</param>
/// <param name="color">The color to store into the field and to use as an argument to the format string.</param>
private static void WriteSetColorString(bool foreground, ConsoleColor color)
{
// Changing the color involves writing an ANSI character sequence out to the output stream.
// We only want to do this if we know that sequence will be interpreted by the output.
// rather than simply displayed visibly.
if (Console.IsOutputRedirected)
return;
// See if we've already cached a format string for this foreground/background
// and specific color choice. If we have, just output that format string again.
int fgbgIndex = foreground ? 0 : 1;
int ccValue = (int)color;
string evaluatedString = s_fgbgAndColorStrings[fgbgIndex, ccValue]; // benign race
if (evaluatedString != null)
{
WriteStdoutAnsiString(evaluatedString);
return;
}
// We haven't yet computed a format string. Compute it, use it, then cache it.
string formatString = foreground ? TerminalFormatStrings.Instance.Foreground : TerminalFormatStrings.Instance.Background;
if (!string.IsNullOrEmpty(formatString))
{
int maxColors = TerminalFormatStrings.Instance.MaxColors; // often 8 or 16; 0 is invalid
if (maxColors > 0)
{
int ansiCode = _consoleColorToAnsiCode[ccValue] % maxColors;
evaluatedString = TermInfo.ParameterizedStrings.Evaluate(formatString, ansiCode);
WriteStdoutAnsiString(evaluatedString);
s_fgbgAndColorStrings[fgbgIndex, ccValue] = evaluatedString; // benign race
}
}
}
/// <summary>Writes out the ANSI string to reset colors.</summary>
private static void WriteResetColorString()
{
// We only want to send the reset string if we're targeting a TTY device
if (!Console.IsOutputRedirected)
{
WriteStdoutAnsiString(TerminalFormatStrings.Instance.Reset);
}
}
/// <summary>
/// The values of the ConsoleColor enums unfortunately don't map to the
/// corresponding ANSI values. We need to do the mapping manually.
/// See http://en.wikipedia.org/wiki/ANSI_escape_code#Colors
/// </summary>
private static readonly int[] _consoleColorToAnsiCode = new int[]
{
// Dark/Normal colors
0, // Black,
4, // DarkBlue,
2, // DarkGreen,
6, // DarkCyan,
1, // DarkRed,
5, // DarkMagenta,
3, // DarkYellow,
7, // Gray,
// Bright colors
8, // DarkGray,
12, // Blue,
10, // Green,
14, // Cyan,
9, // Red,
13, // Magenta,
11, // Yellow,
15 // White
};
/// <summary>Cache of the format strings for foreground/background and ConsoleColor.</summary>
private static readonly string[,] s_fgbgAndColorStrings = new string[2, 16]; // 2 == fg vs bg, 16 == ConsoleColor values
public static bool TryGetSpecialConsoleKey(char[] givenChars, int startIndex, int endIndex, out ConsoleKeyInfo key, out int keyLength)
{
int unprocessedCharCount = endIndex - startIndex;
// First process special control character codes. These override anything from terminfo.
if (unprocessedCharCount > 0)
{
// Is this an erase / backspace?
char c = givenChars[startIndex];
if (c != s_posixDisableValue && c == s_veraseCharacter)
{
key = new ConsoleKeyInfo(c, ConsoleKey.Backspace, shift: false, alt: false, control: false);
keyLength = 1;
return true;
}
}
// Then process terminfo mappings.
int minRange = TerminalFormatStrings.Instance.MinKeyFormatLength;
if (unprocessedCharCount >= minRange)
{
int maxRange = Math.Min(unprocessedCharCount, TerminalFormatStrings.Instance.MaxKeyFormatLength);
for (int i = maxRange; i >= minRange; i--)
{
var currentString = new StringOrCharArray(givenChars, startIndex, i);
// Check if the string prefix matches.
if (TerminalFormatStrings.Instance.KeyFormatToConsoleKey.TryGetValue(currentString, out key))
{
keyLength = currentString.Length;
return true;
}
}
}
// Otherwise, not a known special console key.
key = default(ConsoleKeyInfo);
keyLength = 0;
return false;
}
/// <summary>Whether keypad_xmit has already been written out to the terminal.</summary>
private static volatile bool s_initialized;
/// <summary>Value used to indicate that a special character code isn't available.</summary>
internal static byte s_posixDisableValue;
/// <summary>Special control character code used to represent an erase (backspace).</summary>
private static byte s_veraseCharacter;
/// <summary>Special control character that represents the end of a line.</summary>
internal static byte s_veolCharacter;
/// <summary>Special control character that represents the end of a line.</summary>
internal static byte s_veol2Character;
/// <summary>Special control character that represents the end of a file.</summary>
internal static byte s_veofCharacter;
/// <summary>Ensures that the console has been initialized for use.</summary>
private static void EnsureInitialized()
{
if (!s_initialized)
{
EnsureInitializedCore(); // factored out for inlinability
}
}
/// <summary>Ensures that the console has been initialized for use.</summary>
private static void EnsureInitializedCore()
{
lock (Console.Out) // ensure that writing the ANSI string and setting initialized to true are done atomically
{
if (!s_initialized)
{
// Ensure the console is configured appropriately. This will start
// signal handlers, etc.
if (!Interop.Sys.InitializeConsole())
{
throw Interop.GetExceptionForIoErrno(Interop.Sys.GetLastErrorInfo());
}
// Provide the native lib with the correct code from the terminfo to transition us into
// "application mode". This will both transition it immediately, as well as allow
// the native lib later to handle signals that require re-entering the mode.
if (!Console.IsOutputRedirected)
{
string keypadXmit = TerminalFormatStrings.Instance.KeypadXmit;
if (keypadXmit != null)
{
Interop.Sys.SetKeypadXmit(keypadXmit);
}
}
// Load special control character codes used for input processing
var controlCharacterNames = new Interop.Sys.ControlCharacterNames[4]
{
Interop.Sys.ControlCharacterNames.VERASE,
Interop.Sys.ControlCharacterNames.VEOL,
Interop.Sys.ControlCharacterNames.VEOL2,
Interop.Sys.ControlCharacterNames.VEOF
};
var controlCharacterValues = new byte[controlCharacterNames.Length];
Interop.Sys.GetControlCharacters(controlCharacterNames, controlCharacterValues, controlCharacterNames.Length, out s_posixDisableValue);
s_veraseCharacter = controlCharacterValues[0];
s_veolCharacter = controlCharacterValues[1];
s_veol2Character = controlCharacterValues[2];
s_veofCharacter = controlCharacterValues[3];
// Mark us as initialized
s_initialized = true;
}
}
}
/// <summary>Provides format strings and related information for use with the current terminal.</summary>
internal class TerminalFormatStrings
{
/// <summary>Gets the lazily-initialized terminal information for the terminal.</summary>
public static TerminalFormatStrings Instance { get { return s_instance.Value; } }
private static Lazy<TerminalFormatStrings> s_instance = new Lazy<TerminalFormatStrings>(() => new TerminalFormatStrings(TermInfo.Database.ReadActiveDatabase()));
/// <summary>The format string to use to change the foreground color.</summary>
public readonly string Foreground;
/// <summary>The format string to use to change the background color.</summary>
public readonly string Background;
/// <summary>The format string to use to reset the foreground and background colors.</summary>
public readonly string Reset;
/// <summary>The maximum number of colors supported by the terminal.</summary>
public readonly int MaxColors;
/// <summary>The number of columns in a format.</summary>
public readonly int Columns;
/// <summary>The number of lines in a format.</summary>
public readonly int Lines;
/// <summary>The format string to use to make cursor visible.</summary>
public readonly string CursorVisible;
/// <summary>The format string to use to make cursor invisible</summary>
public readonly string CursorInvisible;
/// <summary>The format string to use to set the window title.</summary>
public readonly string Title;
/// <summary>The format string to use for an audible bell.</summary>
public readonly string Bell;
/// <summary>The format string to use to clear the terminal.</summary>
public readonly string Clear;
/// <summary>The format string to use to set the position of the cursor.</summary>
public readonly string CursorAddress;
/// <summary>The format string to use to move the cursor to the left.</summary>
public readonly string CursorLeft;
/// <summary>The ANSI-compatible string for the Cursor Position report request.</summary>
/// <remarks>
/// This should really be in user string 7 in the terminfo file, but some terminfo databases
/// are missing it. As this is defined to be supported by any ANSI-compatible terminal,
/// we assume it's available; doing so means CursorTop/Left will work even if the terminfo database
/// doesn't contain it (as appears to be the case with e.g. screen and tmux on Ubuntu), at the risk
/// of outputting the sequence on some terminal that's not compatible.
/// </remarks>
public const string CursorPositionReport = "\x1B[6n";
/// <summary>
/// The dictionary of keystring to ConsoleKeyInfo.
/// Only some members of the ConsoleKeyInfo are used; in particular, the actual char is ignored.
/// </summary>
public Dictionary<StringOrCharArray, ConsoleKeyInfo> KeyFormatToConsoleKey;
/// <summary> Max key length </summary>
public int MaxKeyFormatLength;
/// <summary> Min key length </summary>
public int MinKeyFormatLength;
/// <summary>The ANSI string used to enter "application" / "keypad transmit" mode.</summary>
public string KeypadXmit;
public TerminalFormatStrings(TermInfo.Database db)
{
if (db == null)
return;
KeypadXmit = db.GetString(TermInfo.WellKnownStrings.KeypadXmit);
Foreground = db.GetString(TermInfo.WellKnownStrings.SetAnsiForeground);
Background = db.GetString(TermInfo.WellKnownStrings.SetAnsiBackground);
Reset = db.GetString(TermInfo.WellKnownStrings.OrigPairs) ?? db.GetString(TermInfo.WellKnownStrings.OrigColors);
Bell = db.GetString(TermInfo.WellKnownStrings.Bell);
Clear = db.GetString(TermInfo.WellKnownStrings.Clear);
Columns = db.GetNumber(TermInfo.WellKnownNumbers.Columns);
Lines = db.GetNumber(TermInfo.WellKnownNumbers.Lines);
CursorVisible = db.GetString(TermInfo.WellKnownStrings.CursorVisible);
CursorInvisible = db.GetString(TermInfo.WellKnownStrings.CursorInvisible);
CursorAddress = db.GetString(TermInfo.WellKnownStrings.CursorAddress);
CursorLeft = db.GetString(TermInfo.WellKnownStrings.CursorLeft);
Title = GetTitle(db);
Debug.WriteLineIf(db.GetString(TermInfo.WellKnownStrings.CursorPositionReport) != CursorPositionReport,
"Getting the cursor position will only work if the terminal supports the CPR sequence," +
"but the terminfo database does not contain an entry for it.");
int maxColors = db.GetNumber(TermInfo.WellKnownNumbers.MaxColors);
MaxColors = // normalize to either the full range of all ANSI colors, just the dark ones, or none
maxColors >= 16 ? 16 :
maxColors >= 8 ? 8 :
0;
KeyFormatToConsoleKey = new Dictionary<StringOrCharArray, ConsoleKeyInfo>();
AddKey(db, TermInfo.WellKnownStrings.KeyF1, ConsoleKey.F1);
AddKey(db, TermInfo.WellKnownStrings.KeyF2, ConsoleKey.F2);
AddKey(db, TermInfo.WellKnownStrings.KeyF3, ConsoleKey.F3);
AddKey(db, TermInfo.WellKnownStrings.KeyF4, ConsoleKey.F4);
AddKey(db, TermInfo.WellKnownStrings.KeyF5, ConsoleKey.F5);
AddKey(db, TermInfo.WellKnownStrings.KeyF6, ConsoleKey.F6);
AddKey(db, TermInfo.WellKnownStrings.KeyF7, ConsoleKey.F7);
AddKey(db, TermInfo.WellKnownStrings.KeyF8, ConsoleKey.F8);
AddKey(db, TermInfo.WellKnownStrings.KeyF9, ConsoleKey.F9);
AddKey(db, TermInfo.WellKnownStrings.KeyF10, ConsoleKey.F10);
AddKey(db, TermInfo.WellKnownStrings.KeyF11, ConsoleKey.F11);
AddKey(db, TermInfo.WellKnownStrings.KeyF12, ConsoleKey.F12);
AddKey(db, TermInfo.WellKnownStrings.KeyF13, ConsoleKey.F13);
AddKey(db, TermInfo.WellKnownStrings.KeyF14, ConsoleKey.F14);
AddKey(db, TermInfo.WellKnownStrings.KeyF15, ConsoleKey.F15);
AddKey(db, TermInfo.WellKnownStrings.KeyF16, ConsoleKey.F16);
AddKey(db, TermInfo.WellKnownStrings.KeyF17, ConsoleKey.F17);
AddKey(db, TermInfo.WellKnownStrings.KeyF18, ConsoleKey.F18);
AddKey(db, TermInfo.WellKnownStrings.KeyF19, ConsoleKey.F19);
AddKey(db, TermInfo.WellKnownStrings.KeyF20, ConsoleKey.F20);
AddKey(db, TermInfo.WellKnownStrings.KeyF21, ConsoleKey.F21);
AddKey(db, TermInfo.WellKnownStrings.KeyF22, ConsoleKey.F22);
AddKey(db, TermInfo.WellKnownStrings.KeyF23, ConsoleKey.F23);
AddKey(db, TermInfo.WellKnownStrings.KeyF24, ConsoleKey.F24);
AddKey(db, TermInfo.WellKnownStrings.KeyBackspace, ConsoleKey.Backspace);
AddKey(db, TermInfo.WellKnownStrings.KeyBackTab, ConsoleKey.Tab, shift: true, alt: false, control: false);
AddKey(db, TermInfo.WellKnownStrings.KeyBegin, ConsoleKey.Home);
AddKey(db, TermInfo.WellKnownStrings.KeyClear, ConsoleKey.Clear);
AddKey(db, TermInfo.WellKnownStrings.KeyDelete, ConsoleKey.Delete);
AddKey(db, TermInfo.WellKnownStrings.KeyDown, ConsoleKey.DownArrow);
AddKey(db, TermInfo.WellKnownStrings.KeyEnd, ConsoleKey.End);
AddKey(db, TermInfo.WellKnownStrings.KeyEnter, ConsoleKey.Enter);
AddKey(db, TermInfo.WellKnownStrings.KeyHelp, ConsoleKey.Help);
AddKey(db, TermInfo.WellKnownStrings.KeyHome, ConsoleKey.Home);
AddKey(db, TermInfo.WellKnownStrings.KeyInsert, ConsoleKey.Insert);
AddKey(db, TermInfo.WellKnownStrings.KeyLeft, ConsoleKey.LeftArrow);
AddKey(db, TermInfo.WellKnownStrings.KeyPageDown, ConsoleKey.PageDown);
AddKey(db, TermInfo.WellKnownStrings.KeyPageUp, ConsoleKey.PageUp);
AddKey(db, TermInfo.WellKnownStrings.KeyPrint, ConsoleKey.Print);
AddKey(db, TermInfo.WellKnownStrings.KeyRight, ConsoleKey.RightArrow);
AddKey(db, TermInfo.WellKnownStrings.KeyScrollForward, ConsoleKey.PageDown, shift: true, alt: false, control: false);
AddKey(db, TermInfo.WellKnownStrings.KeyScrollReverse, ConsoleKey.PageUp, shift: true, alt: false, control: false);
AddKey(db, TermInfo.WellKnownStrings.KeySBegin, ConsoleKey.Home, shift: true, alt: false, control: false);
AddKey(db, TermInfo.WellKnownStrings.KeySDelete, ConsoleKey.Delete, shift: true, alt: false, control: false);
AddKey(db, TermInfo.WellKnownStrings.KeySHome, ConsoleKey.Home, shift: true, alt: false, control: false);
AddKey(db, TermInfo.WellKnownStrings.KeySelect, ConsoleKey.Select);
AddKey(db, TermInfo.WellKnownStrings.KeySLeft, ConsoleKey.LeftArrow, shift: true, alt: false, control: false);
AddKey(db, TermInfo.WellKnownStrings.KeySPrint, ConsoleKey.Print, shift: true, alt: false, control: false);
AddKey(db, TermInfo.WellKnownStrings.KeySRight, ConsoleKey.RightArrow, shift: true, alt: false, control: false);
AddKey(db, TermInfo.WellKnownStrings.KeyUp, ConsoleKey.UpArrow);
AddPrefixKey(db, "kLFT", ConsoleKey.LeftArrow);
AddPrefixKey(db, "kRIT", ConsoleKey.RightArrow);
AddPrefixKey(db, "kUP", ConsoleKey.UpArrow);
AddPrefixKey(db, "kDN", ConsoleKey.DownArrow);
AddPrefixKey(db, "kDC", ConsoleKey.Delete);
AddPrefixKey(db, "kEND", ConsoleKey.End);
AddPrefixKey(db, "kHOM", ConsoleKey.Home);
AddPrefixKey(db, "kNXT", ConsoleKey.PageDown);
AddPrefixKey(db, "kPRV", ConsoleKey.PageUp);
if (KeyFormatToConsoleKey.Count > 0)
{
MaxKeyFormatLength = int.MinValue;
MinKeyFormatLength = int.MaxValue;
foreach (KeyValuePair<StringOrCharArray, ConsoleKeyInfo> entry in KeyFormatToConsoleKey)
{
if (entry.Key.Length > MaxKeyFormatLength)
{
MaxKeyFormatLength = entry.Key.Length;
}
if (entry.Key.Length < MinKeyFormatLength)
{
MinKeyFormatLength = entry.Key.Length;
}
}
}
}
private static string GetTitle(TermInfo.Database db)
{
// Try to get the format string from tsl/fsl and use it if they're available
string tsl = db.GetString(TermInfo.WellKnownStrings.ToStatusLine);
string fsl = db.GetString(TermInfo.WellKnownStrings.FromStatusLine);
if (tsl != null && fsl != null)
{
return tsl + "%p1%s" + fsl;
}
string term = db.Term;
if (term == null)
{
return string.Empty;
}
if (term.StartsWith("xterm", StringComparison.Ordinal)) // normalize all xterms to enable easier matching
{
term = "xterm";
}
switch (term)
{
case "aixterm":
case "dtterm":
case "linux":
case "rxvt":
case "xterm":
return "\x1B]0;%p1%s\x07";
case "cygwin":
return "\x1B];%p1%s\x07";
case "konsole":
return "\x1B]30;%p1%s\x07";
case "screen":
return "\x1Bk%p1%s\x1B";
default:
return string.Empty;
}
}
private void AddKey(TermInfo.Database db, TermInfo.WellKnownStrings keyId, ConsoleKey key)
{
AddKey(db, keyId, key, shift: false, alt: false, control: false);
}
private void AddKey(TermInfo.Database db, TermInfo.WellKnownStrings keyId, ConsoleKey key, bool shift, bool alt, bool control)
{
string keyFormat = db.GetString(keyId);
if (!string.IsNullOrEmpty(keyFormat))
KeyFormatToConsoleKey[keyFormat] = new ConsoleKeyInfo('\0', key, shift, alt, control);
}
private void AddPrefixKey(TermInfo.Database db, string extendedNamePrefix, ConsoleKey key)
{
AddKey(db, extendedNamePrefix + "3", key, shift: false, alt: true, control: false);
AddKey(db, extendedNamePrefix + "4", key, shift: true, alt: true, control: false);
AddKey(db, extendedNamePrefix + "5", key, shift: false, alt: false, control: true);
AddKey(db, extendedNamePrefix + "6", key, shift: true, alt: false, control: true);
AddKey(db, extendedNamePrefix + "7", key, shift: false, alt: false, control: true);
}
private void AddKey(TermInfo.Database db, string extendedName, ConsoleKey key, bool shift, bool alt, bool control)
{
string keyFormat = db.GetExtendedString(extendedName);
if (!string.IsNullOrEmpty(keyFormat))
KeyFormatToConsoleKey[keyFormat] = new ConsoleKeyInfo('\0', key, shift, alt, control);
}
}
/// <summary>Reads data from the file descriptor into the buffer.</summary>
/// <param name="fd">The file descriptor.</param>
/// <param name="buffer">The buffer to read into.</param>
/// <param name="offset">The offset at which to start writing into the buffer.</param>
/// <param name="count">The maximum number of bytes to read.</param>
/// <returns>The number of bytes read, or a negative value if there's an error.</returns>
internal static unsafe int Read(SafeFileHandle fd, byte[] buffer, int offset, int count)
{
fixed (byte* bufPtr = buffer)
{
int result = Interop.CheckIo(Interop.Sys.Read(fd, (byte*)bufPtr + offset, count));
Debug.Assert(result <= count);
return result;
}
}
/// <summary>Writes data from the buffer into the file descriptor.</summary>
/// <param name="fd">The file descriptor.</param>
/// <param name="buffer">The buffer from which to write data.</param>
/// <param name="offset">The offset at which the data to write starts in the buffer.</param>
/// <param name="count">The number of bytes to write.</param>
private static unsafe void Write(SafeFileHandle fd, byte[] buffer, int offset, int count)
{
fixed (byte* bufPtr = buffer)
{
Write(fd, bufPtr + offset, count);
}
}
private static unsafe void Write(SafeFileHandle fd, byte* bufPtr, int count)
{
while (count > 0)
{
int bytesWritten = Interop.Sys.Write(fd, bufPtr, count);
if (bytesWritten < 0)
{
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
if (errorInfo.Error == Interop.Error.EPIPE)
{
// Broken pipe... likely due to being redirected to a program
// that ended, so simply pretend we were successful.
return;
}
else
{
// Something else... fail.
throw Interop.GetExceptionForIoErrno(errorInfo);
}
}
count -= bytesWritten;
bufPtr += bytesWritten;
}
}
/// <summary>Writes a terminfo-based ANSI escape string to stdout.</summary>
/// <param name="value">The string to write.</param>
private static unsafe void WriteStdoutAnsiString(string value)
{
if (string.IsNullOrEmpty(value))
return;
// Except for extremely rare cases, ANSI escape strings should be very short.
const int StackAllocThreshold = 256;
if (value.Length <= StackAllocThreshold)
{
int dataLen = Encoding.UTF8.GetMaxByteCount(value.Length);
byte* data = stackalloc byte[dataLen];
fixed (char* chars = value)
{
int bytesToWrite = Encoding.UTF8.GetBytes(chars, value.Length, data, dataLen);
Debug.Assert(bytesToWrite <= dataLen);
lock (Console.Out) // synchronize with other writers
{
Write(Interop.Sys.FileDescriptors.STDOUT_FILENO, data, bytesToWrite);
}
}
}
else
{
byte[] data = Encoding.UTF8.GetBytes(value);
lock (Console.Out) // synchronize with other writers
{
Write(Interop.Sys.FileDescriptors.STDOUT_FILENO, data, 0, data.Length);
}
}
}
/// <summary>Provides a stream to use for Unix console input or output.</summary>
private sealed class UnixConsoleStream : ConsoleStream
{
/// <summary>The file descriptor for the opened file.</summary>
private readonly SafeFileHandle _handle;
/// <summary>The type of the underlying file descriptor.</summary>
internal readonly int _handleType;
/// <summary>Initialize the stream.</summary>
/// <param name="handle">The file handle wrapped by this stream.</param>
/// <param name="access">FileAccess.Read or FileAccess.Write.</param>
internal UnixConsoleStream(SafeFileHandle handle, FileAccess access)
: base(access)
{
Debug.Assert(handle != null, "Expected non-null console handle");
Debug.Assert(!handle.IsInvalid, "Expected valid console handle");
_handle = handle;
// Determine the type of the descriptor (e.g. regular file, character file, pipe, etc.)
Interop.Sys.FileStatus buf;
_handleType =
Interop.Sys.FStat(_handle, out buf) == 0 ?
(buf.Mode & Interop.Sys.FileTypes.S_IFMT) :
Interop.Sys.FileTypes.S_IFREG; // if something goes wrong, don't fail, just say it's a regular file
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_handle.Dispose();
}
base.Dispose(disposing);
}
public override int Read(byte[] buffer, int offset, int count)
{
ValidateRead(buffer, offset, count);
return ConsolePal.Read(_handle, buffer, offset, count);
}
public override void Write(byte[] buffer, int offset, int count)
{
ValidateWrite(buffer, offset, count);
ConsolePal.Write(_handle, buffer, offset, count);
}
public override void Flush()
{
if (_handle.IsClosed)
{
throw Error.GetFileNotOpen();
}
base.Flush();
}
}
internal sealed class ControlCHandlerRegistrar
{
private static readonly Interop.Sys.CtrlCallback _handler =
c => Console.HandleBreakEvent(c == Interop.Sys.CtrlCode.Break ? ConsoleSpecialKey.ControlBreak : ConsoleSpecialKey.ControlC);
private bool _handlerRegistered;
internal void Register()
{
EnsureInitialized();
Debug.Assert(!_handlerRegistered);
Interop.Sys.RegisterForCtrl(_handler);
_handlerRegistered = true;
}
internal void Unregister()
{
Debug.Assert(_handlerRegistered);
_handlerRegistered = false;
Interop.Sys.UnregisterForCtrl();
}
}
}
}
| |
using System.Collections.Generic;
using System.Linq;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Collections.Generic;
public static class CecilExtensions
{
public static void Replace(this Collection<Instruction> collection, Instruction instruction, ICollection<Instruction> instructions)
{
var newInstruction = instructions.First();
instruction.Operand = newInstruction.Operand;
instruction.OpCode = newInstruction.OpCode;
var indexOf = collection.IndexOf(instruction);
foreach (var instruction1 in instructions.Skip(1))
{
collection.Insert(indexOf+1, instruction1);
indexOf++;
}
}
public static void Append(this List<Instruction> collection, params Instruction[] instructions)
{
collection.AddRange(instructions);
}
public static string DisplayName(this MethodDefinition method)
{
method = GetActualMethod(method);
var paramNames = string.Join(", ", method.Parameters.Select(x => x.ParameterType.DisplayName()));
return $"{method.ReturnType.DisplayName()} {method.Name}({paramNames})";
}
public static string DisplayName(this TypeReference typeReference)
{
var genericInstanceType = typeReference as GenericInstanceType;
if (genericInstanceType != null && genericInstanceType.HasGenericArguments)
{
return typeReference.Name.Split('`').First() + "<" + string.Join(", ", genericInstanceType.GenericArguments.Select(c => c.DisplayName())) + ">";
}
return typeReference.Name;
}
static MethodDefinition GetActualMethod(MethodDefinition method)
{
var isTypeCompilerGenerated = method.DeclaringType.IsCompilerGenerated();
if (isTypeCompilerGenerated)
{
var rootType = method.DeclaringType.GetNonCompilerGeneratedType();
if (rootType != null)
{
foreach (var parentClassMethod in rootType.Methods)
{
if (method.DeclaringType.Name.Contains("<" + parentClassMethod.Name + ">"))
{
return parentClassMethod;
}
if (method.Name.StartsWith("<" + parentClassMethod.Name + ">"))
{
return parentClassMethod;
}
}
}
}
var isMethodCompilerGenerated = method.IsCompilerGenerated();
if (isMethodCompilerGenerated)
{
foreach (var parentClassMethod in method.DeclaringType.Methods)
{
if (method.Name.StartsWith("<" + parentClassMethod.Name + ">"))
{
return parentClassMethod;
}
}
}
return method;
}
public static TypeDefinition GetNonCompilerGeneratedType(this TypeDefinition typeDefinition)
{
while (typeDefinition.IsCompilerGenerated() && typeDefinition.DeclaringType != null)
{
typeDefinition = typeDefinition.DeclaringType;
}
return typeDefinition;
}
public static bool IsCompilerGenerated(this ICustomAttributeProvider value)
{
return value.CustomAttributes.Any(a => a.AttributeType.Name == "CompilerGeneratedAttribute");
}
public static bool IsCompilerGenerated(this TypeDefinition typeDefinition)
{
return typeDefinition.CustomAttributes.Any(a => a.AttributeType.Name == "CompilerGeneratedAttribute") ||
(typeDefinition.IsNested && typeDefinition.DeclaringType.IsCompilerGenerated());
}
public static void CheckForInvalidLogToUsages(this MethodDefinition methodDefinition)
{
foreach (var instruction in methodDefinition.Body.Instructions)
{
var methodReference = instruction.Operand as MethodReference;
if (methodReference != null)
{
var declaringType = methodReference.DeclaringType;
if (declaringType.Name != "LogTo")
{
continue;
}
if (declaringType.Namespace == null || !declaringType.Namespace.StartsWith("Anotar"))
{
continue;
}
//TODO: sequence point
if (instruction.OpCode == OpCodes.Ldftn)
{
var message = $"Inline delegate usages of 'LogTo' are not supported. '{methodDefinition.FullName}'.";
throw new WeavingException(message);
}
}
var typeReference = instruction.Operand as TypeReference;
if (typeReference != null)
{
if (typeReference.Name != "LogTo")
{
continue;
}
if (typeReference.Namespace == null || !typeReference.Namespace.StartsWith("Anotar"))
{
continue;
}
//TODO: sequence point
if (instruction.OpCode == OpCodes.Ldtoken)
{
var message = $"'typeof' usages or passing `dynamic' params to 'LogTo' are not supported. '{methodDefinition.FullName}'.";
throw new WeavingException(message);
}
}
}
}
public static MethodDefinition GetStaticConstructor(this TypeDefinition type)
{
var staticConstructor = type.Methods.FirstOrDefault(x => x.IsConstructor && x.IsStatic);
if (staticConstructor == null)
{
const MethodAttributes attributes = MethodAttributes.Static
| MethodAttributes.SpecialName
| MethodAttributes.RTSpecialName
| MethodAttributes.HideBySig
| MethodAttributes.Private;
staticConstructor = new MethodDefinition(".cctor", attributes, type.Module.TypeSystem.Void);
staticConstructor.Body.Instructions.Add(Instruction.Create(OpCodes.Ret));
type.Methods.Add(staticConstructor);
}
staticConstructor.Body.InitLocals = true;
return staticConstructor;
}
public static void InsertBefore(this ILProcessor processor, Instruction target, IEnumerable<Instruction> instructions)
{
foreach (var instruction in instructions)
{
processor.InsertBefore(target, instruction);
}
}
public static bool IsBasicLogCall(this Instruction instruction)
{
var previous = instruction.Previous;
if (previous.OpCode != OpCodes.Newarr || ((TypeReference) previous.Operand).FullName != "System.Object")
{
return false;
}
previous = previous.Previous;
if (previous.OpCode != OpCodes.Ldc_I4)
{
return false;
}
previous = previous.Previous;
if (previous.OpCode != OpCodes.Ldstr)
{
return false;
}
return true;
}
public static Instruction FindStringInstruction(this Instruction call)
{
if (IsBasicLogCall(call))
{
return call.Previous.Previous.Previous;
}
var previous = call.Previous;
if (previous.OpCode != OpCodes.Ldloc)
{
return null;
}
var variable = (VariableDefinition) previous.Operand;
while (previous != null && (previous.OpCode != OpCodes.Stloc || previous.Operand != variable))
{
previous = previous.Previous;
}
if (previous == null)
{
return null;
}
if (IsBasicLogCall(previous))
{
return previous.Previous.Previous.Previous;
}
return null;
}
public static bool TryGetPreviousLineNumber(this Instruction instruction, MethodDefinition method, out int lineNumber)
{
while (true)
{
var sequencePoint = method.DebugInformation.GetSequencePoint(instruction);
if (sequencePoint != null)
{
// not a hidden line http://blogs.msdn.com/b/jmstall/archive/2005/06/19/feefee-sequencepoints.aspx
if (sequencePoint.StartLine != 0xFeeFee)
{
lineNumber = sequencePoint.StartLine;
return true;
}
}
instruction = instruction.Previous;
if (instruction == null)
{
lineNumber = 0;
return false;
}
}
}
public static bool ContainsAttribute(this Collection<CustomAttribute> attributes, string attributeName)
{
var containsAttribute = attributes.FirstOrDefault(x => x.AttributeType.FullName == attributeName);
if (containsAttribute != null)
{
attributes.Remove(containsAttribute);
}
return containsAttribute != null;
}
public static MethodDefinition FindMethod(this TypeDefinition typeDefinition, string method, params string[] paramTypes)
{
var firstOrDefault = typeDefinition.Methods
.FirstOrDefault(x =>
!x.HasGenericParameters &&
x.Name == method &&
x.IsMatch(paramTypes));
if (firstOrDefault == null)
{
var parameterNames = string.Join(", ", paramTypes);
throw new WeavingException($"Expected to find method '{method}({parameterNames})' on type '{typeDefinition.FullName}'.");
}
return firstOrDefault;
}
public static MethodDefinition FindGenericMethod(this TypeDefinition typeDefinition, string method, params string[] paramTypes)
{
var firstOrDefault = typeDefinition.Methods
.FirstOrDefault(x =>
x.HasGenericParameters &&
x.Name == method &&
x.IsMatch(paramTypes));
if (firstOrDefault == null)
{
var parameterNames = string.Join(", ", paramTypes);
throw new WeavingException($"Expected to find method '{method}({parameterNames})' on type '{typeDefinition.FullName}'.");
}
return firstOrDefault;
}
public static bool IsMatch(this MethodReference methodReference, params string[] paramTypes)
{
if (methodReference.Parameters.Count != paramTypes.Length)
{
return false;
}
for (var index = 0; index < methodReference.Parameters.Count; index++)
{
var parameterDefinition = methodReference.Parameters[index];
var paramType = paramTypes[index];
if (parameterDefinition.ParameterType.Name != paramType)
{
return false;
}
}
return true;
}
public static FieldReference GetGeneric(this FieldDefinition definition)
{
if (definition.DeclaringType.HasGenericParameters)
{
var declaringType = new GenericInstanceType(definition.DeclaringType);
foreach (var parameter in definition.DeclaringType.GenericParameters)
{
declaringType.GenericArguments.Add(parameter);
}
return new FieldReference(definition.Name, definition.FieldType, declaringType);
}
return definition;
}
public static TypeReference GetGeneric(this TypeDefinition definition)
{
if (definition.HasGenericParameters)
{
var genericInstanceType = new GenericInstanceType(definition);
foreach (var parameter in definition.GenericParameters)
{
genericInstanceType.GenericArguments.Add(parameter);
}
return genericInstanceType;
}
return definition;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Reflection.Metadata.Ecma335
{
public static class CodedIndex
{
private static int ToCodedIndex(this int rowId, HasCustomAttribute tag) => (rowId << (int)HasCustomAttribute.__bits) | (int)tag;
private static int ToCodedIndex(this int rowId, HasConstant tag) => (rowId << (int)HasConstant.__bits) | (int)tag;
private static int ToCodedIndex(this int rowId, CustomAttributeType tag) => (rowId << (int)CustomAttributeType.__bits) | (int)tag;
private static int ToCodedIndex(this int rowId, HasDeclSecurity tag) => (rowId << (int)HasDeclSecurity.__bits) | (int)tag;
private static int ToCodedIndex(this int rowId, HasFieldMarshal tag) => (rowId << (int)HasFieldMarshal.__bits) | (int)tag;
private static int ToCodedIndex(this int rowId, HasSemantics tag) => (rowId << (int)HasSemantics.__bits) | (int)tag;
private static int ToCodedIndex(this int rowId, Implementation tag) => (rowId << (int)Implementation.__bits) | (int)tag;
private static int ToCodedIndex(this int rowId, MemberForwarded tag) => (rowId << (int)MemberForwarded.__bits) | (int)tag;
private static int ToCodedIndex(this int rowId, MemberRefParent tag) => (rowId << (int)MemberRefParent.__bits) | (int)tag;
private static int ToCodedIndex(this int rowId, MethodDefOrRef tag) => (rowId << (int)MethodDefOrRef.__bits) | (int)tag;
private static int ToCodedIndex(this int rowId, ResolutionScope tag) => (rowId << (int)ResolutionScope.__bits) | (int)tag;
private static int ToCodedIndex(this int rowId, TypeDefOrRefOrSpec tag) => (rowId << (int)TypeDefOrRefOrSpec.__bits) | (int)tag;
private static int ToCodedIndex(this int rowId, TypeOrMethodDef tag) => (rowId << (int)TypeOrMethodDef.__bits) | (int)tag;
private static int ToCodedIndex(this int rowId, HasCustomDebugInformation tag) => (rowId << (int)HasCustomDebugInformation.__bits) | (int)tag;
public static int ToHasCustomAttribute(EntityHandle handle) => MetadataTokens.GetRowNumber(handle).ToCodedIndex(ToHasCustomAttributeTag(handle.Kind));
public static int ToHasConstant(EntityHandle handle) => MetadataTokens.GetRowNumber(handle).ToCodedIndex(ToHasConstantTag(handle.Kind));
public static int ToCustomAttributeType(EntityHandle handle) => MetadataTokens.GetRowNumber(handle).ToCodedIndex(ToCustomAttributeTypeTag(handle.Kind));
public static int ToHasDeclSecurity(EntityHandle handle) => MetadataTokens.GetRowNumber(handle).ToCodedIndex(ToHasDeclSecurityTag(handle.Kind));
public static int ToHasFieldMarshal(EntityHandle handle) => MetadataTokens.GetRowNumber(handle).ToCodedIndex(ToHasFieldMarshalTag(handle.Kind));
public static int ToHasSemantics(EntityHandle handle) => MetadataTokens.GetRowNumber(handle).ToCodedIndex(ToHasSemanticsTag(handle.Kind));
public static int ToImplementation(EntityHandle handle) => MetadataTokens.GetRowNumber(handle).ToCodedIndex(ToImplementationTag(handle.Kind));
public static int ToMemberForwarded(EntityHandle handle) => MetadataTokens.GetRowNumber(handle).ToCodedIndex(ToMemberForwardedTag(handle.Kind));
public static int ToMemberRefParent(EntityHandle handle) => MetadataTokens.GetRowNumber(handle).ToCodedIndex(ToMemberRefParentTag(handle.Kind));
public static int ToMethodDefOrRef(EntityHandle handle) => MetadataTokens.GetRowNumber(handle).ToCodedIndex(ToMethodDefOrRefTag(handle.Kind));
public static int ToResolutionScope(EntityHandle handle) => MetadataTokens.GetRowNumber(handle).ToCodedIndex(ToResolutionScopeTag(handle.Kind));
public static int ToTypeDefOrRef(EntityHandle handle) => MetadataTokens.GetRowNumber(handle).ToCodedIndex(ToTypeDefOrRefTag(handle.Kind));
public static int ToTypeDefOrRefOrSpec(EntityHandle handle) => MetadataTokens.GetRowNumber(handle).ToCodedIndex(ToTypeDefOrRefOrSpecTag(handle.Kind));
public static int ToTypeOrMethodDef(EntityHandle handle) => MetadataTokens.GetRowNumber(handle).ToCodedIndex(ToTypeOrMethodDefTag(handle.Kind));
public static int ToHasCustomDebugInformation(EntityHandle handle) => MetadataTokens.GetRowNumber(handle).ToCodedIndex(ToHasCustomDebugInformationTag(handle.Kind));
private enum HasCustomAttribute
{
MethodDef = 0,
Field = 1,
TypeRef = 2,
TypeDef = 3,
Param = 4,
InterfaceImpl = 5,
MemberRef = 6,
Module = 7,
DeclSecurity = 8,
Property = 9,
Event = 10,
StandAloneSig = 11,
ModuleRef = 12,
TypeSpec = 13,
Assembly = 14,
AssemblyRef = 15,
File = 16,
ExportedType = 17,
ManifestResource = 18,
GenericParam = 19,
GenericParamConstraint = 20,
MethodSpec = 21,
__bits = 5
}
private static Exception UnexpectedHandleKind(HandleKind kind)
{
return new ArgumentException(SR.Format(SR.UnexpectedHandleKind, kind));
}
private static HasCustomAttribute ToHasCustomAttributeTag(HandleKind kind)
{
switch (kind)
{
case HandleKind.MethodDefinition: return HasCustomAttribute.MethodDef;
case HandleKind.FieldDefinition: return HasCustomAttribute.Field;
case HandleKind.TypeReference: return HasCustomAttribute.TypeRef;
case HandleKind.TypeDefinition: return HasCustomAttribute.TypeDef;
case HandleKind.Parameter: return HasCustomAttribute.Param;
case HandleKind.InterfaceImplementation: return HasCustomAttribute.InterfaceImpl;
case HandleKind.MemberReference: return HasCustomAttribute.MemberRef;
case HandleKind.ModuleDefinition: return HasCustomAttribute.Module;
case HandleKind.DeclarativeSecurityAttribute: return HasCustomAttribute.DeclSecurity;
case HandleKind.PropertyDefinition: return HasCustomAttribute.Property;
case HandleKind.EventDefinition: return HasCustomAttribute.Event;
case HandleKind.StandaloneSignature: return HasCustomAttribute.StandAloneSig;
case HandleKind.ModuleReference: return HasCustomAttribute.ModuleRef;
case HandleKind.TypeSpecification: return HasCustomAttribute.TypeSpec;
case HandleKind.AssemblyDefinition: return HasCustomAttribute.Assembly;
case HandleKind.AssemblyReference: return HasCustomAttribute.AssemblyRef;
case HandleKind.AssemblyFile: return HasCustomAttribute.File;
case HandleKind.ExportedType: return HasCustomAttribute.ExportedType;
case HandleKind.ManifestResource: return HasCustomAttribute.ManifestResource;
case HandleKind.GenericParameter: return HasCustomAttribute.GenericParam;
case HandleKind.GenericParameterConstraint: return HasCustomAttribute.GenericParamConstraint;
case HandleKind.MethodSpecification: return HasCustomAttribute.MethodSpec;
default:
throw UnexpectedHandleKind(kind);
}
}
private enum HasConstant
{
Field = 0,
Param = 1,
Property = 2,
__bits = 2,
__mask = (1 << __bits) - 1
}
private static HasConstant ToHasConstantTag(HandleKind kind)
{
switch (kind)
{
case HandleKind.FieldDefinition: return HasConstant.Field;
case HandleKind.Parameter: return HasConstant.Param;
case HandleKind.PropertyDefinition: return HasConstant.Property;
default:
throw UnexpectedHandleKind(kind);
}
}
private enum CustomAttributeType
{
MethodDef = 2,
MemberRef = 3,
__bits = 3
}
private static CustomAttributeType ToCustomAttributeTypeTag(HandleKind kind)
{
switch (kind)
{
case HandleKind.MethodDefinition: return CustomAttributeType.MethodDef;
case HandleKind.MemberReference: return CustomAttributeType.MemberRef;
default:
throw UnexpectedHandleKind(kind);
}
}
private enum HasDeclSecurity
{
TypeDef = 0,
MethodDef = 1,
Assembly = 2,
__bits = 2,
__mask = (1 << __bits) - 1
}
private static HasDeclSecurity ToHasDeclSecurityTag(HandleKind kind)
{
switch (kind)
{
case HandleKind.TypeDefinition: return HasDeclSecurity.TypeDef;
case HandleKind.MethodDefinition: return HasDeclSecurity.MethodDef;
case HandleKind.AssemblyDefinition: return HasDeclSecurity.Assembly;
default:
throw UnexpectedHandleKind(kind);
}
}
private enum HasFieldMarshal
{
Field = 0,
Param = 1,
__bits = 1,
__mask = (1 << __bits) - 1
}
private static HasFieldMarshal ToHasFieldMarshalTag(HandleKind kind)
{
switch (kind)
{
case HandleKind.FieldDefinition: return HasFieldMarshal.Field;
case HandleKind.Parameter: return HasFieldMarshal.Param;
default:
throw UnexpectedHandleKind(kind);
}
}
private enum HasSemantics
{
Event = 0,
Property = 1,
__bits = 1
}
private static HasSemantics ToHasSemanticsTag(HandleKind kind)
{
switch (kind)
{
case HandleKind.EventDefinition: return HasSemantics.Event;
case HandleKind.PropertyDefinition: return HasSemantics.Property;
default:
throw UnexpectedHandleKind(kind);
}
}
private enum Implementation
{
File = 0,
AssemblyRef = 1,
ExportedType = 2,
__bits = 2
}
private static Implementation ToImplementationTag(HandleKind kind)
{
switch (kind)
{
case HandleKind.AssemblyFile: return Implementation.File;
case HandleKind.AssemblyReference: return Implementation.AssemblyRef;
case HandleKind.ExportedType: return Implementation.ExportedType;
default:
throw UnexpectedHandleKind(kind);
}
}
private enum MemberForwarded
{
Field = 0,
MethodDef = 1,
__bits = 1
}
private static MemberForwarded ToMemberForwardedTag(HandleKind kind)
{
switch (kind)
{
case HandleKind.FieldDefinition: return MemberForwarded.Field;
case HandleKind.MethodDefinition: return MemberForwarded.MethodDef;
default:
throw UnexpectedHandleKind(kind);
}
}
private enum MemberRefParent
{
TypeDef = 0,
TypeRef = 1,
ModuleRef = 2,
MethodDef = 3,
TypeSpec = 4,
__bits = 3
}
private static MemberRefParent ToMemberRefParentTag(HandleKind kind)
{
switch (kind)
{
case HandleKind.TypeDefinition: return MemberRefParent.TypeDef;
case HandleKind.TypeReference: return MemberRefParent.TypeRef;
case HandleKind.ModuleReference: return MemberRefParent.ModuleRef;
case HandleKind.MethodDefinition: return MemberRefParent.MethodDef;
case HandleKind.TypeSpecification: return MemberRefParent.TypeSpec;
default:
throw UnexpectedHandleKind(kind);
}
}
private enum MethodDefOrRef
{
MethodDef = 0,
MemberRef = 1,
__bits = 1
}
private static MethodDefOrRef ToMethodDefOrRefTag(HandleKind kind)
{
switch (kind)
{
case HandleKind.MethodDefinition: return MethodDefOrRef.MethodDef;
case HandleKind.MemberReference: return MethodDefOrRef.MemberRef;
default:
throw UnexpectedHandleKind(kind);
}
}
private enum ResolutionScope
{
Module = 0,
ModuleRef = 1,
AssemblyRef = 2,
TypeRef = 3,
__bits = 2
}
private static ResolutionScope ToResolutionScopeTag(HandleKind kind)
{
switch (kind)
{
case HandleKind.ModuleDefinition: return ResolutionScope.Module;
case HandleKind.ModuleReference: return ResolutionScope.ModuleRef;
case HandleKind.AssemblyReference: return ResolutionScope.AssemblyRef;
case HandleKind.TypeReference: return ResolutionScope.TypeRef;
default:
throw UnexpectedHandleKind(kind);
}
}
private enum TypeDefOrRefOrSpec
{
TypeDef = 0,
TypeRef = 1,
TypeSpec = 2,
__bits = 2
}
private static TypeDefOrRefOrSpec ToTypeDefOrRefOrSpecTag(HandleKind kind)
{
switch (kind)
{
case HandleKind.TypeDefinition: return TypeDefOrRefOrSpec.TypeDef;
case HandleKind.TypeReference: return TypeDefOrRefOrSpec.TypeRef;
case HandleKind.TypeSpecification: return TypeDefOrRefOrSpec.TypeSpec;
default:
throw UnexpectedHandleKind(kind);
}
}
private static TypeDefOrRefOrSpec ToTypeDefOrRefTag(HandleKind kind)
{
switch (kind)
{
case HandleKind.TypeDefinition: return TypeDefOrRefOrSpec.TypeDef;
case HandleKind.TypeReference: return TypeDefOrRefOrSpec.TypeRef;
default:
throw UnexpectedHandleKind(kind);
}
}
private enum TypeOrMethodDef
{
TypeDef = 0,
MethodDef = 1,
__bits = 1
}
private static TypeOrMethodDef ToTypeOrMethodDefTag(HandleKind kind)
{
switch (kind)
{
case HandleKind.TypeDefinition: return TypeOrMethodDef.TypeDef;
case HandleKind.MethodDefinition: return TypeOrMethodDef.MethodDef;
default:
throw UnexpectedHandleKind(kind);
}
}
private enum HasCustomDebugInformation
{
MethodDef = 0,
Field = 1,
TypeRef = 2,
TypeDef = 3,
Param = 4,
InterfaceImpl = 5,
MemberRef = 6,
Module = 7,
DeclSecurity = 8,
Property = 9,
Event = 10,
StandAloneSig = 11,
ModuleRef = 12,
TypeSpec = 13,
Assembly = 14,
AssemblyRef = 15,
File = 16,
ExportedType = 17,
ManifestResource = 18,
GenericParam = 19,
GenericParamConstraint = 20,
MethodSpec = 21,
Document = 22,
LocalScope = 23,
LocalVariable = 24,
LocalConstant = 25,
ImportScope = 26,
__bits = 5
}
private static HasCustomDebugInformation ToHasCustomDebugInformationTag(HandleKind kind)
{
switch (kind)
{
case HandleKind.MethodDefinition: return HasCustomDebugInformation.MethodDef;
case HandleKind.FieldDefinition: return HasCustomDebugInformation.Field;
case HandleKind.TypeReference: return HasCustomDebugInformation.TypeRef;
case HandleKind.TypeDefinition: return HasCustomDebugInformation.TypeDef;
case HandleKind.Parameter: return HasCustomDebugInformation.Param;
case HandleKind.InterfaceImplementation: return HasCustomDebugInformation.InterfaceImpl;
case HandleKind.MemberReference: return HasCustomDebugInformation.MemberRef;
case HandleKind.ModuleDefinition: return HasCustomDebugInformation.Module;
case HandleKind.DeclarativeSecurityAttribute: return HasCustomDebugInformation.DeclSecurity;
case HandleKind.PropertyDefinition: return HasCustomDebugInformation.Property;
case HandleKind.EventDefinition: return HasCustomDebugInformation.Event;
case HandleKind.StandaloneSignature: return HasCustomDebugInformation.StandAloneSig;
case HandleKind.ModuleReference: return HasCustomDebugInformation.ModuleRef;
case HandleKind.TypeSpecification: return HasCustomDebugInformation.TypeSpec;
case HandleKind.AssemblyDefinition: return HasCustomDebugInformation.Assembly;
case HandleKind.AssemblyReference: return HasCustomDebugInformation.AssemblyRef;
case HandleKind.AssemblyFile: return HasCustomDebugInformation.File;
case HandleKind.ExportedType: return HasCustomDebugInformation.ExportedType;
case HandleKind.ManifestResource: return HasCustomDebugInformation.ManifestResource;
case HandleKind.GenericParameter: return HasCustomDebugInformation.GenericParam;
case HandleKind.GenericParameterConstraint: return HasCustomDebugInformation.GenericParamConstraint;
case HandleKind.MethodSpecification: return HasCustomDebugInformation.MethodSpec;
case HandleKind.Document: return HasCustomDebugInformation.Document;
case HandleKind.LocalScope: return HasCustomDebugInformation.LocalScope;
case HandleKind.LocalVariable: return HasCustomDebugInformation.LocalVariable;
case HandleKind.LocalConstant: return HasCustomDebugInformation.LocalConstant;
case HandleKind.ImportScope: return HasCustomDebugInformation.ImportScope;
default:
throw UnexpectedHandleKind(kind);
}
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="SnacFamily04Tests.cs" company="Jan-Cornelius Molnar">
// The MIT License (MIT)
//
// Copyright (c) 2015 Jan-Cornelius Molnar
//
// 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 Jcq.IcqProtocol.DataTypes;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Jcq.IcqProtocol.Tests
{
[TestClass]
public class SnacFamily04Tests
{
//[TestMethod]
//public void Snac0401DeserializeTest()
//{
// var data = new byte[]
// {
// 0x2A, 0x02, 0xEF, 0xD9, 0x00, 0x0C, 0x00, 0x04, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x14,
// 0x00, 0x0E
// };
// var f = SerializationTools.DeserializeFlap(data);
// var s = SerializationTools.DeserializeSnac<Snac0401>(f);
// Assert.Inconclusive("Verify that Snac0401 was deserialized correctly.");
//}
[TestMethod]
public void Snac0402DeserializeTest()
{
var data = new byte[]
{
0x2A, 0x02, 0x33, 0x73, 0x00, 0x1A, 0x00, 0x04, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x1F, 0x40, 0x03, 0xE7, 0x03, 0xE7, 0x00, 0x00, 0x00, 0x00
};
Flap f = SerializationTools.DeserializeFlap(data);
var s = SerializationTools.DeserializeSnac<Snac0402>(f);
Assert.Inconclusive("Verify that Snac0402 was deserialized correctly.");
}
[TestMethod]
public void Snac0403DeserializeTest()
{
var data = new byte[]
{
0x2A, 0x02, 0x31, 0x6F, 0x00, 0x0A, 0x00, 0x04, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03
};
Flap f = SerializationTools.DeserializeFlap(data);
var s = SerializationTools.DeserializeSnac<Snac0403>(f);
Assert.Inconclusive("Verify that Snac0403 was deserialized correctly.");
}
[TestMethod]
public void Snac0404DeserializeTest()
{
var data = new byte[]
{
0x2A, 0x02, 0x33, 0x6F, 0x00, 0x0A, 0x00, 0x04, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04
};
Flap f = SerializationTools.DeserializeFlap(data);
var s = SerializationTools.DeserializeSnac<Snac0404>(f);
Assert.Inconclusive("Verify that Snac0404 was deserialized correctly.");
}
[TestMethod]
public void Snac0405DeserializeTest()
{
var data = new byte[]
{
0x2A, 0x02, 0x38, 0xC2, 0x00, 0x1A, 0x00, 0x04, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04,
0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0x02, 0x00, 0x03, 0xE7, 0x03, 0xE7, 0x00, 0x00, 0x03, 0xE8
};
Flap f = SerializationTools.DeserializeFlap(data);
var s = SerializationTools.DeserializeSnac<Snac0405>(f);
Assert.Inconclusive("Verify that Snac0405 was deserialized correctly.");
}
//[TestMethod]
//public void Snac0406DeserializeTest()
//{
// var data = new byte[]
// {
// 0x02, 0x23,
// 0x00, 0x47, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00, 0x01, 0x00, 0x06,
// 0x67,
// 0x15, 0x01,
// 0x00, 0x00, 0x00, 0x01, 0x07, 0x31, 0x30, 0x30, 0x30, 0x30,
// 0x00,
// 0x30, 0x30, 0x00, 0x02, 0x00, 0x23, 0x05, 0x01, 0x00, 0x01, 0x01, 0x01, 0x01, 0x00,
// 0x00,
// 0x00,
// 0x74, 0x65, 0x73, 0x74, 0x20, 0x63, 0x68, 0x61,
// 0x65,
// 0x20,
// 0x31, 0x20,
// 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x00, 0x06, 0x00, 0x00
// };
// var f = SerializationTools.DeserializeFlap(data);
// var s = SerializationTools.DeserializeSnac<Snac0406>(f);
// Assert.Inconclusive("Verify that Snac0406 was deserialized correctly.");
//}
[TestMethod]
public void Snac0406DeserializeTest()
{
var data = new byte[]
{
0x2A, 0x02, 0x36, 0x87, 0x00, 0x99, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00, 0x0F, 0x00, 0x06,
0xCC, 0xEB, 0x54, 0x00, 0xF7, 0x07, 0x00, 0x00, 0x00, 0x02, 0x09, 0x31, 0x32, 0x33, 0x34, 0x35,
0x36, 0x37, 0x38, 0x39, 0x00, 0x05, 0x00, 0x73, 0x00, 0x00, 0xCC, 0xEB, 0x54, 0x00, 0xF7, 0x07,
0x00, 0x00, 0x09, 0x46, 0x13, 0x49, 0x4C, 0x7F, 0x11, 0xD1, 0x82, 0x22, 0x44, 0x45, 0x53, 0x54,
0x00, 0x00, 0x00, 0x0A, 0x00, 0x02, 0x00, 0x01, 0x00, 0x0F, 0x00, 0x00, 0x27, 0x11, 0x00, 0x4B,
0x1B, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0xFB, 0xFF, 0x0E, 0x00, 0xFB,
0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
0x00, 0x21, 0x00, 0x0E, 0x00, 0x54, 0x65, 0x73, 0x74, 0x20, 0x6D, 0x65, 0x73, 0x73, 0x61, 0x67,
0x65, 0x2E, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x03, 0x00, 0x00
};
Flap f = SerializationTools.DeserializeFlap(data);
var s = SerializationTools.DeserializeSnac<Snac0406>(f);
Assert.Inconclusive("Verify that Snac0406 was deserialized correctly.");
}
//[TestMethod]
//public void Snac0406DeserializeTest()
//{
// var data = new byte[]
// {
// 0x02, 0x56,
// 0x00,
// 0x00,
// 0x00, 0x06, 0x00, 0x00, 0x00,
// 0x00, 0x06,
// 0x01, 0x33, 0x28, 0x00,
// 0x00, 0x04, 0x07, 0x31, 0x30, 0x30, 0x30, 0x30,
// 0x00,
// 0x30, 0x30, 0x00, 0x05, 0x00,
// 0x00, 0x04, 0x00, 0x43, 0x00, 0x54, 0x68,
// 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x74,
// 0x65, 0x20, 0x74, 0x65, 0x73, 0x74, 0x20, 0x75,
// 0x72,
// 0x20,
// 0x65, 0x73, 0x73,
// 0x67, 0x65, 0x20, 0x74,
// 0x20, 0x61,
// 0x20,
// 0x64, 0x20, 0x63,
// 0x65,
// 0x74,
// 0x68, 0x74, 0x74, 0x70,
// 0x68, 0x74, 0x74, 0x70,
// 0x74, 0x65, 0x73, 0x74,
// 0x75, 0x72,
// 0x00, 0x00, 0x06, 0x00, 0x00
// };
// var f = SerializationTools.DeserializeFlap(data);
// var s = SerializationTools.DeserializeSnac<Snac0406>(f);
// Assert.Inconclusive("Verify that Snac0406 was deserialized correctly.");
//}
//[TestMethod]
//public void Snac0407Channel1DeserializeTest()
//{
// var data = new byte[]
// {
// 0x02,
// 0x00, 0x66, 0x00, 0x04, 0x00, 0x07, 0x00, 0x00,
// 0x91,
// 0x00, 0x01, 0x07, 0x31, 0x30, 0x30, 0x30, 0x30,
// 0x00,
// 0x30, 0x30, 0x00, 0x00, 0x00, 0x04, 0x00, 0x01, 0x00, 0x02, 0x00, 0x50, 0x00, 0x06, 0x00, 0x04,
// 0x00, 0x01, 0x00, 0x00, 0x00,
// 0x00, 0x04, 0x00, 0x00, 0x04, 0x66, 0x00, 0x03, 0x00, 0x04,
// 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x24, 0x05, 0x01, 0x00, 0x01, 0x00, 0x01, 0x01, 0x00,
// 0x00, 0x00, 0x00, 0x00, 0x74, 0x65, 0x73, 0x74, 0x20, 0x70,
// 0x61, 0x69,
// 0x74, 0x65, 0x78, 0x74, 0x20,
// 0x65, 0x73, 0x73, 0x61, 0x67, 0x65
// };
// var f = SerializationTools.DeserializeFlap(data);
// var s = SerializationTools.DeserializeSnac<Snac0407>(f);
// Assert.Inconclusive("Verify that Snac0407 was deserialized correctly.");
//}
[TestMethod]
public void Snac0407Channel2DeserializeTest()
{
var data = new byte[]
{
0x2A, 0x02, 0x08, 0x2C, 0x01, 0x9D, 0x00, 0x04, 0x00, 0x07, 0x00, 0x00, 0x90, 0x2F, 0x30, 0x11,
0x70, 0x95, 0xA0, 0x00, 0x26, 0x1F, 0x00, 0x00, 0x00, 0x02, 0x07, 0x31, 0x32, 0x33, 0x34, 0x35,
0x36, 0x37, 0x00, 0x00, 0x00, 0x04, 0x00, 0x01, 0x00, 0x02, 0x00, 0x50, 0x00, 0x06, 0x00, 0x04,
0x20, 0x12, 0x00, 0x00, 0x00, 0x0F, 0x00, 0x04, 0x00, 0x00, 0x06, 0xF3, 0x00, 0x03, 0x00, 0x04,
0x40, 0x5A, 0x93, 0x78, 0x00, 0x05, 0x01, 0x5B, 0x00, 0x00, 0x70, 0x95, 0xA0, 0x00, 0x26, 0x1F,
0x00, 0x00, 0x09, 0x46, 0x13, 0x49, 0x4C, 0x7F, 0x11, 0xD1, 0x82, 0x22, 0x44, 0x45, 0x53, 0x54,
0x00, 0x00, 0x00, 0x0A, 0x00, 0x02, 0x00, 0x01, 0x00, 0x0F, 0x00, 0x00, 0x27, 0x11, 0x01, 0x33,
0x1B, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0xE3, 0xFF, 0x0E, 0x00, 0xE3,
0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
0x00, 0x21, 0x00, 0xCC, 0x00, 0x7B, 0x5C, 0x72, 0x74, 0x66, 0x31, 0x5C, 0x61, 0x6E, 0x73, 0x69,
0x5C, 0x61, 0x6E, 0x73, 0x69, 0x63, 0x70, 0x67, 0x31, 0x32, 0x35, 0x31, 0x5C, 0x64, 0x65, 0x66,
0x66, 0x30, 0x5C, 0x64, 0x65, 0x66, 0x6C, 0x61, 0x6E, 0x67, 0x31, 0x30, 0x34, 0x39, 0x7B, 0x5C,
0x66, 0x6F, 0x6E, 0x74, 0x74, 0x62, 0x6C, 0x7B, 0x5C, 0x66, 0x30, 0x5C, 0x66, 0x6E, 0x69, 0x6C,
0x5C, 0x66, 0x63, 0x68, 0x61, 0x72, 0x73, 0x65, 0x74, 0x32, 0x30, 0x34, 0x7B, 0x5C, 0x2A, 0x5C,
0x66, 0x6E, 0x61, 0x6D, 0x65, 0x20, 0x4D, 0x53, 0x20, 0x53, 0x61, 0x6E, 0x73, 0x20, 0x53, 0x65,
0x72, 0x69, 0x66, 0x3B, 0x7D, 0x4D, 0x53, 0x20, 0x53, 0x68, 0x65, 0x6C, 0x6C, 0x20, 0x44, 0x6C,
0x67, 0x3B, 0x7D, 0x7D, 0x0D, 0x0A, 0x7B, 0x5C, 0x63, 0x6F, 0x6C, 0x6F, 0x72, 0x74, 0x62, 0x6C,
0x20, 0x3B, 0x5C, 0x72, 0x65, 0x64, 0x30, 0x5C, 0x67, 0x72, 0x65, 0x65, 0x6E, 0x30, 0x5C, 0x62,
0x6C, 0x75, 0x65, 0x30, 0x3B, 0x7D, 0x0D, 0x0A, 0x5C, 0x76, 0x69, 0x65, 0x77, 0x6B, 0x69, 0x6E,
0x64, 0x34, 0x5C, 0x75, 0x63, 0x31, 0x5C, 0x70, 0x61, 0x72, 0x64, 0x5C, 0x63, 0x66, 0x31, 0x5C,
0x66, 0x30, 0x5C, 0x66, 0x73, 0x32, 0x30, 0x3C, 0x23, 0x23, 0x69, 0x63, 0x71, 0x69, 0x6D, 0x61,
0x67, 0x65, 0x30, 0x30, 0x30, 0x38, 0x3E, 0x5C, 0x70, 0x61, 0x72, 0x0D, 0x0A, 0x7D, 0x0D, 0x0A,
0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x26, 0x00, 0x00, 0x00, 0x7B, 0x39, 0x37,
0x42, 0x31, 0x32, 0x37, 0x35, 0x31, 0x2D, 0x32, 0x34, 0x33, 0x43, 0x2D, 0x34, 0x33, 0x33, 0x34,
0x2D, 0x41, 0x44, 0x32, 0x32, 0x2D, 0x44, 0x36, 0x41, 0x42, 0x46, 0x37, 0x33, 0x46, 0x31, 0x34,
0x39, 0x32, 0x7D
};
Flap f = SerializationTools.DeserializeFlap(data);
var s = SerializationTools.DeserializeSnac<Snac0407>(f);
Assert.Inconclusive("Verify that Snac0407 was deserialized correctly.");
}
//[TestMethod]
//public void Snac0407DeserializeTest()
//{
// var data = new byte[]
// {
// 0x02,
// 0x00,
// 0x00, 0x04, 0x00, 0x07, 0x00, 0x00,
// 0x59, 0x65,
// 0x56, 0x00, 0x04, 0x07, 0x31, 0x30, 0x30, 0x30, 0x30,
// 0x00,
// 0x30, 0x30, 0x00, 0x00, 0x00, 0x04, 0x00, 0x01, 0x00, 0x02, 0x00, 0x50, 0x00, 0x06, 0x00, 0x04,
// 0x00, 0x01, 0x00, 0x00, 0x00,
// 0x00, 0x04, 0x00, 0x00, 0x00,
// 0x00, 0x03, 0x00, 0x04,
// 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x28, 0x40, 0x42,
// 0x00, 0x04, 0x00, 0x20, 0x00,
// 0x55, 0x72,
// 0x20, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69,
// 0x68, 0x74, 0x74, 0x70,
// 0x74, 0x65, 0x73, 0x74,
// 0x75, 0x72,
// 0x00
// };
// var f = SerializationTools.DeserializeFlap(data);
// var s = SerializationTools.DeserializeSnac<Snac0407>(f);
// Assert.Inconclusive("Verify that Snac0407 was deserialized correctly.");
//}
//[TestMethod]
//public void Snac0408DeserializeTest()
//{
// var data = new byte[]
// {
// 0x2A, 0x02, 0x7D, 0x6E, 0x00, 0x1B, 0x00, 0x04, 0x00, 0x08, 0x00, 0x00, 0x00, 0x1B, 0x00, 0x08,
// 0x00, 0x00, 0x0E, 0x73, 0x77, 0x65, 0x65, 0x74, 0x67, 0x69, 0x72, 0x6C, 0x33, 0x38, 0x34, 0x36,
// 0x46,
// 0x32
// };
// var f = SerializationTools.DeserializeFlap(data);
// var s = SerializationTools.DeserializeSnac<Snac0408>(f);
// Assert.Inconclusive("Verify that Snac0408 was deserialized correctly.");
//}
//[TestMethod]
//public void Snac0409DeserializeTest()
//{
// var data = new byte[]
// {
// 0x2A, 0x02, 0xD5, 0xB8, 0x00, 0x0E, 0x00, 0x04, 0x00, 0x09, 0x00, 0x00, 0x00, 0x17, 0x00, 0x08,
// 0x00, 0xC8, 0x01, 0xED
// };
// var f = SerializationTools.DeserializeFlap(data);
// var s = SerializationTools.DeserializeSnac<Snac0409>(f);
// Assert.Inconclusive("Verify that Snac0409 was deserialized correctly.");
//}
[TestMethod]
public void Snac040ADeserializeTest()
{
var data = new byte[]
{
0x2A, 0x02, 0x12, 0x05, 0x00, 0x38, 0x00, 0x04, 0x00, 0x0A, 0x00, 0x00, 0x8E, 0x36, 0xC7, 0xB1,
0x00, 0x02, 0x07, 0x36, 0x32, 0x31, 0x38, 0x38, 0x39, 0x35, 0x00, 0x00, 0x00, 0x04, 0x00, 0x01,
0x00, 0x02, 0x00, 0x06, 0x00, 0x04, 0x00, 0x02, 0x00, 0x00, 0x00, 0x0F, 0x00, 0x04, 0x00, 0x00,
0x00, 0x00, 0x00, 0x03, 0x00, 0x04, 0x3D, 0xE7, 0x38, 0x8B, 0x00, 0x01, 0x00, 0x01
};
Flap f = SerializationTools.DeserializeFlap(data);
var s = SerializationTools.DeserializeSnac<Snac040A>(f);
Assert.Inconclusive("Verify that Snac040A was deserialized correctly.");
}
[TestMethod]
public void Snac040BDeserializeTest()
{
var data = new byte[]
{
0x2A, 0x02, 0x54, 0x28, 0x00, 0x6E, 0x00, 0x04, 0x00, 0x0B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0B,
0xF3, 0x3A, 0xC1, 0x0C, 0x70, 0x18, 0x00, 0x00, 0x00, 0x02, 0x07, 0x36, 0x32, 0x31, 0x38, 0x38,
0x39, 0x35, 0x00, 0x03, 0x1B, 0x00, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x07,
0x00, 0x0E, 0x00, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0xE9, 0x03, 0x00, 0x00, 0x00, 0x00, 0x1B, 0x00, 0x55, 0x73, 0x65, 0x72, 0x20, 0x69, 0x73,
0x20, 0x63, 0x75, 0x72, 0x72, 0x65, 0x6E, 0x74, 0x6C, 0x79, 0x20, 0x4F, 0x63, 0x63, 0x75, 0x70,
0x69, 0x65, 0x64, 0x00
};
Flap f = SerializationTools.DeserializeFlap(data);
var s = SerializationTools.DeserializeSnac<Snac040B>(f);
Assert.Inconclusive("Verify that Snac040B was deserialized correctly.");
}
//[TestMethod]
//public void Snac040BDeserializeTest()
//{
// var data = new byte[]
// {
// };
// var f = SerializationTools.DeserializeFlap(data);
// var s = SerializationTools.DeserializeSnac<Snac040B>(f);
// Assert.Inconclusive("Verify that Snac040B was deserialized correctly.");
//}
//[TestMethod]
//public void Snac040BDeserializeTest()
//{
// var data = new byte[]
// {
// 0x2A, 0x02, 0x54, 0x28, 0x00, 0x6E, 0x00, 0x04, 0x00, 0x0B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0B,
// 0xF3, 0x3A, 0xC1, 0x0C, 0x70, 0x18, 0x00, 0x00, 0x00, 0x02, 0x07, 0x36, 0x32, 0x31, 0x38, 0x38,
// 0x88,
// 0x39, 0x35, 0x00, 0x03, 0x1B, 0x00, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x07,
// 0x00, 0x0E, 0x00, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// 0x00, 0xE9, 0x03, 0x00, 0x00, 0x00, 0x00, 0x1B, 0x00, 0x55, 0x73, 0x65, 0x72, 0x20, 0x69, 0x73,
// 0x20, 0x63, 0x75, 0x72, 0x72, 0x65, 0x6E, 0x74, 0x6C, 0x79, 0x20, 0x4F, 0x63, 0x63, 0x75, 0x70,
// 0x69, 0x65, 0x64, 0x00
// };
// var f = SerializationTools.DeserializeFlap(data);
// var s = SerializationTools.DeserializeSnac<Snac040B>(f);
// Assert.Inconclusive("Verify that Snac040B was deserialized correctly.");
//}
[TestMethod]
public void Snac040CDeserializeTest()
{
var data = new byte[]
{
0x2A, 0x02, 0x39, 0x37, 0x00, 0x1D, 0x00, 0x04, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x0C, 0x00, 0x06,
0xAB, 0xA5, 0xF5, 0x29, 0x29, 0x1D, 0x00, 0x00, 0x00, 0x02, 0x08, 0x35, 0x32, 0x39, 0x34, 0x33,
0x31, 0x32, 0x37
};
Flap f = SerializationTools.DeserializeFlap(data);
var s = SerializationTools.DeserializeSnac<Snac040C>(f);
Assert.Inconclusive("Verify that Snac040C was deserialized correctly.");
}
[TestMethod]
public void Snac0414DeserializeTest()
{
var data = new byte[]
{
0x2A, 0x02, 0x38, 0xC2, 0x00, 0x1E, 0x00, 0x04, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x14,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x07, 0x36, 0x32, 0x31, 0x38, 0x38,
0x39, 0x35, 0x00, 0x02
};
Flap f = SerializationTools.DeserializeFlap(data);
var s = SerializationTools.DeserializeSnac<Snac0414>(f);
Assert.Inconclusive("Verify that Snac0414 was deserialized correctly.");
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Binary
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Impl.Binary.IO;
using Apache.Ignite.Core.Impl.Binary.Metadata;
using Apache.Ignite.Core.Impl.Common;
/// <summary>
/// Binary builder implementation.
/// </summary>
internal class BinaryObjectBuilder : IBinaryObjectBuilder
{
/** Cached dictionary with no values. */
private static readonly IDictionary<int, BinaryBuilderField> EmptyVals =
new Dictionary<int, BinaryBuilderField>();
/** Binary. */
private readonly Binary _binary;
/** */
private readonly BinaryObjectBuilder _parent;
/** Initial binary object. */
private readonly BinaryObject _obj;
/** Type descriptor. */
private readonly IBinaryTypeDescriptor _desc;
/** Values. */
private SortedDictionary<string, BinaryBuilderField> _vals;
/** Contextual fields. */
private IDictionary<int, BinaryBuilderField> _cache;
/** Current context. */
private Context _ctx;
/** Write array action. */
private static readonly Action<BinaryWriter, object> WriteArrayAction =
(w, o) => w.WriteArrayInternal((Array) o);
/** Write collection action. */
private static readonly Action<BinaryWriter, object> WriteCollectionAction =
(w, o) => w.WriteCollection((ICollection) o);
/** Write timestamp action. */
private static readonly Action<BinaryWriter, object> WriteTimestampAction =
(w, o) => w.WriteTimestamp((DateTime?) o);
/** Write timestamp array action. */
private static readonly Action<BinaryWriter, object> WriteTimestampArrayAction =
(w, o) => w.WriteTimestampArray((DateTime?[])o);
/// <summary>
/// Constructor.
/// </summary>
/// <param name="binary">Binary.</param>
/// <param name="parent">Parent builder.</param>
/// <param name="obj">Initial binary object.</param>
/// <param name="desc">Type descriptor.</param>
public BinaryObjectBuilder(Binary binary, BinaryObjectBuilder parent,
BinaryObject obj, IBinaryTypeDescriptor desc)
{
Debug.Assert(binary != null);
Debug.Assert(desc != null);
_binary = binary;
_parent = parent ?? this;
_desc = desc;
_obj = obj ?? BinaryFromDescriptor(desc);
}
/** <inheritDoc /> */
public T GetField<T>(string name)
{
BinaryBuilderField field;
if (_vals != null && _vals.TryGetValue(name, out field))
return field != BinaryBuilderField.RmvMarker ? (T) field.Value : default(T);
int pos;
if (!_obj.TryGetFieldPosition(name, out pos))
return default(T);
T val;
if (TryGetCachedField(pos, out val))
return val;
val = _obj.GetField<T>(pos, this);
var fld = CacheField(pos, val);
SetField0(name, fld);
return val;
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetField<T>(string fieldName, T val)
{
// typeof(T) is used instead of val.GetType():
// it works for nulls, and generic parameter is supposed to clearly show the intent of the user.
// When boxed values are being passed, the overload below should be used.
return SetField(fieldName, val, typeof(T));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetField<T>(string fieldName, T val, Type valType)
{
IgniteArgumentCheck.NotNull(valType, "valType");
return SetField0(fieldName, new BinaryBuilderField(valType, val, BinaryTypeId.GetTypeId(valType)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetArrayField<T>(string fieldName, T[] val)
{
return SetField0(fieldName,
new BinaryBuilderField(typeof (T[]), val, BinaryTypeId.Array, WriteArrayAction));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetBooleanField(string fieldName, bool val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (bool), val, BinaryTypeId.Bool,
(w, o) => w.WriteBooleanField((bool) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetBooleanArrayField(string fieldName, bool[] val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (bool[]), val, BinaryTypeId.ArrayBool,
(w, o) => w.WriteBooleanArray((bool[]) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetByteField(string fieldName, byte val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (byte), val, BinaryTypeId.Byte,
(w, o) => w.WriteByteField((byte) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetByteArrayField(string fieldName, byte[] val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (byte[]), val, BinaryTypeId.ArrayByte,
(w, o) => w.WriteByteArray((byte[]) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetCharField(string fieldName, char val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (char), val, BinaryTypeId.Char,
(w, o) => w.WriteCharField((char) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetCharArrayField(string fieldName, char[] val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (char[]), val, BinaryTypeId.ArrayChar,
(w, o) => w.WriteCharArray((char[]) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetCollectionField(string fieldName, ICollection val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (ICollection), val, BinaryTypeId.Collection,
WriteCollectionAction));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetDecimalField(string fieldName, decimal? val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (decimal?), val, BinaryTypeId.Decimal,
(w, o) => w.WriteDecimal((decimal?) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetDecimalArrayField(string fieldName, decimal?[] val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (decimal?[]), val, BinaryTypeId.ArrayDecimal,
(w, o) => w.WriteDecimalArray((decimal?[]) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetDictionaryField(string fieldName, IDictionary val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (IDictionary), val, BinaryTypeId.Dictionary,
(w, o) => w.WriteDictionary((IDictionary) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetDoubleField(string fieldName, double val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (double), val, BinaryTypeId.Double,
(w, o) => w.WriteDoubleField((double) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetDoubleArrayField(string fieldName, double[] val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (double[]), val, BinaryTypeId.ArrayDouble,
(w, o) => w.WriteDoubleArray((double[]) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetEnumField<T>(string fieldName, T val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (T), val, BinaryTypeId.Enum,
(w, o) => w.WriteEnum((T) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetEnumArrayField<T>(string fieldName, T[] val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (T[]), val, BinaryTypeId.ArrayEnum,
(w, o) => w.WriteEnumArray((T[]) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetFloatField(string fieldName, float val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (float), val, BinaryTypeId.Float,
(w, o) => w.WriteFloatField((float) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetFloatArrayField(string fieldName, float[] val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (float[]), val, BinaryTypeId.ArrayFloat,
(w, o) => w.WriteFloatArray((float[]) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetGuidField(string fieldName, Guid? val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (Guid?), val, BinaryTypeId.Guid,
(w, o) => w.WriteGuid((Guid?) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetGuidArrayField(string fieldName, Guid?[] val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (Guid?[]), val, BinaryTypeId.ArrayGuid,
(w, o) => w.WriteGuidArray((Guid?[]) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetIntField(string fieldName, int val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (int), val, BinaryTypeId.Int,
(w, o) => w.WriteIntField((int) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetIntArrayField(string fieldName, int[] val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (int[]), val, BinaryTypeId.ArrayInt,
(w, o) => w.WriteIntArray((int[]) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetLongField(string fieldName, long val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (long), val, BinaryTypeId.Long,
(w, o) => w.WriteLongField((long) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetLongArrayField(string fieldName, long[] val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (long[]), val, BinaryTypeId.ArrayLong,
(w, o) => w.WriteLongArray((long[]) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetShortField(string fieldName, short val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (short), val, BinaryTypeId.Short,
(w, o) => w.WriteShortField((short) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetShortArrayField(string fieldName, short[] val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (short[]), val, BinaryTypeId.ArrayShort,
(w, o) => w.WriteShortArray((short[]) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetStringField(string fieldName, string val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (string), val, BinaryTypeId.String,
(w, o) => w.WriteString((string) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetStringArrayField(string fieldName, string[] val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (string[]), val, BinaryTypeId.ArrayString,
(w, o) => w.WriteStringArray((string[]) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetTimestampField(string fieldName, DateTime? val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (DateTime?), val, BinaryTypeId.Timestamp,
WriteTimestampAction));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetTimestampArrayField(string fieldName, DateTime?[] val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (DateTime?[]), val, BinaryTypeId.ArrayTimestamp,
WriteTimestampArrayAction));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder RemoveField(string name)
{
return SetField0(name, BinaryBuilderField.RmvMarker);
}
/** <inheritDoc /> */
public IBinaryObject Build()
{
// Assume that resulting length will be no less than header + [fields_cnt] * 12;
int estimatedCapacity = BinaryObjectHeader.Size + (_vals == null ? 0 : _vals.Count*12);
using (var outStream = new BinaryHeapStream(estimatedCapacity))
{
BinaryWriter writer = _binary.Marshaller.StartMarshal(outStream);
writer.SetBuilder(this);
// All related builders will work in this context with this writer.
_parent._ctx = new Context(writer);
try
{
// Write.
writer.Write(this);
// Process metadata.
_binary.Marshaller.FinishMarshal(writer);
// Create binary object once metadata is processed.
return new BinaryObject(_binary.Marshaller, outStream.InternalArray, 0,
BinaryObjectHeader.Read(outStream, 0));
}
finally
{
// Cleanup.
_parent._ctx.Closed = true;
}
}
}
/// <summary>
/// Create child builder.
/// </summary>
/// <param name="obj">binary object.</param>
/// <returns>Child builder.</returns>
public BinaryObjectBuilder Child(BinaryObject obj)
{
var desc = _binary.Marshaller.GetDescriptor(true, obj.TypeId);
return new BinaryObjectBuilder(_binary, null, obj, desc);
}
/// <summary>
/// Get cache field.
/// </summary>
/// <param name="pos">Position.</param>
/// <param name="val">Value.</param>
/// <returns><c>true</c> if value is found in cache.</returns>
public bool TryGetCachedField<T>(int pos, out T val)
{
if (_parent._cache != null)
{
BinaryBuilderField res;
if (_parent._cache.TryGetValue(pos, out res))
{
val = res != null ? (T) res.Value : default(T);
return true;
}
}
val = default(T);
return false;
}
/// <summary>
/// Add field to cache test.
/// </summary>
/// <param name="pos">Position.</param>
/// <param name="val">Value.</param>
public BinaryBuilderField CacheField<T>(int pos, T val)
{
if (_parent._cache == null)
_parent._cache = new Dictionary<int, BinaryBuilderField>(2);
var hdr = _obj.Data[pos];
var field = new BinaryBuilderField(typeof(T), val, hdr, GetWriteAction(hdr, pos));
_parent._cache[pos] = field;
return field;
}
/// <summary>
/// Gets the write action by header.
/// </summary>
/// <param name="header">The header.</param>
/// <param name="pos">Position.</param>
/// <returns>Write action.</returns>
private Action<BinaryWriter, object> GetWriteAction(byte header, int pos)
{
// We need special actions for all cases where SetField(X) produces different result from SetSpecialField(X)
// Arrays, Collections, Dates
switch (header)
{
case BinaryTypeId.Array:
return WriteArrayAction;
case BinaryTypeId.Collection:
return WriteCollectionAction;
case BinaryTypeId.Timestamp:
return WriteTimestampAction;
case BinaryTypeId.ArrayTimestamp:
return WriteTimestampArrayAction;
case BinaryTypeId.ArrayEnum:
using (var stream = new BinaryHeapStream(_obj.Data))
{
stream.Seek(pos, SeekOrigin.Begin + 1);
var elementTypeId = stream.ReadInt();
return (w, o) => w.WriteEnumArrayInternal((Array) o, elementTypeId);
}
default:
return null;
}
}
/// <summary>
/// Internal set field routine.
/// </summary>
/// <param name="fieldName">Name.</param>
/// <param name="val">Value.</param>
/// <returns>This builder.</returns>
private IBinaryObjectBuilder SetField0(string fieldName, BinaryBuilderField val)
{
if (_vals == null)
_vals = new SortedDictionary<string, BinaryBuilderField>();
_vals[fieldName] = val;
return this;
}
/// <summary>
/// Mutate binary object.
/// </summary>
/// <param name="inStream">Input stream with initial object.</param>
/// <param name="outStream">Output stream.</param>
/// <param name="desc">Type descriptor.</param>
/// <param name="vals">Values.</param>
private void Mutate(
BinaryHeapStream inStream,
BinaryHeapStream outStream,
IBinaryTypeDescriptor desc,
IDictionary<string, BinaryBuilderField> vals)
{
// Set correct builder to writer frame.
BinaryObjectBuilder oldBuilder = _parent._ctx.Writer.SetBuilder(_parent);
int streamPos = inStream.Position;
try
{
// Prepare fields.
IBinaryTypeHandler metaHnd = _binary.Marshaller.GetBinaryTypeHandler(desc);
IDictionary<int, BinaryBuilderField> vals0;
if (vals == null || vals.Count == 0)
vals0 = EmptyVals;
else
{
vals0 = new Dictionary<int, BinaryBuilderField>(vals.Count);
foreach (KeyValuePair<string, BinaryBuilderField> valEntry in vals)
{
int fieldId = BinaryUtils.FieldId(desc.TypeId, valEntry.Key, desc.NameMapper, desc.IdMapper);
if (vals0.ContainsKey(fieldId))
throw new IgniteException("Collision in field ID detected (change field name or " +
"define custom ID mapper) [fieldName=" + valEntry.Key + ", fieldId=" + fieldId + ']');
vals0[fieldId] = valEntry.Value;
// Write metadata if: 1) it is enabled for type; 2) type is not null (i.e. it is neither
// remove marker, nor a field read through "GetField" method.
if (metaHnd != null && valEntry.Value.Type != null)
metaHnd.OnFieldWrite(fieldId, valEntry.Key, valEntry.Value.TypeId);
}
}
// Actual processing.
Mutate0(_parent._ctx, inStream, outStream, true, vals0);
// 3. Handle metadata.
if (metaHnd != null)
{
_parent._ctx.Writer.SaveMetadata(desc, metaHnd.OnObjectWriteFinished());
}
}
finally
{
// Restore builder frame.
_parent._ctx.Writer.SetBuilder(oldBuilder);
inStream.Seek(streamPos, SeekOrigin.Begin);
}
}
/// <summary>
/// Internal mutation routine.
/// </summary>
/// <param name="inStream">Input stream.</param>
/// <param name="outStream">Output stream.</param>
/// <param name="ctx">Context.</param>
/// <param name="changeHash">WHether hash should be changed.</param>
/// <param name="vals">Values to be replaced.</param>
/// <returns>Mutated object.</returns>
private void Mutate0(Context ctx, BinaryHeapStream inStream, IBinaryStream outStream,
bool changeHash, IDictionary<int, BinaryBuilderField> vals)
{
int inStartPos = inStream.Position;
int outStartPos = outStream.Position;
byte inHdr = inStream.ReadByte();
if (inHdr == BinaryUtils.HdrNull)
outStream.WriteByte(BinaryUtils.HdrNull);
else if (inHdr == BinaryUtils.HdrHnd)
{
int inHnd = inStream.ReadInt();
int oldPos = inStartPos - inHnd;
int newPos;
if (ctx.OldToNew(oldPos, out newPos))
{
// Handle is still valid.
outStream.WriteByte(BinaryUtils.HdrHnd);
outStream.WriteInt(outStartPos - newPos);
}
else
{
// Handle is invalid, write full object.
int inRetPos = inStream.Position;
inStream.Seek(oldPos, SeekOrigin.Begin);
Mutate0(ctx, inStream, outStream, false, EmptyVals);
inStream.Seek(inRetPos, SeekOrigin.Begin);
}
}
else if (inHdr == BinaryUtils.HdrFull)
{
var inHeader = BinaryObjectHeader.Read(inStream, inStartPos);
BinaryUtils.ValidateProtocolVersion(inHeader.Version);
int hndPos;
if (ctx.AddOldToNew(inStartPos, outStartPos, out hndPos))
{
// Object could be cached in parent builder.
BinaryBuilderField cachedVal;
if (_parent._cache != null && _parent._cache.TryGetValue(inStartPos, out cachedVal))
{
WriteField(ctx, cachedVal);
}
else
{
// New object, write in full form.
var inSchema = BinaryObjectSchemaSerializer.ReadSchema(inStream, inStartPos, inHeader,
_desc.Schema, _binary.Marshaller.Ignite);
var outSchema = BinaryObjectSchemaHolder.Current;
var schemaIdx = outSchema.PushSchema();
try
{
// Skip header as it is not known at this point.
outStream.Seek(BinaryObjectHeader.Size, SeekOrigin.Current);
if (inSchema != null)
{
foreach (var inField in inSchema)
{
BinaryBuilderField fieldVal;
var fieldFound = vals.TryGetValue(inField.Id, out fieldVal);
if (fieldFound && fieldVal == BinaryBuilderField.RmvMarker)
continue;
outSchema.PushField(inField.Id, outStream.Position - outStartPos);
if (!fieldFound)
fieldFound = _parent._cache != null &&
_parent._cache.TryGetValue(inField.Offset + inStartPos,
out fieldVal);
if (fieldFound)
{
WriteField(ctx, fieldVal);
vals.Remove(inField.Id);
}
else
{
// Field is not tracked, re-write as is.
inStream.Seek(inField.Offset + inStartPos, SeekOrigin.Begin);
Mutate0(ctx, inStream, outStream, false, EmptyVals);
}
}
}
// Write remaining new fields.
foreach (var valEntry in vals)
{
if (valEntry.Value == BinaryBuilderField.RmvMarker)
continue;
outSchema.PushField(valEntry.Key, outStream.Position - outStartPos);
WriteField(ctx, valEntry.Value);
}
var flags = inHeader.IsUserType
? BinaryObjectHeader.Flag.UserType
: BinaryObjectHeader.Flag.None;
if (inHeader.IsCustomDotNetType)
flags |= BinaryObjectHeader.Flag.CustomDotNetType;
// Write raw data.
int outRawOff = outStream.Position - outStartPos;
if (inHeader.HasRaw)
{
var inRawOff = inHeader.GetRawOffset(inStream, inStartPos);
var inRawLen = inHeader.SchemaOffset - inRawOff;
flags |= BinaryObjectHeader.Flag.HasRaw;
outStream.Write(inStream.InternalArray, inStartPos + inRawOff, inRawLen);
}
// Write schema
int outSchemaOff = outRawOff;
var schemaPos = outStream.Position;
int outSchemaId;
if (inHeader.IsCompactFooter)
flags |= BinaryObjectHeader.Flag.CompactFooter;
var hasSchema = outSchema.WriteSchema(outStream, schemaIdx, out outSchemaId, ref flags);
if (hasSchema)
{
outSchemaOff = schemaPos - outStartPos;
flags |= BinaryObjectHeader.Flag.HasSchema;
if (inHeader.HasRaw)
outStream.WriteInt(outRawOff);
if (_desc.Schema.Get(outSchemaId) == null)
_desc.Schema.Add(outSchemaId, outSchema.GetSchema(schemaIdx));
}
var outLen = outStream.Position - outStartPos;
var outHash = inHeader.HashCode;
if (changeHash)
{
// Get from identity resolver.
outHash = BinaryArrayEqualityComparer.GetHashCode(outStream,
outStartPos + BinaryObjectHeader.Size,
schemaPos - outStartPos - BinaryObjectHeader.Size);
}
var outHeader = new BinaryObjectHeader(inHeader.TypeId, outHash, outLen,
outSchemaId, outSchemaOff, flags);
BinaryObjectHeader.Write(outHeader, outStream, outStartPos);
outStream.Seek(outStartPos + outLen, SeekOrigin.Begin); // seek to the end of the object
}
finally
{
outSchema.PopSchema(schemaIdx);
}
}
}
else
{
// Object has already been written, write as handle.
outStream.WriteByte(BinaryUtils.HdrHnd);
outStream.WriteInt(outStartPos - hndPos);
}
// Synchronize input stream position.
inStream.Seek(inStartPos + inHeader.Length, SeekOrigin.Begin);
}
else
{
// Try writing as well-known type with fixed size.
outStream.WriteByte(inHdr);
if (!WriteAsPredefined(inHdr, inStream, outStream, ctx))
throw new IgniteException("Unexpected header [position=" + (inStream.Position - 1) +
", header=" + inHdr + ']');
}
}
/// <summary>
/// Writes the specified field.
/// </summary>
private static void WriteField(Context ctx, BinaryBuilderField field)
{
var action = field.WriteAction;
if (action != null)
action(ctx.Writer, field.Value);
else
ctx.Writer.Write(field.Value);
}
/// <summary>
/// Process binary object inverting handles if needed.
/// </summary>
/// <param name="outStream">Output stream.</param>
/// <param name="port">Binary object.</param>
internal void ProcessBinary(IBinaryStream outStream, BinaryObject port)
{
// Special case: writing binary object with correct inversions.
using (var inStream = new BinaryHeapStream(port.Data))
{
inStream.Seek(port.Offset, SeekOrigin.Begin);
// Use fresh context to ensure correct binary inversion.
Mutate0(new Context(), inStream, outStream, false, EmptyVals);
}
}
/// <summary>
/// Process child builder.
/// </summary>
/// <param name="outStream">Output stream.</param>
/// <param name="builder">Builder.</param>
internal void ProcessBuilder(IBinaryStream outStream, BinaryObjectBuilder builder)
{
using (var inStream = new BinaryHeapStream(builder._obj.Data))
{
inStream.Seek(builder._obj.Offset, SeekOrigin.Begin);
// Builder parent context might be null only in one case: if we never met this group of
// builders before. In this case we set context to their parent and track it. Context
// cleanup will be performed at the very end of build process.
if (builder._parent._ctx == null || builder._parent._ctx.Closed)
builder._parent._ctx = new Context(_parent._ctx);
builder.Mutate(inStream, (BinaryHeapStream) outStream, builder._desc,
builder._vals);
}
}
/// <summary>
/// Write object as a predefined type if possible.
/// </summary>
/// <param name="hdr">Header.</param>
/// <param name="inStream">Input stream.</param>
/// <param name="outStream">Output stream.</param>
/// <param name="ctx">Context.</param>
/// <returns><c>True</c> if was written.</returns>
private bool WriteAsPredefined(byte hdr, BinaryHeapStream inStream, IBinaryStream outStream,
Context ctx)
{
switch (hdr)
{
case BinaryTypeId.Byte:
TransferBytes(inStream, outStream, 1);
break;
case BinaryTypeId.Short:
TransferBytes(inStream, outStream, 2);
break;
case BinaryTypeId.Int:
TransferBytes(inStream, outStream, 4);
break;
case BinaryTypeId.Long:
TransferBytes(inStream, outStream, 8);
break;
case BinaryTypeId.Float:
TransferBytes(inStream, outStream, 4);
break;
case BinaryTypeId.Double:
TransferBytes(inStream, outStream, 8);
break;
case BinaryTypeId.Char:
TransferBytes(inStream, outStream, 2);
break;
case BinaryTypeId.Bool:
TransferBytes(inStream, outStream, 1);
break;
case BinaryTypeId.Decimal:
TransferBytes(inStream, outStream, 4); // Transfer scale
int magLen = inStream.ReadInt(); // Transfer magnitude length.
outStream.WriteInt(magLen);
TransferBytes(inStream, outStream, magLen); // Transfer magnitude.
break;
case BinaryTypeId.String:
BinaryUtils.WriteString(BinaryUtils.ReadString(inStream), outStream);
break;
case BinaryTypeId.Guid:
TransferBytes(inStream, outStream, 16);
break;
case BinaryTypeId.Timestamp:
TransferBytes(inStream, outStream, 12);
break;
case BinaryTypeId.ArrayByte:
TransferArray(inStream, outStream, 1);
break;
case BinaryTypeId.ArrayShort:
TransferArray(inStream, outStream, 2);
break;
case BinaryTypeId.ArrayInt:
TransferArray(inStream, outStream, 4);
break;
case BinaryTypeId.ArrayLong:
TransferArray(inStream, outStream, 8);
break;
case BinaryTypeId.ArrayFloat:
TransferArray(inStream, outStream, 4);
break;
case BinaryTypeId.ArrayDouble:
TransferArray(inStream, outStream, 8);
break;
case BinaryTypeId.ArrayChar:
TransferArray(inStream, outStream, 2);
break;
case BinaryTypeId.ArrayBool:
TransferArray(inStream, outStream, 1);
break;
case BinaryTypeId.ArrayDecimal:
case BinaryTypeId.ArrayString:
case BinaryTypeId.ArrayGuid:
case BinaryTypeId.ArrayTimestamp:
int arrLen = inStream.ReadInt();
outStream.WriteInt(arrLen);
for (int i = 0; i < arrLen; i++)
Mutate0(ctx, inStream, outStream, false, null);
break;
case BinaryTypeId.ArrayEnum:
case BinaryTypeId.Array:
int type = inStream.ReadInt();
outStream.WriteInt(type);
if (type == BinaryTypeId.Unregistered)
{
outStream.WriteByte(inStream.ReadByte()); // String header.
BinaryUtils.WriteString(BinaryUtils.ReadString(inStream), outStream); // String data.
}
arrLen = inStream.ReadInt();
outStream.WriteInt(arrLen);
for (int i = 0; i < arrLen; i++)
Mutate0(ctx, inStream, outStream, false, EmptyVals);
break;
case BinaryTypeId.Collection:
int colLen = inStream.ReadInt();
outStream.WriteInt(colLen);
outStream.WriteByte(inStream.ReadByte());
for (int i = 0; i < colLen; i++)
Mutate0(ctx, inStream, outStream, false, EmptyVals);
break;
case BinaryTypeId.Dictionary:
int dictLen = inStream.ReadInt();
outStream.WriteInt(dictLen);
outStream.WriteByte(inStream.ReadByte());
for (int i = 0; i < dictLen; i++)
{
Mutate0(ctx, inStream, outStream, false, EmptyVals);
Mutate0(ctx, inStream, outStream, false, EmptyVals);
}
break;
case BinaryTypeId.Binary:
TransferArray(inStream, outStream, 1); // Data array.
TransferBytes(inStream, outStream, 4); // Offset in array.
break;
case BinaryTypeId.Enum:
TransferBytes(inStream, outStream, 8); // int typeId, int value.
break;
default:
return false;
}
return true;
}
/// <summary>
/// Transfer bytes from one stream to another.
/// </summary>
/// <param name="inStream">Input stream.</param>
/// <param name="outStream">Output stream.</param>
/// <param name="cnt">Bytes count.</param>
private static void TransferBytes(BinaryHeapStream inStream, IBinaryStream outStream, int cnt)
{
outStream.Write(inStream.InternalArray, inStream.Position, cnt);
inStream.Seek(cnt, SeekOrigin.Current);
}
/// <summary>
/// Transfer array of fixed-size elements from one stream to another.
/// </summary>
/// <param name="inStream">Input stream.</param>
/// <param name="outStream">Output stream.</param>
/// <param name="elemSize">Element size.</param>
private static void TransferArray(BinaryHeapStream inStream, IBinaryStream outStream,
int elemSize)
{
int len = inStream.ReadInt();
outStream.WriteInt(len);
TransferBytes(inStream, outStream, elemSize * len);
}
/// <summary>
/// Create empty binary object from descriptor.
/// </summary>
/// <param name="desc">Descriptor.</param>
/// <returns>Empty binary object.</returns>
private BinaryObject BinaryFromDescriptor(IBinaryTypeDescriptor desc)
{
const int len = BinaryObjectHeader.Size;
var flags = desc.UserType ? BinaryObjectHeader.Flag.UserType : BinaryObjectHeader.Flag.None;
if (_binary.Marshaller.CompactFooter && desc.UserType)
flags |= BinaryObjectHeader.Flag.CompactFooter;
var hdr = new BinaryObjectHeader(desc.TypeId, 0, len, 0, len, flags);
using (var stream = new BinaryHeapStream(len))
{
BinaryObjectHeader.Write(hdr, stream, 0);
return new BinaryObject(_binary.Marshaller, stream.InternalArray, 0, hdr);
}
}
/// <summary>
/// Mutation context.
/// </summary>
private class Context
{
/** Map from object position in old binary to position in new binary. */
private IDictionary<int, int> _oldToNew;
/** Parent context. */
private readonly Context _parent;
/** Binary writer. */
private readonly BinaryWriter _writer;
/** Children contexts. */
private ICollection<Context> _children;
/** Closed flag; if context is closed, it can no longer be used. */
private bool _closed;
/// <summary>
/// Constructor for parent context where writer invocation is not expected.
/// </summary>
public Context()
{
// No-op.
}
/// <summary>
/// Constructor for parent context.
/// </summary>
/// <param name="writer">Writer</param>
public Context(BinaryWriter writer)
{
_writer = writer;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="parent">Parent context.</param>
public Context(Context parent)
{
_parent = parent;
_writer = parent._writer;
if (parent._children == null)
parent._children = new List<Context>();
parent._children.Add(this);
}
/// <summary>
/// Add another old-to-new position mapping.
/// </summary>
/// <param name="oldPos">Old position.</param>
/// <param name="newPos">New position.</param>
/// <param name="hndPos">Handle position.</param>
/// <returns><c>True</c> if ampping was added, <c>false</c> if mapping already existed and handle
/// position in the new object is returned.</returns>
public bool AddOldToNew(int oldPos, int newPos, out int hndPos)
{
if (_oldToNew == null)
_oldToNew = new Dictionary<int, int>();
if (_oldToNew.TryGetValue(oldPos, out hndPos))
return false;
_oldToNew[oldPos] = newPos;
return true;
}
/// <summary>
/// Get mapping of old position to the new one.
/// </summary>
/// <param name="oldPos">Old position.</param>
/// <param name="newPos">New position.</param>
/// <returns><c>True</c> if mapping exists.</returns>
public bool OldToNew(int oldPos, out int newPos)
{
return _oldToNew.TryGetValue(oldPos, out newPos);
}
/// <summary>
/// Writer.
/// </summary>
public BinaryWriter Writer
{
get { return _writer; }
}
/// <summary>
/// Closed flag.
/// </summary>
public bool Closed
{
get
{
return _closed;
}
set
{
Context ctx = this;
while (ctx != null)
{
ctx._closed = value;
if (_children != null) {
foreach (Context child in _children)
child.Closed = value;
}
ctx = ctx._parent;
}
}
}
}
}
}
| |
/*
* 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 OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using System;
using System.Collections.Generic;
namespace OpenSim.Region.ScriptEngine.Shared.Api.Plugins
{
public class SensorRepeat
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public AsyncCommandManager m_CmdManager;
private const int ACTIVE = 2;
private const int AGENT = 1;
private const int AGENT_BY_USERNAME = 0x10;
private const int NPC = 0x20;
private const int OS_NPC = 0x01000000;
private const int PASSIVE = 4;
private const int SCRIPTED = 8;
private INPCModule m_npcModule;
private double maximumRange = 96.0;
private int maximumToReturn = 16;
private Object SenseLock = new Object();
/// <summary>
/// Sensors to process.
/// </summary>
/// <remarks>
/// Do not add or remove sensors from this list directly. Instead, copy the list and substitute the updated
/// copy. This is to avoid locking the list for the duration of the sensor sweep, which increases the danger
/// of deadlocks with future code updates.
///
/// Always lock SenseRepeatListLock when updating this list.
/// </remarks>
private List<SensorInfo> SenseRepeaters = new List<SensorInfo>();
private object SenseRepeatListLock = new object();
public SensorRepeat(AsyncCommandManager CmdManager)
{
m_CmdManager = CmdManager;
maximumRange = CmdManager.m_ScriptEngine.Config.GetDouble("SensorMaxRange", 96.0d);
maximumToReturn = CmdManager.m_ScriptEngine.Config.GetInt("SensorMaxResults", 16);
m_npcModule = m_CmdManager.m_ScriptEngine.World.RequestModuleInterface<INPCModule>();
}
/// <summary>
/// Number of sensors active.
/// </summary>
public int SensorsCount
{
get
{
return SenseRepeaters.Count;
}
}
public void CheckSenseRepeaterEvents()
{
// Go through all timers
foreach (SensorInfo ts in SenseRepeaters)
{
// Time has passed?
if (ts.next.ToUniversalTime() < DateTime.Now.ToUniversalTime())
{
SensorSweep(ts);
// set next interval
ts.next = DateTime.Now.ToUniversalTime().AddSeconds(ts.interval);
}
}
}
public void CreateFromData(uint localID, UUID itemID, UUID objectID,
Object[] data)
{
SceneObjectPart part =
m_CmdManager.m_ScriptEngine.World.GetSceneObjectPart(
objectID);
if (part == null)
return;
int idx = 0;
while (idx < data.Length)
{
SensorInfo ts = new SensorInfo();
ts.localID = localID;
ts.itemID = itemID;
ts.interval = (double)data[idx];
ts.name = (string)data[idx + 1];
ts.keyID = (UUID)data[idx + 2];
ts.type = (int)data[idx + 3];
ts.range = (double)data[idx + 4];
ts.arc = (double)data[idx + 5];
ts.host = part;
ts.next =
DateTime.Now.ToUniversalTime().AddSeconds(ts.interval);
AddSenseRepeater(ts);
idx += 6;
}
}
public List<SensorInfo> GetSensorInfo()
{
List<SensorInfo> retList = new List<SensorInfo>();
lock (SenseRepeatListLock)
{
foreach (SensorInfo i in SenseRepeaters)
retList.Add(i.Clone());
}
return retList;
}
public Object[] GetSerializationData(UUID itemID)
{
List<Object> data = new List<Object>();
foreach (SensorInfo ts in SenseRepeaters)
{
if (ts.itemID == itemID)
{
data.Add(ts.interval);
data.Add(ts.name);
data.Add(ts.keyID);
data.Add(ts.type);
data.Add(ts.range);
data.Add(ts.arc);
}
}
return data.ToArray();
}
public void SenseOnce(uint m_localID, UUID m_itemID,
string name, UUID keyID, int type,
double range, double arc, SceneObjectPart host)
{
// Add to timer
SensorInfo ts = new SensorInfo();
ts.localID = m_localID;
ts.itemID = m_itemID;
ts.interval = 0;
ts.name = name;
ts.keyID = keyID;
ts.type = type;
if (range > maximumRange)
ts.range = maximumRange;
else
ts.range = range;
ts.arc = arc;
ts.host = host;
SensorSweep(ts);
}
public void SetSenseRepeatEvent(uint m_localID, UUID m_itemID,
string name, UUID keyID, int type, double range,
double arc, double sec, SceneObjectPart host)
{
// Always remove first, in case this is a re-set
UnSetSenseRepeaterEvents(m_localID, m_itemID);
if (sec == 0) // Disabling timer
return;
// Add to timer
SensorInfo ts = new SensorInfo();
ts.localID = m_localID;
ts.itemID = m_itemID;
ts.interval = sec;
ts.name = name;
ts.keyID = keyID;
ts.type = type;
if (range > maximumRange)
ts.range = maximumRange;
else
ts.range = range;
ts.arc = arc;
ts.host = host;
ts.next = DateTime.Now.ToUniversalTime().AddSeconds(ts.interval);
AddSenseRepeater(ts);
}
public void UnSetSenseRepeaterEvents(uint m_localID, UUID m_itemID)
{
// Remove from timer
lock (SenseRepeatListLock)
{
List<SensorInfo> newSenseRepeaters = new List<SensorInfo>();
foreach (SensorInfo ts in SenseRepeaters)
{
if (ts.localID != m_localID || ts.itemID != m_itemID)
{
newSenseRepeaters.Add(ts);
}
}
SenseRepeaters = newSenseRepeaters;
}
}
private void AddSenseRepeater(SensorInfo senseRepeater)
{
lock (SenseRepeatListLock)
{
List<SensorInfo> newSenseRepeaters = new List<SensorInfo>(SenseRepeaters);
newSenseRepeaters.Add(senseRepeater);
SenseRepeaters = newSenseRepeaters;
}
}
private List<SensedEntity> doAgentSensor(SensorInfo ts)
{
List<SensedEntity> sensedEntities = new List<SensedEntity>();
// If nobody about quit fast
if (m_CmdManager.m_ScriptEngine.World.GetRootAgentCount() == 0)
return sensedEntities;
SceneObjectPart SensePoint = ts.host;
Vector3 fromRegionPos = SensePoint.GetWorldPosition();
Quaternion q = SensePoint.GetWorldRotation();
if (SensePoint.ParentGroup.IsAttachment)
{
// In attachments, rotate the sensor cone with the
// avatar rotation. This may include a nonzero elevation if
// in mouselook.
// This will not include the rotation and position of the
// attachment point (e.g. your head when a sensor is in your
// hair attached to your scull. Your hair will turn with
// your head but the sensor will stay with your (global)
// avatar rotation and position.
// Position of a sensor in a child prim attached to an avatar
// will be still wrong.
ScenePresence avatar = m_CmdManager.m_ScriptEngine.World.GetScenePresence(SensePoint.ParentGroup.AttachedAvatar);
// Don't proceed if the avatar for this attachment has since been removed from the scene.
if (avatar == null)
return sensedEntities;
q = avatar.GetWorldRotation() * q;
}
LSL_Types.Quaternion r = new LSL_Types.Quaternion(q);
LSL_Types.Vector3 forward_dir = (new LSL_Types.Vector3(1, 0, 0) * r);
double mag_fwd = LSL_Types.Vector3.Mag(forward_dir);
bool attached = (SensePoint.ParentGroup.AttachmentPoint != 0);
Vector3 toRegionPos;
double dis;
Action<ScenePresence> senseEntity = new Action<ScenePresence>(presence =>
{
// m_log.DebugFormat(
// "[SENSOR REPEAT]: Inspecting scene presence {0}, type {1} on sensor sweep for {2}, type {3}",
// presence.Name, presence.PresenceType, ts.name, ts.type);
if ((ts.type & NPC) == 0 && (ts.type & OS_NPC) == 0 && presence.PresenceType == PresenceType.Npc)
{
INPC npcData = m_npcModule.GetNPC(presence.UUID, presence.Scene);
if (npcData == null || !npcData.SenseAsAgent)
{
// m_log.DebugFormat(
// "[SENSOR REPEAT]: Discarding NPC {0} from agent sense sweep for script item id {1}",
// presence.Name, ts.itemID);
return;
}
}
if ((ts.type & AGENT) == 0)
{
if (presence.PresenceType == PresenceType.User)
{
return;
}
else
{
INPC npcData = m_npcModule.GetNPC(presence.UUID, presence.Scene);
if (npcData != null && npcData.SenseAsAgent)
{
// m_log.DebugFormat(
// "[SENSOR REPEAT]: Discarding NPC {0} from non-agent sense sweep for script item id {1}",
// presence.Name, ts.itemID);
return;
}
}
}
if (presence.IsDeleted || presence.IsChildAgent || presence.GodLevel > 0.0)
return;
// if the object the script is in is attached and the avatar is the owner
// then this one is not wanted
if (attached && presence.UUID == SensePoint.OwnerID)
return;
toRegionPos = presence.AbsolutePosition;
dis = Math.Abs(Util.GetDistanceTo(toRegionPos, fromRegionPos));
// Disabled for now since all osNpc* methods check for appropriate ownership permission.
// Perhaps could be re-enabled as an NPC setting at some point since being able to make NPCs not
// sensed might be useful.
// if (presence.PresenceType == PresenceType.Npc && npcModule != null)
// {
// UUID npcOwner = npcModule.GetOwner(presence.UUID);
// if (npcOwner != UUID.Zero && npcOwner != SensePoint.OwnerID)
// return;
// }
// are they in range
if (dis <= ts.range)
{
// Are they in the required angle of view
if (ts.arc < Math.PI)
{
// not omni-directional. Can you see it ?
// vec forward_dir = llRot2Fwd(llGetRot())
// vec obj_dir = toRegionPos-fromRegionPos
// dot=dot(forward_dir,obj_dir)
// mag_fwd = mag(forward_dir)
// mag_obj = mag(obj_dir)
// ang = acos(dot /(mag_fwd*mag_obj))
double ang_obj = 0;
try
{
LSL_Types.Vector3 obj_dir = new LSL_Types.Vector3(
toRegionPos - fromRegionPos);
double dot = LSL_Types.Vector3.Dot(forward_dir, obj_dir);
double mag_obj = LSL_Types.Vector3.Mag(obj_dir);
ang_obj = Math.Acos(dot / (mag_fwd * mag_obj));
}
catch
{
}
if (ang_obj <= ts.arc)
{
sensedEntities.Add(new SensedEntity(dis, presence.UUID));
}
}
else
{
sensedEntities.Add(new SensedEntity(dis, presence.UUID));
}
}
});
// If this is an avatar sense by key try to get them directly
// rather than getting a list to scan through
if (ts.keyID != UUID.Zero)
{
ScenePresence sp;
// Try direct lookup by UUID
if (!m_CmdManager.m_ScriptEngine.World.TryGetScenePresence(ts.keyID, out sp))
return sensedEntities;
senseEntity(sp);
}
else if (!string.IsNullOrEmpty(ts.name))
{
ScenePresence sp;
// Try lookup by name will return if/when found
if (((ts.type & AGENT) != 0) && m_CmdManager.m_ScriptEngine.World.TryGetAvatarByName(ts.name, out sp))
senseEntity(sp);
if ((ts.type & AGENT_BY_USERNAME) != 0)
{
m_CmdManager.m_ScriptEngine.World.ForEachRootScenePresence(
delegate(ScenePresence ssp)
{
if (ssp.Lastname == "Resident")
{
if (ssp.Firstname.ToLower() == ts.name)
senseEntity(ssp);
return;
}
if (ssp.Name.Replace(" ", ".").ToLower() == ts.name)
senseEntity(ssp);
}
);
}
return sensedEntities;
}
else
{
m_CmdManager.m_ScriptEngine.World.ForEachRootScenePresence(senseEntity);
}
return sensedEntities;
}
private List<SensedEntity> doObjectSensor(SensorInfo ts)
{
List<EntityBase> Entities;
List<SensedEntity> sensedEntities = new List<SensedEntity>();
// If this is an object sense by key try to get it directly
// rather than getting a list to scan through
if (ts.keyID != UUID.Zero)
{
EntityBase e = null;
m_CmdManager.m_ScriptEngine.World.Entities.TryGetValue(ts.keyID, out e);
if (e == null)
return sensedEntities;
Entities = new List<EntityBase>();
Entities.Add(e);
}
else
{
Entities = new List<EntityBase>(m_CmdManager.m_ScriptEngine.World.GetEntities());
}
SceneObjectPart SensePoint = ts.host;
Vector3 fromRegionPos = SensePoint.GetWorldPosition();
// pre define some things to avoid repeated definitions in the loop body
Vector3 toRegionPos;
double dis;
int objtype;
SceneObjectPart part;
float dx;
float dy;
float dz;
Quaternion q = SensePoint.GetWorldRotation();
if (SensePoint.ParentGroup.IsAttachment)
{
// In attachments, rotate the sensor cone with the
// avatar rotation. This may include a nonzero elevation if
// in mouselook.
// This will not include the rotation and position of the
// attachment point (e.g. your head when a sensor is in your
// hair attached to your scull. Your hair will turn with
// your head but the sensor will stay with your (global)
// avatar rotation and position.
// Position of a sensor in a child prim attached to an avatar
// will be still wrong.
ScenePresence avatar = m_CmdManager.m_ScriptEngine.World.GetScenePresence(SensePoint.ParentGroup.AttachedAvatar);
// Don't proceed if the avatar for this attachment has since been removed from the scene.
if (avatar == null)
return sensedEntities;
q = avatar.GetWorldRotation() * q;
}
LSL_Types.Quaternion r = new LSL_Types.Quaternion(q);
LSL_Types.Vector3 forward_dir = (new LSL_Types.Vector3(1, 0, 0) * r);
double mag_fwd = LSL_Types.Vector3.Mag(forward_dir);
Vector3 ZeroVector = new Vector3(0, 0, 0);
bool nameSearch = !string.IsNullOrEmpty(ts.name);
foreach (EntityBase ent in Entities)
{
bool keep = true;
if (nameSearch && ent.Name != ts.name) // Wrong name and it is a named search
continue;
if (ent.IsDeleted) // taken so long to do this it has gone from the scene
continue;
if (!(ent is SceneObjectGroup)) // dont bother if it is a pesky avatar
continue;
toRegionPos = ent.AbsolutePosition;
// Calculation is in line for speed
dx = toRegionPos.X - fromRegionPos.X;
dy = toRegionPos.Y - fromRegionPos.Y;
dz = toRegionPos.Z - fromRegionPos.Z;
// Weed out those that will not fit in a cube the size of the range
// no point calculating if they are within a sphere the size of the range
// if they arent even in the cube
if (Math.Abs(dx) > ts.range || Math.Abs(dy) > ts.range || Math.Abs(dz) > ts.range)
dis = ts.range + 1.0;
else
dis = Math.Sqrt(dx * dx + dy * dy + dz * dz);
if (keep && dis <= ts.range && ts.host.UUID != ent.UUID)
{
// In Range and not the object containing the script, is it the right Type ?
objtype = 0;
part = ((SceneObjectGroup)ent).RootPart;
if (part.ParentGroup.AttachmentPoint != 0) // Attached so ignore
continue;
if (part.Inventory.ContainsScripts())
{
objtype |= ACTIVE | SCRIPTED; // Scripted and active. It COULD have one hidden ...
}
else
{
if (ent.Velocity.Equals(ZeroVector))
{
objtype |= PASSIVE; // Passive non-moving
}
else
{
objtype |= ACTIVE; // moving so active
}
}
// If any of the objects attributes match any in the requested scan type
if (((ts.type & objtype) != 0))
{
// Right type too, what about the other params , key and name ?
if (ts.arc < Math.PI)
{
// not omni-directional. Can you see it ?
// vec forward_dir = llRot2Fwd(llGetRot())
// vec obj_dir = toRegionPos-fromRegionPos
// dot=dot(forward_dir,obj_dir)
// mag_fwd = mag(forward_dir)
// mag_obj = mag(obj_dir)
// ang = acos(dot /(mag_fwd*mag_obj))
double ang_obj = 0;
try
{
Vector3 diff = toRegionPos - fromRegionPos;
double dot = LSL_Types.Vector3.Dot(forward_dir, diff);
double mag_obj = LSL_Types.Vector3.Mag(diff);
ang_obj = Math.Acos(dot / (mag_fwd * mag_obj));
}
catch
{
}
if (ang_obj > ts.arc) keep = false;
}
if (keep == true)
{
// add distance for sorting purposes later
sensedEntities.Add(new SensedEntity(dis, ent.UUID));
}
}
}
}
return sensedEntities;
}
private void SensorSweep(SensorInfo ts)
{
if (ts.host == null)
{
return;
}
List<SensedEntity> sensedEntities = new List<SensedEntity>();
// Is the sensor type is AGENT and not SCRIPTED then include agents
if ((ts.type & (AGENT | AGENT_BY_USERNAME | NPC | OS_NPC)) != 0 && (ts.type & SCRIPTED) == 0)
{
sensedEntities.AddRange(doAgentSensor(ts));
}
// If SCRIPTED or PASSIVE or ACTIVE check objects
if ((ts.type & SCRIPTED) != 0 || (ts.type & PASSIVE) != 0 || (ts.type & ACTIVE) != 0)
{
sensedEntities.AddRange(doObjectSensor(ts));
}
lock (SenseLock)
{
if (sensedEntities.Count == 0)
{
// send a "no_sensor"
// Add it to queue
m_CmdManager.m_ScriptEngine.PostScriptEvent(ts.itemID,
new EventParams("no_sensor", new Object[0],
new DetectParams[0]));
}
else
{
// Sort the list to get everything ordered by distance
sensedEntities.Sort();
int count = sensedEntities.Count;
int idx;
List<DetectParams> detected = new List<DetectParams>();
for (idx = 0; idx < count; idx++)
{
try
{
DetectParams detect = new DetectParams();
detect.Key = sensedEntities[idx].itemID;
detect.Populate(m_CmdManager.m_ScriptEngine.World);
detected.Add(detect);
}
catch (Exception)
{
// Ignore errors, the object has been deleted or the avatar has gone and
// there was a problem in detect.Populate so nothing added to the list
}
if (detected.Count == maximumToReturn)
break;
}
if (detected.Count == 0)
{
// To get here with zero in the list there must have been some sort of problem
// like the object being deleted or the avatar leaving to have caused some
// difficulty during the Populate above so fire a no_sensor event
m_CmdManager.m_ScriptEngine.PostScriptEvent(ts.itemID,
new EventParams("no_sensor", new Object[0],
new DetectParams[0]));
}
else
{
m_CmdManager.m_ScriptEngine.PostScriptEvent(ts.itemID,
new EventParams("sensor",
new Object[] { new LSL_Types.LSLInteger(detected.Count) },
detected.ToArray()));
}
}
}
}
/// <summary>
/// Used by one-off and repeated sensors
/// </summary>
public class SensorInfo
{
public double arc;
public SceneObjectPart host;
public double interval;
public UUID itemID;
public UUID keyID;
public uint localID;
public string name;
public DateTime next;
public double range;
public int type;
public SensorInfo Clone()
{
return (SensorInfo)this.MemberwiseClone();
}
}
//
// Sensed entity
//
private class SensedEntity : IComparable
{
public double distance;
public UUID itemID;
public SensedEntity(double detectedDistance, UUID detectedID)
{
distance = detectedDistance;
itemID = detectedID;
}
public int CompareTo(object obj)
{
if (!(obj is SensedEntity)) throw new InvalidOperationException();
SensedEntity ent = (SensedEntity)obj;
if (ent == null || ent.distance < distance) return 1;
if (ent.distance > distance) return -1;
return 0;
}
}
}
}
| |
// DeflaterEngine.cs
//
// Copyright (C) 2001 Mike Krueger
// Copyright (C) 2004 John Reilly
//
// This file was translated from java, it was part of the GNU Classpath
// Copyright (C) 2001 Free Software Foundation, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
using System;
using PdfSharp.SharpZipLib.Checksums;
// ReSharper disable RedundantThisQualifier
namespace PdfSharp.SharpZipLib.Zip.Compression
{
/// <summary>
/// Strategies for deflater
/// </summary>
internal enum DeflateStrategy
{
/// <summary>
/// The default strategy
/// </summary>
Default = 0,
/// <summary>
/// This strategy will only allow longer string repetitions. It is
/// useful for random data with a small character set.
/// </summary>
Filtered = 1,
/// <summary>
/// This strategy will not look for string repetitions at all. It
/// only encodes with Huffman trees (which means, that more common
/// characters get a smaller encoding.
/// </summary>
HuffmanOnly = 2
}
// DEFLATE ALGORITHM:
//
// The uncompressed stream is inserted into the window array. When
// the window array is full the first half is thrown away and the
// second half is copied to the beginning.
//
// The head array is a hash table. Three characters build a hash value
// and they the value points to the corresponding index in window of
// the last string with this hash. The prev array implements a
// linked list of matches with the same hash: prev[index & WMASK] points
// to the previous index with the same hash.
//
/// <summary>
/// Low level compression engine for deflate algorithm which uses a 32K sliding window
/// with secondary compression from Huffman/Shannon-Fano codes.
/// </summary>
internal class DeflaterEngine : DeflaterConstants
{
#region Constants
const int TooFar = 4096;
#endregion
#region Constructors
/// <summary>
/// Construct instance with pending buffer
/// </summary>
/// <param name="pending">
/// Pending buffer to use
/// </param>>
public DeflaterEngine(DeflaterPending pending)
{
this.pending = pending;
huffman = new DeflaterHuffman(pending);
adler = new Adler32();
window = new byte[2 * WSIZE];
head = new short[HASH_SIZE];
prev = new short[WSIZE];
// We start at index 1, to avoid an implementation deficiency, that
// we cannot build a repeat pattern at index 0.
blockStart = strstart = 1;
}
#endregion
/// <summary>
/// Deflate drives actual compression of data
/// </summary>
/// <param name="flush">True to flush input buffers</param>
/// <param name="finish">Finish deflation with the current input.</param>
/// <returns>Returns true if progress has been made.</returns>
public bool Deflate(bool flush, bool finish)
{
bool progress;
do
{
FillWindow();
bool canFlush = flush && (inputOff == inputEnd);
#if DebugDeflation
if (DeflaterConstants.DEBUGGING) {
Console.WriteLine("window: [" + blockStart + "," + strstart + ","
+ lookahead + "], " + compressionFunction + "," + canFlush);
}
#endif
switch (compressionFunction)
{
case DEFLATE_STORED:
progress = DeflateStored(canFlush, finish);
break;
case DEFLATE_FAST:
progress = DeflateFast(canFlush, finish);
break;
case DEFLATE_SLOW:
progress = DeflateSlow(canFlush, finish);
break;
default:
throw new InvalidOperationException("unknown compressionFunction");
}
} while (pending.IsFlushed && progress); // repeat while we have no pending output and progress was made
return progress;
}
/// <summary>
/// Sets input data to be deflated. Should only be called when <code>NeedsInput()</code>
/// returns true
/// </summary>
/// <param name="buffer">The buffer containing input data.</param>
/// <param name="offset">The offset of the first byte of data.</param>
/// <param name="count">The number of bytes of data to use as input.</param>
public void SetInput(byte[] buffer, int offset, int count)
{
if (buffer == null)
{
throw new ArgumentNullException("buffer");
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException("offset");
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count");
}
if (inputOff < inputEnd)
{
throw new InvalidOperationException("Old input was not completely processed");
}
int end = offset + count;
/* We want to throw an ArrayIndexOutOfBoundsException early. The
* check is very tricky: it also handles integer wrap around.
*/
if ((offset > end) || (end > buffer.Length))
{
throw new ArgumentOutOfRangeException("count");
}
inputBuf = buffer;
inputOff = offset;
inputEnd = end;
}
/// <summary>
/// Determines if more <see cref="SetInput">input</see> is needed.
/// </summary>
/// <returns>Return true if input is needed via <see cref="SetInput">SetInput</see></returns>
public bool NeedsInput()
{
return (inputEnd == inputOff);
}
/// <summary>
/// Set compression dictionary
/// </summary>
/// <param name="buffer">The buffer containing the dictionary data</param>
/// <param name="offset">The offset in the buffer for the first byte of data</param>
/// <param name="length">The length of the dictionary data.</param>
public void SetDictionary(byte[] buffer, int offset, int length)
{
#if DebugDeflation
if (DeflaterConstants.DEBUGGING && (strstart != 1) )
{
throw new InvalidOperationException("strstart not 1");
}
#endif
adler.Update(buffer, offset, length);
if (length < MIN_MATCH)
{
return;
}
if (length > MAX_DIST)
{
offset += length - MAX_DIST;
length = MAX_DIST;
}
System.Array.Copy(buffer, offset, window, strstart, length);
UpdateHash();
--length;
while (--length > 0)
{
InsertString();
strstart++;
}
strstart += 2;
blockStart = strstart;
}
/// <summary>
/// Reset internal state
/// </summary>
public void Reset()
{
huffman.Reset();
adler.Reset();
blockStart = strstart = 1;
lookahead = 0;
totalIn = 0;
prevAvailable = false;
matchLen = MIN_MATCH - 1;
for (int i = 0; i < HASH_SIZE; i++)
{
head[i] = 0;
}
for (int i = 0; i < WSIZE; i++)
{
prev[i] = 0;
}
}
/// <summary>
/// Reset Adler checksum
/// </summary>
public void ResetAdler()
{
adler.Reset();
}
/// <summary>
/// Get current value of Adler checksum
/// </summary>
public int Adler
{
get
{
return unchecked((int)adler.Value);
}
}
/// <summary>
/// Total data processed
/// </summary>
public long TotalIn
{
get
{
return totalIn;
}
}
/// <summary>
/// Get/set the <see cref="DeflateStrategy">deflate strategy</see>
/// </summary>
public DeflateStrategy Strategy
{
get
{
return strategy;
}
set
{
strategy = value;
}
}
/// <summary>
/// Set the deflate level (0-9)
/// </summary>
/// <param name="level">The value to set the level to.</param>
public void SetLevel(int level)
{
if ((level < 0) || (level > 9))
{
throw new ArgumentOutOfRangeException("level");
}
goodLength = DeflaterConstants.GOOD_LENGTH[level];
max_lazy = DeflaterConstants.MAX_LAZY[level];
niceLength = DeflaterConstants.NICE_LENGTH[level];
max_chain = DeflaterConstants.MAX_CHAIN[level];
if (DeflaterConstants.COMPR_FUNC[level] != compressionFunction)
{
#if DebugDeflation
if (DeflaterConstants.DEBUGGING) {
Console.WriteLine("Change from " + compressionFunction + " to "
+ DeflaterConstants.COMPR_FUNC[level]);
}
#endif
switch (compressionFunction)
{
case DEFLATE_STORED:
if (strstart > blockStart)
{
huffman.FlushStoredBlock(window, blockStart,
strstart - blockStart, false);
blockStart = strstart;
}
UpdateHash();
break;
case DEFLATE_FAST:
if (strstart > blockStart)
{
huffman.FlushBlock(window, blockStart, strstart - blockStart,
false);
blockStart = strstart;
}
break;
case DEFLATE_SLOW:
if (prevAvailable)
{
huffman.TallyLit(window[strstart - 1] & 0xff);
}
if (strstart > blockStart)
{
huffman.FlushBlock(window, blockStart, strstart - blockStart, false);
blockStart = strstart;
}
prevAvailable = false;
matchLen = MIN_MATCH - 1;
break;
}
compressionFunction = COMPR_FUNC[level];
}
}
/// <summary>
/// Fill the window
/// </summary>
public void FillWindow()
{
/* If the window is almost full and there is insufficient lookahead,
* move the upper half to the lower one to make room in the upper half.
*/
if (strstart >= WSIZE + MAX_DIST)
{
SlideWindow();
}
/* If there is not enough lookahead, but still some input left,
* read in the input
*/
while (lookahead < DeflaterConstants.MIN_LOOKAHEAD && inputOff < inputEnd)
{
int more = 2 * WSIZE - lookahead - strstart;
if (more > inputEnd - inputOff)
{
more = inputEnd - inputOff;
}
System.Array.Copy(inputBuf, inputOff, window, strstart + lookahead, more);
adler.Update(inputBuf, inputOff, more);
inputOff += more;
totalIn += more;
lookahead += more;
}
if (lookahead >= MIN_MATCH)
{
UpdateHash();
}
}
void UpdateHash()
{
/*
if (DEBUGGING) {
Console.WriteLine("updateHash: "+strstart);
}
*/
ins_h = (window[strstart] << HASH_SHIFT) ^ window[strstart + 1];
}
/// <summary>
/// Inserts the current string in the head hash and returns the previous
/// value for this hash.
/// </summary>
/// <returns>The previous hash value</returns>
int InsertString()
{
short match;
int hash = ((ins_h << HASH_SHIFT) ^ window[strstart + (MIN_MATCH - 1)]) & HASH_MASK;
#if DebugDeflation
if (DeflaterConstants.DEBUGGING)
{
if (hash != (((window[strstart] << (2*HASH_SHIFT)) ^
(window[strstart + 1] << HASH_SHIFT) ^
(window[strstart + 2])) & HASH_MASK)) {
throw new SharpZipBaseException("hash inconsistent: " + hash + "/"
+window[strstart] + ","
+window[strstart + 1] + ","
+window[strstart + 2] + "," + HASH_SHIFT);
}
}
#endif
prev[strstart & WMASK] = match = head[hash];
head[hash] = unchecked((short)strstart);
ins_h = hash;
return match & 0xffff;
}
void SlideWindow()
{
Array.Copy(window, WSIZE, window, 0, WSIZE);
matchStart -= WSIZE;
strstart -= WSIZE;
blockStart -= WSIZE;
// Slide the hash table (could be avoided with 32 bit values
// at the expense of memory usage).
for (int i = 0; i < HASH_SIZE; ++i)
{
int m = head[i] & 0xffff;
head[i] = (short)(m >= WSIZE ? (m - WSIZE) : 0);
}
// Slide the prev table.
for (int i = 0; i < WSIZE; i++)
{
int m = prev[i] & 0xffff;
prev[i] = (short)(m >= WSIZE ? (m - WSIZE) : 0);
}
}
/// <summary>
/// Find the best (longest) string in the window matching the
/// string starting at strstart.
///
/// Preconditions:
/// <code>
/// strstart + MAX_MATCH <= window.length.</code>
/// </summary>
/// <param name="curMatch"></param>
/// <returns>True if a match greater than the minimum length is found</returns>
bool FindLongestMatch(int curMatch)
{
int chainLength = this.max_chain;
int niceLength = this.niceLength;
short[] prev = this.prev;
int scan = this.strstart;
int match;
int best_end = this.strstart + matchLen;
int best_len = Math.Max(matchLen, MIN_MATCH - 1);
int limit = Math.Max(strstart - MAX_DIST, 0);
int strend = strstart + MAX_MATCH - 1;
byte scan_end1 = window[best_end - 1];
byte scan_end = window[best_end];
// Do not waste too much time if we already have a good match:
if (best_len >= this.goodLength)
{
chainLength >>= 2;
}
/* Do not look for matches beyond the end of the input. This is necessary
* to make deflate deterministic.
*/
if (niceLength > lookahead)
{
niceLength = lookahead;
}
#if DebugDeflation
if (DeflaterConstants.DEBUGGING && (strstart > 2 * WSIZE - MIN_LOOKAHEAD))
{
throw new InvalidOperationException("need lookahead");
}
#endif
do
{
#if DebugDeflation
if (DeflaterConstants.DEBUGGING && (curMatch >= strstart) )
{
throw new InvalidOperationException("no future");
}
#endif
if (window[curMatch + best_len] != scan_end ||
window[curMatch + best_len - 1] != scan_end1 ||
window[curMatch] != window[scan] ||
window[curMatch + 1] != window[scan + 1])
{
continue;
}
match = curMatch + 2;
scan += 2;
/* We check for insufficient lookahead only every 8th comparison;
* the 256th check will be made at strstart + 258.
*/
while (
window[++scan] == window[++match] &&
window[++scan] == window[++match] &&
window[++scan] == window[++match] &&
window[++scan] == window[++match] &&
window[++scan] == window[++match] &&
window[++scan] == window[++match] &&
window[++scan] == window[++match] &&
window[++scan] == window[++match] &&
(scan < strend))
{
// Do nothing
}
if (scan > best_end)
{
#if DebugDeflation
if (DeflaterConstants.DEBUGGING && (ins_h == 0) )
Console.Error.WriteLine("Found match: " + curMatch + "-" + (scan - strstart));
#endif
matchStart = curMatch;
best_end = scan;
best_len = scan - strstart;
if (best_len >= niceLength)
{
break;
}
scan_end1 = window[best_end - 1];
scan_end = window[best_end];
}
scan = strstart;
} while ((curMatch = (prev[curMatch & WMASK] & 0xffff)) > limit && --chainLength != 0);
matchLen = Math.Min(best_len, lookahead);
return matchLen >= MIN_MATCH;
}
bool DeflateStored(bool flush, bool finish)
{
if (!flush && (lookahead == 0))
{
return false;
}
strstart += lookahead;
lookahead = 0;
int storedLength = strstart - blockStart;
if ((storedLength >= DeflaterConstants.MAX_BLOCK_SIZE) || // Block is full
(blockStart < WSIZE && storedLength >= MAX_DIST) || // Block may move out of window
flush)
{
bool lastBlock = finish;
if (storedLength > DeflaterConstants.MAX_BLOCK_SIZE)
{
storedLength = DeflaterConstants.MAX_BLOCK_SIZE;
lastBlock = false;
}
#if DebugDeflation
if (DeflaterConstants.DEBUGGING)
{
Console.WriteLine("storedBlock[" + storedLength + "," + lastBlock + "]");
}
#endif
huffman.FlushStoredBlock(window, blockStart, storedLength, lastBlock);
blockStart += storedLength;
return !lastBlock;
}
return true;
}
bool DeflateFast(bool flush, bool finish)
{
if (lookahead < MIN_LOOKAHEAD && !flush)
{
return false;
}
while (lookahead >= MIN_LOOKAHEAD || flush)
{
if (lookahead == 0)
{
// We are flushing everything
huffman.FlushBlock(window, blockStart, strstart - blockStart, finish);
blockStart = strstart;
return false;
}
if (strstart > 2 * WSIZE - MIN_LOOKAHEAD)
{
/* slide window, as FindLongestMatch needs this.
* This should only happen when flushing and the window
* is almost full.
*/
SlideWindow();
}
int hashHead;
if (lookahead >= MIN_MATCH &&
(hashHead = InsertString()) != 0 &&
strategy != DeflateStrategy.HuffmanOnly &&
strstart - hashHead <= MAX_DIST &&
FindLongestMatch(hashHead))
{
// longestMatch sets matchStart and matchLen
#if DebugDeflation
if (DeflaterConstants.DEBUGGING)
{
for (int i = 0 ; i < matchLen; i++) {
if (window[strstart + i] != window[matchStart + i]) {
throw new SharpZipBaseException("Match failure");
}
}
}
#endif
bool full = huffman.TallyDist(strstart - matchStart, matchLen);
lookahead -= matchLen;
if (matchLen <= max_lazy && lookahead >= MIN_MATCH)
{
while (--matchLen > 0)
{
++strstart;
InsertString();
}
++strstart;
}
else
{
strstart += matchLen;
if (lookahead >= MIN_MATCH - 1)
{
UpdateHash();
}
}
matchLen = MIN_MATCH - 1;
if (!full)
{
continue;
}
}
else
{
// No match found
huffman.TallyLit(window[strstart] & 0xff);
++strstart;
--lookahead;
}
if (huffman.IsFull())
{
bool lastBlock = finish && (lookahead == 0);
huffman.FlushBlock(window, blockStart, strstart - blockStart, lastBlock);
blockStart = strstart;
return !lastBlock;
}
}
return true;
}
bool DeflateSlow(bool flush, bool finish)
{
if (lookahead < MIN_LOOKAHEAD && !flush)
{
return false;
}
while (lookahead >= MIN_LOOKAHEAD || flush)
{
if (lookahead == 0)
{
if (prevAvailable)
{
huffman.TallyLit(window[strstart - 1] & 0xff);
}
prevAvailable = false;
// We are flushing everything
#if DebugDeflation
if (DeflaterConstants.DEBUGGING && !flush)
{
throw new SharpZipBaseException("Not flushing, but no lookahead");
}
#endif
huffman.FlushBlock(window, blockStart, strstart - blockStart,
finish);
blockStart = strstart;
return false;
}
if (strstart >= 2 * WSIZE - MIN_LOOKAHEAD)
{
/* slide window, as FindLongestMatch needs this.
* This should only happen when flushing and the window
* is almost full.
*/
SlideWindow();
}
int prevMatch = matchStart;
int prevLen = matchLen;
if (lookahead >= MIN_MATCH)
{
int hashHead = InsertString();
if (strategy != DeflateStrategy.HuffmanOnly &&
hashHead != 0 &&
strstart - hashHead <= MAX_DIST &&
FindLongestMatch(hashHead))
{
// longestMatch sets matchStart and matchLen
// Discard match if too small and too far away
if (matchLen <= 5 && (strategy == DeflateStrategy.Filtered || (matchLen == MIN_MATCH && strstart - matchStart > TooFar)))
{
matchLen = MIN_MATCH - 1;
}
}
}
// previous match was better
if ((prevLen >= MIN_MATCH) && (matchLen <= prevLen))
{
#if DebugDeflation
if (DeflaterConstants.DEBUGGING)
{
for (int i = 0 ; i < matchLen; i++) {
if (window[strstart-1+i] != window[prevMatch + i])
throw new SharpZipBaseException();
}
}
#endif
huffman.TallyDist(strstart - 1 - prevMatch, prevLen);
prevLen -= 2;
do
{
strstart++;
lookahead--;
if (lookahead >= MIN_MATCH)
{
InsertString();
}
} while (--prevLen > 0);
strstart++;
lookahead--;
prevAvailable = false;
matchLen = MIN_MATCH - 1;
}
else
{
if (prevAvailable)
{
huffman.TallyLit(window[strstart - 1] & 0xff);
}
prevAvailable = true;
strstart++;
lookahead--;
}
if (huffman.IsFull())
{
int len = strstart - blockStart;
if (prevAvailable)
{
len--;
}
bool lastBlock = (finish && (lookahead == 0) && !prevAvailable);
huffman.FlushBlock(window, blockStart, len, lastBlock);
blockStart += len;
return !lastBlock;
}
}
return true;
}
#region Instance Fields
// Hash index of string to be inserted
int ins_h;
/// <summary>
/// Hashtable, hashing three characters to an index for window, so
/// that window[index]..window[index+2] have this hash code.
/// Note that the array should really be unsigned short, so you need
/// to and the values with 0xffff.
/// </summary>
short[] head;
/// <summary>
/// <code>prev[index & WMASK]</code> points to the previous index that has the
/// same hash code as the string starting at index. This way
/// entries with the same hash code are in a linked list.
/// Note that the array should really be unsigned short, so you need
/// to and the values with 0xffff.
/// </summary>
short[] prev;
int matchStart;
// Length of best match
int matchLen;
// Set if previous match exists
bool prevAvailable;
int blockStart;
/// <summary>
/// Points to the current character in the window.
/// </summary>
int strstart;
/// <summary>
/// lookahead is the number of characters starting at strstart in
/// window that are valid.
/// So window[strstart] until window[strstart+lookahead-1] are valid
/// characters.
/// </summary>
int lookahead;
/// <summary>
/// This array contains the part of the uncompressed stream that
/// is of relevance. The current character is indexed by strstart.
/// </summary>
byte[] window;
DeflateStrategy strategy;
int max_chain, max_lazy, niceLength, goodLength;
/// <summary>
/// The current compression function.
/// </summary>
int compressionFunction;
/// <summary>
/// The input data for compression.
/// </summary>
byte[] inputBuf;
/// <summary>
/// The total bytes of input read.
/// </summary>
long totalIn;
/// <summary>
/// The offset into inputBuf, where input data starts.
/// </summary>
int inputOff;
/// <summary>
/// The end offset of the input data.
/// </summary>
int inputEnd;
DeflaterPending pending;
DeflaterHuffman huffman;
/// <summary>
/// The adler checksum
/// </summary>
Adler32 adler;
#endregion
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Tests.Binary.Serializable
{
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#if !NETCOREAPP // AppDomains are not supported in .NET Core
using System.Reflection;
using System.Reflection.Emit;
#endif
using System.Runtime.Serialization;
using System.Xml;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Compute;
using NUnit.Framework;
/// <summary>
/// Tests additional [Serializable] scenarios.
/// </summary>
public class AdvancedSerializationTest
{
/// <summary>
/// Set up routine.
/// </summary>
[TestFixtureSetUp]
public void SetUp()
{
Ignition.Start(TestUtils.GetTestConfiguration());
}
/// <summary>
/// Tear down routine.
/// </summary>
[TestFixtureTearDown]
public void TearDown()
{
Ignition.StopAll(true);
}
/// <summary>
/// Test complex file serialization.
/// </summary>
[Test]
public void TestSerializableXmlDoc()
{
var grid = Ignition.GetIgnite(null);
var cache = grid.GetOrCreateCache<int, SerializableXmlDoc>("cache");
var doc = new SerializableXmlDoc();
doc.LoadXml("<document><test1>val</test1><test2 attr=\"x\" /></document>");
for (var i = 0; i < 50; i++)
{
// Test cache
cache.Put(i, doc);
var resultDoc = cache.Get(i);
Assert.AreEqual(doc.OuterXml, resultDoc.OuterXml);
// Test task with document arg
CheckTask(grid, doc);
}
}
/// <summary>
/// Checks task execution.
/// </summary>
/// <param name="grid">Grid.</param>
/// <param name="arg">Task arg.</param>
private static void CheckTask(IIgnite grid, object arg)
{
var jobResult = grid.GetCompute().Execute(new CombineStringsTask(), arg);
var nodeCount = grid.GetCluster().GetNodes().Count;
var expectedRes =
CombineStringsTask.CombineStrings(Enumerable.Range(0, nodeCount).Select(x => arg.ToString()));
Assert.AreEqual(expectedRes, jobResult.InnerXml);
}
#if !NETCOREAPP// AppDomains are not supported in .NET Core
/// <summary>
/// Tests custom serialization binder.
/// </summary>
[Test]
public void TestSerializationBinder()
{
const int count = 50;
var cache = Ignition.GetIgnite(null).GetOrCreateCache<int, object>("cache");
// Put multiple objects from multiple same-named assemblies to cache
for (var i = 0; i < count; i++)
{
dynamic val = Activator.CreateInstance(GenerateDynamicType());
val.Id = i;
val.Name = "Name_" + i;
cache.Put(i, val);
}
// Verify correct deserialization
for (var i = 0; i < count; i++)
{
dynamic val = cache.Get(i);
Assert.AreEqual(val.Id, i);
Assert.AreEqual(val.Name, "Name_" + i);
}
}
/// <summary>
/// Generates a Type in runtime, puts it into a dynamic assembly.
/// </summary>
/// <returns></returns>
private static Type GenerateDynamicType()
{
var asmBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(
new AssemblyName("GridSerializationTestDynamicAssembly"), AssemblyBuilderAccess.Run);
var moduleBuilder = asmBuilder.DefineDynamicModule("GridSerializationTestDynamicModule");
var typeBuilder = moduleBuilder.DefineType("GridSerializationTestDynamicType",
TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.Serializable);
typeBuilder.DefineField("Id", typeof (int), FieldAttributes.Public);
typeBuilder.DefineField("Name", typeof (string), FieldAttributes.Public);
return typeBuilder.CreateType();
}
#endif
/// <summary>
/// Tests the DataTable serialization.
/// </summary>
[Test]
public void TestDataTable()
{
var dt = new DataTable("foo");
dt.Columns.Add("intCol", typeof(int));
dt.Columns.Add("stringCol", typeof(string));
dt.Rows.Add(1, "1");
dt.Rows.Add(2, "2");
var cache = Ignition.GetIgnite().GetOrCreateCache<int, DataTable>("dataTables");
cache.Put(1, dt);
var res = cache.Get(1);
Assert.AreEqual("foo", res.TableName);
Assert.AreEqual(2, res.Columns.Count);
Assert.AreEqual("intCol", res.Columns[0].ColumnName);
Assert.AreEqual("stringCol", res.Columns[1].ColumnName);
Assert.AreEqual(2, res.Rows.Count);
Assert.AreEqual(new object[] {1, "1"}, res.Rows[0].ItemArray);
Assert.AreEqual(new object[] {2, "2"}, res.Rows[1].ItemArray);
}
}
[Serializable]
[DataContract]
[SuppressMessage("Microsoft.Design", "CA1058:TypesShouldNotExtendCertainBaseTypes")]
public sealed class SerializableXmlDoc : XmlDocument, ISerializable
{
/// <summary>
/// Default ctor.
/// </summary>
public SerializableXmlDoc()
{
// No-op
}
/// <summary>
/// Serialization ctor.
/// </summary>
private SerializableXmlDoc(SerializationInfo info, StreamingContext context)
{
LoadXml(info.GetString("xmlDocument"));
}
/** <inheritdoc /> */
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("xmlDocument", OuterXml, typeof(string));
}
}
[Serializable]
public class CombineStringsTask : IComputeTask<object, string, SerializableXmlDoc>
{
public IDictionary<IComputeJob<string>, IClusterNode> Map(IList<IClusterNode> subgrid, object arg)
{
return subgrid.ToDictionary(x => (IComputeJob<string>) new ToStringJob {Arg = arg}, x => x);
}
public ComputeJobResultPolicy OnResult(IComputeJobResult<string> res, IList<IComputeJobResult<string>> rcvd)
{
return ComputeJobResultPolicy.Wait;
}
public SerializableXmlDoc Reduce(IList<IComputeJobResult<string>> results)
{
var result = new SerializableXmlDoc();
result.LoadXml(CombineStrings(results.Select(x => x.Data)));
return result;
}
public static string CombineStrings(IEnumerable<string> strings)
{
var text = string.Concat(strings.Select(x => string.Format("<val>{0}</val>", x)));
return string.Format("<document>{0}</document>", text);
}
}
[Serializable]
public class ToStringJob : IComputeJob<string>
{
/// <summary>
/// Job argument.
/// </summary>
public object Arg { get; set; }
/** <inheritdoc /> */
public string Execute()
{
return Arg.ToString();
}
/** <inheritdoc /> */
public void Cancel()
{
// No-op.
}
}
}
| |
//
// COPYRIGHT: Copyright 2007
// Infralution
// www.infralution.com
//
using System;
using System.Collections.Generic;
using System.Text;
using System.Globalization;
using System.ComponentModel;
using System.Resources;
using System.Windows.Data;
namespace Infralution.Localization.Wpf
{
/// <summary>
/// Defines a type converter for enum values that converts enum values to
/// and from string representations using resources
/// </summary>
/// <remarks>
/// This class makes localization of display values for enums in a project easy. Simply
/// derive a class from this class and pass the ResourceManagerin the constructor.
///
/// <code lang="C#" escaped="true" >
/// class LocalizedEnumConverter : ResourceEnumConverter
/// {
/// public LocalizedEnumConverter(Type type)
/// : base(type, Properties.Resources.ResourceManager)
/// {
/// }
/// }
/// </code>
///
/// <code lang="Visual Basic" escaped="true" >
/// Public Class LocalizedEnumConverter
///
/// Inherits ResourceEnumConverter
/// Public Sub New(ByVal sType as Type)
/// MyBase.New(sType, My.Resources.ResourceManager)
/// End Sub
/// End Class
/// </code>
///
/// Then define the enum values in the resource editor. The names of
/// the resources are simply the enum value prefixed by the enum type name with an
/// underscore separator eg MyEnum_MyValue. You can then use the TypeConverter attribute
/// to make the LocalizedEnumConverter the default TypeConverter for the enums in your
/// project.
/// </remarks>
public class ResourceEnumConverter : EnumConverter, IValueConverter
{
private class LookupTable : Dictionary<string, object> { }
private Dictionary<CultureInfo, LookupTable> _lookupTables = new Dictionary<CultureInfo, LookupTable>();
private ResourceManager _resourceManager;
private bool _isFlagEnum = false;
private Array _flagValues;
/// <summary>
/// Get the lookup table for the given culture (creating if necessary)
/// </summary>
/// <param name="culture"></param>
/// <returns></returns>
private LookupTable GetLookupTable(CultureInfo culture)
{
LookupTable result = null;
if (culture == null)
culture = CultureInfo.CurrentCulture;
if (!_lookupTables.TryGetValue(culture, out result))
{
result = new LookupTable();
foreach (object value in GetStandardValues())
{
string text = GetValueText(culture, value);
if (text != null)
{
result.Add(text, value);
}
}
_lookupTables.Add(culture, result);
}
return result;
}
/// <summary>
/// Return the name of the resource to use
/// </summary>
/// <param name="value">The value to get</param>
/// <returns>The name of the resource to use</returns>
protected virtual string GetResourceName(object value)
{
Type type = value.GetType();
return string.Format("{0}_{1}", type.Name, value.ToString());
}
/// <summary>
/// Return the text to display for a simple value in the given culture
/// </summary>
/// <param name="culture">The culture to get the text for</param>
/// <param name="value">The enum value to get the text for</param>
/// <returns>The localized text</returns>
private string GetValueText(CultureInfo culture, object value)
{
string resourceName = GetResourceName(value);
string result = _resourceManager.GetString(resourceName, culture);
if (result == null)
result = resourceName;
return result;
}
/// <summary>
/// Return true if the given value is can be represented using a single bit
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
private bool IsSingleBitValue(ulong value)
{
switch (value)
{
case 0:
return false;
case 1:
return true;
}
return ((value & (value - 1)) == 0);
}
/// <summary>
/// Return the text to display for a flag value in the given culture
/// </summary>
/// <param name="culture">The culture to get the text for</param>
/// <param name="value">The flag enum value to get the text for</param>
/// <returns>The localized text</returns>
private string GetFlagValueText(CultureInfo culture, object value)
{
// if there is a standard value then use it
//
if (Enum.IsDefined(value.GetType(), value))
{
return GetValueText(culture, value);
}
// otherwise find the combination of flag bit values
// that makes up the value
//
ulong lValue = Convert.ToUInt32(value);
string result = null;
foreach (object flagValue in _flagValues)
{
ulong lFlagValue = Convert.ToUInt32(flagValue);
if (IsSingleBitValue(lFlagValue))
{
if ((lFlagValue & lValue) == lFlagValue)
{
string valueText = GetValueText(culture, flagValue);
if (result == null)
{
result = valueText;
}
else
{
result = string.Format("{0}, {1}", result, valueText);
}
}
}
}
return result;
}
/// <summary>
/// Return the Enum value for a simple (non-flagged enum)
/// </summary>
/// <param name="culture">The culture to convert using</param>
/// <param name="text">The text to convert</param>
/// <returns>The enum value</returns>
private object GetValue(CultureInfo culture, string text)
{
LookupTable lookupTable = GetLookupTable(culture);
object result = null;
lookupTable.TryGetValue(text, out result);
return result;
}
/// <summary>
/// Return the Enum value for a flagged enum
/// </summary>
/// <param name="culture">The culture to convert using</param>
/// <param name="text">The text to convert</param>
/// <returns>The enum value</returns>
private object GetFlagValue(CultureInfo culture, string text)
{
LookupTable lookupTable = GetLookupTable(culture);
string[] textValues = text.Split(',');
ulong result = 0;
foreach (string textValue in textValues)
{
object value = null;
string trimmedTextValue = textValue.Trim();
if (!lookupTable.TryGetValue(trimmedTextValue, out value))
{
return null;
}
result |= Convert.ToUInt32(value);
}
return Enum.ToObject(EnumType, result);
}
/// <summary>
/// Create a new instance of the converter using translations from the given resource manager
/// </summary>
/// <param name="type"></param>
/// <param name="resourceManager"></param>
public ResourceEnumConverter(Type type, ResourceManager resourceManager)
: base(type)
{
_resourceManager = resourceManager;
object[] flagAttributes = type.GetCustomAttributes(typeof(FlagsAttribute), true);
_isFlagEnum = flagAttributes.Length > 0;
if (_isFlagEnum)
{
_flagValues = Enum.GetValues(type);
}
}
/// <summary>
/// Convert string values to enum values
/// </summary>
/// <param name="context"></param>
/// <param name="culture"></param>
/// <param name="value"></param>
/// <returns></returns>
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
if (culture == null)
culture = CultureInfo.CurrentCulture;
if (value is string)
{
object result = (_isFlagEnum) ?
GetFlagValue(culture, (string)value): GetValue(culture, (string)value);
if (result == null)
{
result = base.ConvertFrom(context, culture, value);
}
return result;
}
else
{
return base.ConvertFrom(context, culture, value);
}
}
/// <summary>
/// Convert the enum value to a string
/// </summary>
/// <param name="context"></param>
/// <param name="culture"></param>
/// <param name="value"></param>
/// <param name="destinationType"></param>
/// <returns></returns>
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if (culture == null)
culture = CultureInfo.CurrentCulture;
if (value == null) return null;
if (destinationType == typeof(string) || destinationType == typeof(object))
{
object result = (_isFlagEnum) ?
GetFlagValueText(culture, value) : GetValueText(culture, value);
return result;
}
else
{
return base.ConvertTo(context, culture, value, destinationType);
}
}
/// <summary>
/// Convert the given enum value to string using the registered type converter
/// </summary>
/// <param name="value">The enum value to convert to string</param>
/// <returns>The localized string value for the enum</returns>
static public string ConvertToString(Enum value)
{
TypeConverter converter = TypeDescriptor.GetConverter(value.GetType());
return converter.ConvertToString(value);
}
/// <summary>
/// Return a list of the enum values and their associated display text for the given enum type
/// </summary>
/// <param name="enumType">The enum type to get the values for</param>
/// <param name="culture">The culture to get the text for</param>
/// <returns>
/// A list of KeyValuePairs where the key is the enum value and the value is the text to display
/// </returns>
/// <remarks>
/// This method can be used to provide localized binding to enums in ASP.NET applications. Unlike
/// windows forms the standard ASP.NET controls do not use TypeConverters to convert from enum values
/// to the displayed text. You can bind an ASP.NET control to the list returned by this method by setting
/// the DataValueField to "Key" and theDataTextField to "Value".
/// </remarks>
static public List<KeyValuePair<Enum, string>> GetValues(Type enumType, CultureInfo culture)
{
List<KeyValuePair<Enum, string>> result = new List<KeyValuePair<Enum, string>>();
TypeConverter converter = TypeDescriptor.GetConverter(enumType);
foreach (Enum value in Enum.GetValues(enumType))
{
KeyValuePair<Enum, string> pair = new KeyValuePair<Enum, string>(value, converter.ConvertToString(null, culture, value));
result.Add(pair);
}
return result;
}
/// <summary>
/// Return a list of the enum values and their associated display text for the given enum type in the current UI Culture
/// </summary>
/// <param name="enumType">The enum type to get the values for</param>
/// <returns>
/// A list of KeyValuePairs where the key is the enum value and the value is the text to display
/// </returns>
/// <remarks>
/// This method can be used to provide localized binding to enums in ASP.NET applications. Unlike
/// windows forms the standard ASP.NET controls do not use TypeConverters to convert from enum values
/// to the displayed text. You can bind an ASP.NET control to the list returned by this method by setting
/// the DataValueField to "Key" and theDataTextField to "Value".
/// </remarks>
static public List<KeyValuePair<Enum, string>> GetValues(Type enumType)
{
return GetValues(enumType, CultureInfo.CurrentUICulture);
}
/// <summary>
/// Handle XAML Conversion from this type to other types
/// </summary>
/// <param name="value">The value to convert</param>
/// <param name="targetType">The target type</param>
/// <param name="parameter">not used</param>
/// <param name="culture">The culture to convert</param>
/// <returns>The converted value</returns>
object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return ConvertTo(null, culture, value, targetType);
}
/// <summary>
/// Handle XAML Conversion from other types back to this type
/// </summary>
/// <param name="value">The value to convert</param>
/// <param name="targetType">The target type</param>
/// <param name="parameter">not used</param>
/// <param name="culture">The culture to convert</param>
/// <returns>The converted value</returns>
object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return ConvertFrom(null, culture, value);
}
}
}
| |
/*
* Copyright 2006-2007 Jeremias Maerki.
*
* 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.Text;
namespace ZXing.Datamatrix.Encoder
{
/// <summary>
/// DataMatrix ECC 200 data encoder following the algorithm described in ISO/IEC 16022:200(E) in
/// annex S.
/// </summary>
internal static class HighLevelEncoder
{
/// <summary>
/// Padding character
/// </summary>
public const char PAD = (char)129;
/// <summary>
/// mode latch to C40 encodation mode
/// </summary>
public const char LATCH_TO_C40 = (char)230;
/// <summary>
/// mode latch to Base 256 encodation mode
/// </summary>
public const char LATCH_TO_BASE256 = (char)231;
/// <summary>
/// FNC1 Codeword
/// </summary>
public const char FNC1 = (char)232;
/// <summary>
/// Structured Append Codeword
/// </summary>
public const char STRUCTURED_APPEND = (char)233;
/// <summary>
/// Reader Programming
/// </summary>
public const char READER_PROGRAMMING = (char)234;
/// <summary>
/// Upper Shift
/// </summary>
public const char UPPER_SHIFT = (char)235;
/// <summary>
/// 05 Macro
/// </summary>
public const char MACRO_05 = (char)236;
/// <summary>
/// 06 Macro
/// </summary>
public const char MACRO_06 = (char)237;
/// <summary>
/// mode latch to ANSI X.12 encodation mode
/// </summary>
public const char LATCH_TO_ANSIX12 = (char)238;
/// <summary>
/// mode latch to Text encodation mode
/// </summary>
public const char LATCH_TO_TEXT = (char)239;
/// <summary>
/// mode latch to EDIFACT encodation mode
/// </summary>
public const char LATCH_TO_EDIFACT = (char)240;
/// <summary>
/// ECI character (Extended Channel Interpretation)
/// </summary>
public const char ECI = (char)241;
/// <summary>
/// Unlatch from C40 encodation
/// </summary>
public const char C40_UNLATCH = (char)254;
/// <summary>
/// Unlatch from X12 encodation
/// </summary>
public const char X12_UNLATCH = (char)254;
/// <summary>
/// 05 Macro header
/// </summary>
public const String MACRO_05_HEADER = "[)>\u001E05\u001D";
/// <summary>
/// 06 Macro header
/// </summary>
public const String MACRO_06_HEADER = "[)>\u001E06\u001D";
/// <summary>
/// Macro trailer
/// </summary>
public const String MACRO_TRAILER = "\u001E\u0004";
/*
/// <summary>
/// Converts the message to a byte array using the default encoding (cp437) as defined by the
/// specification
/// </summary>
/// <param name="msg">the message</param>
/// <returns>the byte array of the message</returns>
public static byte[] getBytesForMessage(String msg)
{
return Encoding.GetEncoding("CP437").GetBytes(msg); //See 4.4.3 and annex B of ISO/IEC 15438:2001(E)
}
*/
private static char randomize253State(char ch, int codewordPosition)
{
int pseudoRandom = ((149 * codewordPosition) % 253) + 1;
int tempVariable = ch + pseudoRandom;
return tempVariable <= 254 ? (char)tempVariable : (char)(tempVariable - 254);
}
/// <summary>
/// Performs message encoding of a DataMatrix message using the algorithm described in annex P
/// of ISO/IEC 16022:2000(E).
/// </summary>
/// <param name="msg">the message</param>
/// <returns>the encoded message (the char values range from 0 to 255)</returns>
public static String encodeHighLevel(String msg)
{
return encodeHighLevel(msg, SymbolShapeHint.FORCE_NONE, null, null, (int)Encodation.ASCII);
}
/// <summary>
/// Performs message encoding of a DataMatrix message using the algorithm described in annex P
/// of ISO/IEC 16022:2000(E).
/// </summary>
/// <param name="msg">the message</param>
/// <param name="shape">requested shape. May be {@code SymbolShapeHint.FORCE_NONE},{@code SymbolShapeHint.FORCE_SQUARE} or {@code SymbolShapeHint.FORCE_RECTANGLE}.</param>
/// <param name="minSize">the minimum symbol size constraint or null for no constraint</param>
/// <param name="maxSize">the maximum symbol size constraint or null for no constraint</param>
/// <returns>the encoded message (the char values range from 0 to 255)</returns>
public static String encodeHighLevel(String msg,
SymbolShapeHint shape,
Dimension minSize,
Dimension maxSize,
int defaultEncodation)
{
//the codewords 0..255 are encoded as Unicode characters
Encoder[] encoders =
{
new ASCIIEncoder(), new C40Encoder(), new TextEncoder(),
new X12Encoder(), new EdifactEncoder(), new Base256Encoder()
};
var context = new EncoderContext(msg);
context.setSymbolShape(shape);
context.setSizeConstraints(minSize, maxSize);
if (msg.StartsWith(MACRO_05_HEADER) && msg.EndsWith(MACRO_TRAILER))
{
context.writeCodeword(MACRO_05);
context.setSkipAtEnd(2);
context.Pos += MACRO_05_HEADER.Length;
}
else if (msg.StartsWith(MACRO_06_HEADER) && msg.EndsWith(MACRO_TRAILER))
{
context.writeCodeword(MACRO_06);
context.setSkipAtEnd(2);
context.Pos += MACRO_06_HEADER.Length;
}
int encodingMode = defaultEncodation; //Default mode
switch (encodingMode)
{
case (int)Encodation.BASE256:
context.writeCodeword(HighLevelEncoder.LATCH_TO_BASE256);
break;
case (int)Encodation.C40:
context.writeCodeword(HighLevelEncoder.LATCH_TO_C40);
break;
case (int)Encodation.X12:
context.writeCodeword(HighLevelEncoder.LATCH_TO_ANSIX12);
break;
case (int)Encodation.TEXT:
context.writeCodeword(HighLevelEncoder.LATCH_TO_TEXT);
break;
case (int)Encodation.EDIFACT:
context.writeCodeword(HighLevelEncoder.LATCH_TO_EDIFACT);
break;
case (int)Encodation.ASCII:
break;
default:
throw new InvalidOperationException("Illegal mode: " + encodingMode);
}
while (context.HasMoreCharacters)
{
encoders[encodingMode].encode(context);
if (context.NewEncoding >= 0)
{
encodingMode = context.NewEncoding;
context.resetEncoderSignal();
}
}
int len = context.Codewords.Length;
context.updateSymbolInfo();
int capacity = context.SymbolInfo.dataCapacity;
if (len < capacity)
{
if (encodingMode != (int)Encodation.ASCII && encodingMode != (int)Encodation.BASE256)
{
context.writeCodeword('\u00fe'); //Unlatch (254)
}
}
//Padding
StringBuilder codewords = context.Codewords;
if (codewords.Length < capacity)
{
codewords.Append(PAD);
}
while (codewords.Length < capacity)
{
codewords.Append(randomize253State(PAD, codewords.Length + 1));
}
return context.Codewords.ToString();
}
internal static int lookAheadTest(String msg, int startpos, int currentMode)
{
if (startpos >= msg.Length)
{
return currentMode;
}
float[] charCounts;
//step J
if (currentMode == (int)Encodation.ASCII)
{
charCounts = new [] { 0, 1, 1, 1, 1, 1.25f };
}
else
{
charCounts = new [] { 1, 2, 2, 2, 2, 2.25f };
charCounts[currentMode] = 0;
}
int charsProcessed = 0;
while (true)
{
//step K
if ((startpos + charsProcessed) == msg.Length)
{
var min = Int32.MaxValue;
var mins = new byte[6];
var intCharCounts = new int[6];
min = findMinimums(charCounts, intCharCounts, min, mins);
var minCount = getMinimumCount(mins);
if (intCharCounts[(int)Encodation.ASCII] == min)
{
return (int)Encodation.ASCII;
}
if (minCount == 1 && mins[(int)Encodation.BASE256] > 0)
{
return (int)Encodation.BASE256;
}
if (minCount == 1 && mins[(int)Encodation.EDIFACT] > 0)
{
return (int)Encodation.EDIFACT;
}
if (minCount == 1 && mins[(int)Encodation.TEXT] > 0)
{
return (int)Encodation.TEXT;
}
if (minCount == 1 && mins[(int)Encodation.X12] > 0)
{
return (int)Encodation.X12;
}
return (int)Encodation.C40;
}
char c = msg[startpos + charsProcessed];
charsProcessed++;
//step L
if (isDigit(c))
{
charCounts[(int)Encodation.ASCII] += 0.5f;
}
else if (isExtendedASCII(c))
{
charCounts[(int)Encodation.ASCII] = (int)Math.Ceiling(charCounts[(int)Encodation.ASCII]);
charCounts[(int)Encodation.ASCII] += 2;
}
else
{
charCounts[(int)Encodation.ASCII] = (int)Math.Ceiling(charCounts[(int)Encodation.ASCII]);
charCounts[(int)Encodation.ASCII]++;
}
//step M
if (isNativeC40(c))
{
charCounts[(int)Encodation.C40] += 2.0f / 3.0f;
}
else if (isExtendedASCII(c))
{
charCounts[(int)Encodation.C40] += 8.0f / 3.0f;
}
else
{
charCounts[(int)Encodation.C40] += 4.0f / 3.0f;
}
//step N
if (isNativeText(c))
{
charCounts[(int)Encodation.TEXT] += 2.0f / 3.0f;
}
else if (isExtendedASCII(c))
{
charCounts[(int)Encodation.TEXT] += 8.0f / 3.0f;
}
else
{
charCounts[(int)Encodation.TEXT] += 4.0f / 3.0f;
}
//step O
if (isNativeX12(c))
{
charCounts[(int)Encodation.X12] += 2.0f / 3.0f;
}
else if (isExtendedASCII(c))
{
charCounts[(int)Encodation.X12] += 13.0f / 3.0f;
}
else
{
charCounts[(int)Encodation.X12] += 10.0f / 3.0f;
}
//step P
if (isNativeEDIFACT(c))
{
charCounts[(int)Encodation.EDIFACT] += 3.0f / 4.0f;
}
else if (isExtendedASCII(c))
{
charCounts[(int)Encodation.EDIFACT] += 17.0f / 4.0f;
}
else
{
charCounts[(int)Encodation.EDIFACT] += 13.0f / 4.0f;
}
// step Q
if (isSpecialB256(c))
{
charCounts[(int)Encodation.BASE256] += 4;
}
else
{
charCounts[(int)Encodation.BASE256]++;
}
//step R
if (charsProcessed >= 4)
{
var intCharCounts = new int[6];
var mins = new byte[6];
findMinimums(charCounts, intCharCounts, Int32.MaxValue, mins);
int minCount = getMinimumCount(mins);
if (intCharCounts[(int)Encodation.ASCII] < intCharCounts[(int)Encodation.BASE256]
&& intCharCounts[(int)Encodation.ASCII] < intCharCounts[(int)Encodation.C40]
&& intCharCounts[(int)Encodation.ASCII] < intCharCounts[(int)Encodation.TEXT]
&& intCharCounts[(int)Encodation.ASCII] < intCharCounts[(int)Encodation.X12]
&& intCharCounts[(int)Encodation.ASCII] < intCharCounts[(int)Encodation.EDIFACT])
{
return (int)Encodation.ASCII;
}
if (intCharCounts[(int)Encodation.BASE256] < intCharCounts[(int)Encodation.ASCII]
|| (mins[(int)Encodation.C40] + mins[(int)Encodation.TEXT] + mins[(int)Encodation.X12] + mins[(int)Encodation.EDIFACT]) == 0)
{
return (int)Encodation.BASE256;
}
if (minCount == 1 && mins[(int)Encodation.EDIFACT] > 0)
{
return (int)Encodation.EDIFACT;
}
if (minCount == 1 && mins[(int)Encodation.TEXT] > 0)
{
return (int)Encodation.TEXT;
}
if (minCount == 1 && mins[(int)Encodation.X12] > 0)
{
return (int)Encodation.X12;
}
if (intCharCounts[(int)Encodation.C40] + 1 < intCharCounts[(int)Encodation.ASCII]
&& intCharCounts[(int)Encodation.C40] + 1 < intCharCounts[(int)Encodation.BASE256]
&& intCharCounts[(int)Encodation.C40] + 1 < intCharCounts[(int)Encodation.EDIFACT]
&& intCharCounts[(int)Encodation.C40] + 1 < intCharCounts[(int)Encodation.TEXT])
{
if (intCharCounts[(int)Encodation.C40] < intCharCounts[(int)Encodation.X12])
{
return (int)Encodation.C40;
}
if (intCharCounts[(int)Encodation.C40] == intCharCounts[(int)Encodation.X12])
{
int p = startpos + charsProcessed + 1;
while (p < msg.Length)
{
char tc = msg[p];
if (isX12TermSep(tc))
{
return (int)Encodation.X12;
}
if (!isNativeX12(tc))
{
break;
}
p++;
}
return (int)Encodation.C40;
}
}
}
}
}
private static int findMinimums(float[] charCounts, int[] intCharCounts, int min, byte[] mins)
{
SupportClass.Fill(mins, (byte)0);
for (int i = 0; i < 6; i++)
{
intCharCounts[i] = (int)Math.Ceiling(charCounts[i]);
int current = intCharCounts[i];
if (min > current)
{
min = current;
SupportClass.Fill(mins, (byte)0);
}
if (min == current)
{
mins[i]++;
}
}
return min;
}
private static int getMinimumCount(byte[] mins)
{
int minCount = 0;
for (int i = 0; i < 6; i++)
{
minCount += mins[i];
}
return minCount;
}
internal static bool isDigit(char ch)
{
return ch >= '0' && ch <= '9';
}
internal static bool isExtendedASCII(char ch)
{
return ch >= 128 && ch <= 255;
}
internal static bool isNativeC40(char ch)
{
return (ch == ' ') || (ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z');
}
internal static bool isNativeText(char ch)
{
return (ch == ' ') || (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'z');
}
internal static bool isNativeX12(char ch)
{
return isX12TermSep(ch) || (ch == ' ') || (ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z');
}
internal static bool isX12TermSep(char ch)
{
return (ch == '\r') //CR
|| (ch == '*')
|| (ch == '>');
}
internal static bool isNativeEDIFACT(char ch)
{
return ch >= ' ' && ch <= '^';
}
internal static bool isSpecialB256(char ch)
{
return false; //TODO NOT IMPLEMENTED YET!!!
}
/// <summary>
/// Determines the number of consecutive characters that are encodable using numeric compaction.
/// </summary>
/// <param name="msg">the message</param>
/// <param name="startpos">the start position within the message</param>
/// <returns>the requested character count</returns>
public static int determineConsecutiveDigitCount(String msg, int startpos)
{
int count = 0;
int len = msg.Length;
int idx = startpos;
if (idx < len)
{
char ch = msg[idx];
while (isDigit(ch) && idx < len)
{
count++;
idx++;
if (idx < len)
{
ch = msg[idx];
}
}
}
return count;
}
internal static void illegalCharacter(char c)
{
throw new ArgumentException(String.Format("Illegal character: {0} (0x{1:X})", c, (int)c));
}
}
}
| |
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using JetBrains.Annotations;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics.UserInterface;
using osu.Game.Online.API;
using osu.Game.Online.Rooms;
using osu.Game.Rulesets;
using osu.Game.Scoring;
using osu.Game.Screens.Ranking;
namespace osu.Game.Screens.OnlinePlay.Playlists
{
public class PlaylistsResultsScreen : ResultsScreen
{
private readonly long roomId;
private readonly PlaylistItem playlistItem;
protected LoadingSpinner LeftSpinner { get; private set; }
protected LoadingSpinner CentreSpinner { get; private set; }
protected LoadingSpinner RightSpinner { get; private set; }
private MultiplayerScores higherScores;
private MultiplayerScores lowerScores;
[Resolved]
private IAPIProvider api { get; set; }
[Resolved]
private ScoreManager scoreManager { get; set; }
[Resolved]
private RulesetStore rulesets { get; set; }
public PlaylistsResultsScreen(ScoreInfo score, long roomId, PlaylistItem playlistItem, bool allowRetry, bool allowWatchingReplay = true)
: base(score, allowRetry, allowWatchingReplay)
{
this.roomId = roomId;
this.playlistItem = playlistItem;
}
[BackgroundDependencyLoader]
private void load()
{
AddInternal(new Container
{
RelativeSizeAxes = Axes.Both,
Padding = new MarginPadding { Bottom = TwoLayerButton.SIZE_EXTENDED.Y },
Children = new Drawable[]
{
LeftSpinner = new PanelListLoadingSpinner(ScorePanelList)
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.Centre,
},
CentreSpinner = new PanelListLoadingSpinner(ScorePanelList)
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
State = { Value = Score == null ? Visibility.Visible : Visibility.Hidden },
},
RightSpinner = new PanelListLoadingSpinner(ScorePanelList)
{
Anchor = Anchor.CentreRight,
Origin = Anchor.Centre,
},
}
});
}
protected override APIRequest FetchScores(Action<IEnumerable<ScoreInfo>> scoresCallback)
{
// This performs two requests:
// 1. A request to show the user's score (and scores around).
// 2. If that fails, a request to index the room starting from the highest score.
var userScoreReq = new ShowPlaylistUserScoreRequest(roomId, playlistItem.ID, api.LocalUser.Value.Id);
userScoreReq.Success += userScore =>
{
var allScores = new List<MultiplayerScore> { userScore };
if (userScore.ScoresAround?.Higher != null)
{
allScores.AddRange(userScore.ScoresAround.Higher.Scores);
higherScores = userScore.ScoresAround.Higher;
Debug.Assert(userScore.Position != null);
setPositions(higherScores, userScore.Position.Value, -1);
}
if (userScore.ScoresAround?.Lower != null)
{
allScores.AddRange(userScore.ScoresAround.Lower.Scores);
lowerScores = userScore.ScoresAround.Lower;
Debug.Assert(userScore.Position != null);
setPositions(lowerScores, userScore.Position.Value, 1);
}
performSuccessCallback(scoresCallback, allScores);
};
// On failure, fallback to a normal index.
userScoreReq.Failure += _ => api.Queue(createIndexRequest(scoresCallback));
return userScoreReq;
}
protected override APIRequest FetchNextPage(int direction, Action<IEnumerable<ScoreInfo>> scoresCallback)
{
Debug.Assert(direction == 1 || direction == -1);
MultiplayerScores pivot = direction == -1 ? higherScores : lowerScores;
if (pivot?.Cursor == null)
return null;
if (pivot == higherScores)
LeftSpinner.Show();
else
RightSpinner.Show();
return createIndexRequest(scoresCallback, pivot);
}
/// <summary>
/// Creates a <see cref="IndexPlaylistScoresRequest"/> with an optional score pivot.
/// </summary>
/// <remarks>Does not queue the request.</remarks>
/// <param name="scoresCallback">The callback to perform with the resulting scores.</param>
/// <param name="pivot">An optional score pivot to retrieve scores around. Can be null to retrieve scores from the highest score.</param>
/// <returns>The indexing <see cref="APIRequest"/>.</returns>
private APIRequest createIndexRequest(Action<IEnumerable<ScoreInfo>> scoresCallback, [CanBeNull] MultiplayerScores pivot = null)
{
var indexReq = pivot != null
? new IndexPlaylistScoresRequest(roomId, playlistItem.ID, pivot.Cursor, pivot.Params)
: new IndexPlaylistScoresRequest(roomId, playlistItem.ID);
indexReq.Success += r =>
{
if (pivot == lowerScores)
{
lowerScores = r;
setPositions(r, pivot, 1);
}
else
{
higherScores = r;
setPositions(r, pivot, -1);
}
performSuccessCallback(scoresCallback, r.Scores, r);
};
indexReq.Failure += _ => hideLoadingSpinners(pivot);
return indexReq;
}
/// <summary>
/// Transforms returned <see cref="MultiplayerScores"/> into <see cref="ScoreInfo"/>s, ensure the <see cref="ScorePanelList"/> is put into a sane state, and invokes a given success callback.
/// </summary>
/// <param name="callback">The callback to invoke with the final <see cref="ScoreInfo"/>s.</param>
/// <param name="scores">The <see cref="MultiplayerScore"/>s that were retrieved from <see cref="APIRequest"/>s.</param>
/// <param name="pivot">An optional pivot around which the scores were retrieved.</param>
private void performSuccessCallback([NotNull] Action<IEnumerable<ScoreInfo>> callback, [NotNull] List<MultiplayerScore> scores, [CanBeNull] MultiplayerScores pivot = null)
{
var scoreInfos = scores.Select(s => s.CreateScoreInfo(rulesets, playlistItem, Beatmap.Value.BeatmapInfo)).ToArray();
// Score panels calculate total score before displaying, which can take some time. In order to count that calculation as part of the loading spinner display duration,
// calculate the total scores locally before invoking the success callback.
scoreManager.OrderByTotalScoreAsync(scoreInfos).ContinueWith(_ => Schedule(() =>
{
// Select a score if we don't already have one selected.
// Note: This is done before the callback so that the panel list centres on the selected score before panels are added (eliminating initial scroll).
if (SelectedScore.Value == null)
{
Schedule(() =>
{
// Prefer selecting the local user's score, or otherwise default to the first visible score.
SelectedScore.Value = scoreInfos.FirstOrDefault(s => s.User.Id == api.LocalUser.Value.Id) ?? scoreInfos.FirstOrDefault();
});
}
// Invoke callback to add the scores. Exclude the user's current score which was added previously.
callback.Invoke(scoreInfos.Where(s => s.OnlineScoreID != Score?.OnlineScoreID));
hideLoadingSpinners(pivot);
}));
}
private void hideLoadingSpinners([CanBeNull] MultiplayerScores pivot = null)
{
CentreSpinner.Hide();
if (pivot == lowerScores)
RightSpinner.Hide();
else if (pivot == higherScores)
LeftSpinner.Hide();
}
/// <summary>
/// Applies positions to all <see cref="MultiplayerScore"/>s referenced to a given pivot.
/// </summary>
/// <param name="scores">The <see cref="MultiplayerScores"/> to set positions on.</param>
/// <param name="pivot">The pivot.</param>
/// <param name="increment">The amount to increment the pivot position by for each <see cref="MultiplayerScore"/> in <paramref name="scores"/>.</param>
private void setPositions([NotNull] MultiplayerScores scores, [CanBeNull] MultiplayerScores pivot, int increment)
=> setPositions(scores, pivot?.Scores[^1].Position ?? 0, increment);
/// <summary>
/// Applies positions to all <see cref="MultiplayerScore"/>s referenced to a given pivot.
/// </summary>
/// <param name="scores">The <see cref="MultiplayerScores"/> to set positions on.</param>
/// <param name="pivotPosition">The pivot position.</param>
/// <param name="increment">The amount to increment the pivot position by for each <see cref="MultiplayerScore"/> in <paramref name="scores"/>.</param>
private void setPositions([NotNull] MultiplayerScores scores, int pivotPosition, int increment)
{
foreach (var s in scores.Scores)
{
pivotPosition += increment;
s.Position = pivotPosition;
}
}
private class PanelListLoadingSpinner : LoadingSpinner
{
private readonly ScorePanelList list;
/// <summary>
/// Creates a new <see cref="PanelListLoadingSpinner"/>.
/// </summary>
/// <param name="list">The list to track.</param>
/// <param name="withBox">Whether the spinner should have a surrounding black box for visibility.</param>
public PanelListLoadingSpinner(ScorePanelList list, bool withBox = true)
: base(withBox)
{
this.list = list;
}
protected override void Update()
{
base.Update();
float panelOffset = list.DrawWidth / 2 - ScorePanel.EXPANDED_WIDTH;
if ((Anchor & Anchor.x0) > 0)
X = (float)(panelOffset - list.Current);
else if ((Anchor & Anchor.x2) > 0)
X = (float)(list.ScrollableExtent - list.Current - panelOffset);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using Cosmos.System;
using IL2CPU.API;
using IL2CPU.API.Attribs;
namespace Cosmos.System_Plugs.System
{
[Plug(Target = typeof (global::System.Console))]
public static class ConsoleImpl
{
private static ConsoleColor mForeground = ConsoleColor.White;
private static ConsoleColor mBackground = ConsoleColor.Black;
private static Encoding ConsoleInputEncoding = Encoding.ASCII;
private static Encoding ConsoleOutputEncoding = Encoding.ASCII;
private static readonly Cosmos.System.Console mFallbackConsole = new Cosmos.System.Console(null);
private static Cosmos.System.Console GetConsole()
{
return mFallbackConsole;
}
public static ConsoleColor get_BackgroundColor()
{
return mBackground;
}
public static void set_BackgroundColor(ConsoleColor value)
{
mBackground = value;
//Cosmos.HAL.Global.TextScreen.SetColors(mForeground, mBackground);
if (GetConsole() != null) GetConsole().Background = value;
}
public static int get_BufferHeight()
{
WriteLine("Not implemented: get_BufferHeight");
return -1;
}
public static void set_BufferHeight(int aHeight)
{
WriteLine("Not implemented: set_BufferHeight");
}
public static int get_BufferWidth()
{
WriteLine("Not implemented: get_BufferWidth");
return -1;
}
public static void set_BufferWidth(int aWidth)
{
WriteLine("Not implemented: set_BufferWidth");
}
public static bool get_CapsLock()
{
return Global.CapsLock;
}
public static int get_CursorLeft()
{
var xConsole = GetConsole();
if (xConsole == null)
{
// for now:
return 0;
}
return GetConsole().X;
}
public static void set_CursorLeft(int x)
{
var xConsole = GetConsole();
if (xConsole == null)
{
// for now:
return;
}
if (x < get_WindowWidth())
{
xConsole.X = x;
}
else
{
WriteLine("x must be lower than the console width!");
}
}
public static int get_CursorSize()
{
var xConsole = GetConsole();
if (xConsole == null)
{
// for now:
return 0;
}
return xConsole.CursorSize;
}
public static void set_CursorSize(int aSize)
{
var xConsole = GetConsole();
if (xConsole == null)
{
// for now:
return;
}
xConsole.CursorSize = aSize;
}
public static int get_CursorTop()
{
var xConsole = GetConsole();
if (xConsole == null)
{
// for now:
return 0;
}
return GetConsole().Y;
}
public static void set_CursorTop(int y)
{
var xConsole = GetConsole();
if (xConsole == null)
{
// for now:
return;
}
if (y < get_WindowHeight())
{
xConsole.Y = y;
}
else
{
WriteLine("y must be lower than the console height!");
}
}
public static bool get_CursorVisible()
{
var xConsole = GetConsole();
if (xConsole == null)
{
return false;
}
return GetConsole().CursorVisible;
}
public static void set_CursorVisible(bool value)
{
var xConsole = GetConsole();
if (xConsole == null)
{
// for now:
return;
}
xConsole.CursorVisible = value;
}
//public static TextWriter get_Error() {
// WriteLine("Not implemented: get_Error");
// return null;
//}
public static ConsoleColor get_ForegroundColor()
{
return mForeground;
}
public static void set_ForegroundColor(ConsoleColor value)
{
mForeground = value;
//Cosmos.HAL.Global.TextScreen.SetColors(mForeground, mBackground);
if (GetConsole() != null) GetConsole().Foreground = value;
}
//public static TextReader get_In()
//{
// WriteLine("Not implemented: get_In");
// return null;
//}
public static Encoding get_InputEncoding()
{
return ConsoleInputEncoding;
}
public static void set_InputEncoding(Encoding value)
{
ConsoleInputEncoding = value;
}
public static Encoding get_OutputEncoding()
{
return ConsoleOutputEncoding;
}
public static void set_OutputEncoding(Encoding value)
{
ConsoleOutputEncoding = value;
}
public static bool get_KeyAvailable()
{
return KeyboardManager.KeyAvailable;
}
public static int get_LargestWindowHeight()
{
WriteLine("Not implemented: get_LargestWindowHeight");
return -1;
}
public static int get_LargestWindowWidth()
{
WriteLine("Not implemented: get_LargestWindowWidth");
return -1;
}
public static bool get_NumberLock()
{
return Global.NumLock;
}
//public static TextWriter get_Out() {
// WriteLine("Not implemented: get_Out");
// return null;
//}
public static string get_Title()
{
WriteLine("Not implemented: get_Title");
return string.Empty;
}
public static void set_Title(string value)
{
WriteLine("Not implemented: set_Title");
}
public static bool get_TreatControlCAsInput()
{
WriteLine("Not implemented: get_TreatControlCAsInput");
return false;
}
public static void set_TreatControlCAsInput(bool value)
{
WriteLine("Not implemented: set_TreatControlCAsInput");
}
public static int get_WindowHeight()
{
var xConsole = GetConsole();
if (xConsole == null)
{
// for now:
return 25;
}
return GetConsole().Rows;
}
public static void set_WindowHeight(int value)
{
WriteLine("Not implemented: set_WindowHeight");
}
public static int get_WindowLeft()
{
WriteLine("Not implemented: get_WindowLeft");
return -1;
}
public static void set_WindowLeft(int value)
{
WriteLine("Not implemented: set_WindowLeft");
}
public static int get_WindowTop()
{
WriteLine("Not implemented: get_WindowTop");
return -1;
}
public static void set_WindowTop(int value)
{
WriteLine("Not implemented: set_WindowTop");
}
public static int get_WindowWidth()
{
var xConsole = GetConsole();
if (xConsole == null)
{
// for now:
return 85;
}
return GetConsole().Cols;
}
public static void set_WindowWidth(int value)
{
WriteLine("Not implemented: set_WindowWidth");
}
/// <summary>
/// The ArgumentOutOfRangeException check is now done at driver level in PCSpeaker - is it still needed here?
/// </summary>
/// <param name="aFrequency"></param>
/// <param name="aDuration"></param>
public static void Beep(int aFrequency, int aDuration)
{
if (aFrequency < 37 || aFrequency > 32767)
{
throw new ArgumentOutOfRangeException("Frequency must be between 37 and 32767Hz");
}
if (aDuration <= 0)
{
throw new ArgumentOutOfRangeException("Duration must be more than 0");
}
PCSpeaker.Beep((uint) aFrequency, (uint) aDuration);
}
/// <summary>
/// Beep() is pure CIL
/// Default implementation beeps for 200 milliseconds at 800 hertz
/// In Cosmos, these are Cosmos.System.Duration.Default and Cosmos.System.Notes.Default respectively,
/// and are used when there are no params
/// https://docs.microsoft.com/en-us/dotnet/api/system.console.beep?view=netcore-2.0
/// </summary>
public static void Beep()
{
PCSpeaker.Beep();
}
//TODO: Console uses TextWriter - intercept and plug it instead
public static void Clear()
{
var xConsole = GetConsole();
if (xConsole == null)
{
// for now:
return;
}
GetConsole().Clear();
}
// MoveBufferArea(int, int, int, int, int, int) is pure CIL
public static void MoveBufferArea(int sourceLeft, int sourceTop, int sourceWidth, int sourceHeight,
int targetLeft, int targetTop, Char sourceChar, ConsoleColor sourceForeColor, ConsoleColor sourceBackColor)
{
WriteLine("Not implemented: MoveBufferArea");
}
//public static Stream OpenStandardError() {
// WriteLine("Not implemented: OpenStandardError");
//}
//public static Stream OpenStandardError(int bufferSize) {
// WriteLine("Not implemented: OpenStandardError");
//}
//public static Stream OpenStandardInput(int bufferSize) {
// WriteLine("Not implemented: OpenStandardInput");
//}
//public static Stream OpenStandardInput() {
// WriteLine("Not implemented: OpenStandardInput");
//}
//public static Stream OpenStandardOutput(int bufferSize) {
// WriteLine("Not implemented: OpenStandardOutput");
//}
//public static Stream OpenStandardOutput() {
// WriteLine("Not implemented: OpenStandardOutput");
//}
public static int Read()
{
// TODO special cases, if needed, that returns -1
KeyEvent xResult;
if (KeyboardManager.TryReadKey(out xResult))
{
return xResult.KeyChar;
}
else
{
return -1;
}
}
public static ConsoleKeyInfo ReadKey()
{
return ReadKey(false);
}
// ReadKey() pure CIL
public static ConsoleKeyInfo ReadKey(bool intercept)
{
var key = KeyboardManager.ReadKey();
if (intercept == false && key.KeyChar != '\0')
{
Write(key.KeyChar);
}
//TODO: Plug HasFlag and use the next 3 lines instead of the 3 following lines
//bool xShift = key.Modifiers.HasFlag(ConsoleModifiers.Shift);
//bool xAlt = key.Modifiers.HasFlag(ConsoleModifiers.Alt);
//bool xControl = key.Modifiers.HasFlag(ConsoleModifiers.Control);
bool xShift = (key.Modifiers & ConsoleModifiers.Shift) == ConsoleModifiers.Shift;
bool xAlt = (key.Modifiers & ConsoleModifiers.Alt) == ConsoleModifiers.Alt;
bool xControl = (key.Modifiers & ConsoleModifiers.Control) == ConsoleModifiers.Control;
return new ConsoleKeyInfo(key.KeyChar, key.Key.ToConsoleKey(), xShift, xAlt, xControl);
}
public static String ReadLine()
{
var xConsole = GetConsole();
if (xConsole == null)
{
// for now:
return null;
}
List<char> chars = new List<char>(32);
KeyEvent current;
int currentCount = 0;
while ((current = KeyboardManager.ReadKey()).Key != ConsoleKeyEx.Enter)
{
if (current.Key == ConsoleKeyEx.NumEnter) break;
//Check for "special" keys
if (current.Key == ConsoleKeyEx.Backspace) // Backspace
{
if (currentCount > 0)
{
int curCharTemp = GetConsole().X;
chars.RemoveAt(currentCount - 1);
GetConsole().X = GetConsole().X - 1;
//Move characters to the left
for (int x = currentCount - 1; x < chars.Count; x++)
{
Write(chars[x]);
}
Write(' ');
GetConsole().X = curCharTemp - 1;
currentCount--;
}
continue;
}
else if (current.Key == ConsoleKeyEx.LeftArrow)
{
if (currentCount > 0)
{
GetConsole().X = GetConsole().X - 1;
currentCount--;
}
continue;
}
else if (current.Key == ConsoleKeyEx.RightArrow)
{
if (currentCount < chars.Count)
{
GetConsole().X = GetConsole().X + 1;
currentCount++;
}
continue;
}
if (current.KeyChar == '\0') continue;
//Write the character to the screen
if (currentCount == chars.Count)
{
chars.Add(current.KeyChar);
Write(current.KeyChar);
currentCount++;
}
else
{
//Insert the new character in the correct location
//For some reason, List.Insert() doesn't work properly
//so the character has to be inserted manually
List<char> temp = new List<char>();
for (int x = 0; x < chars.Count; x++)
{
if (x == currentCount)
{
temp.Add(current.KeyChar);
}
temp.Add(chars[x]);
}
chars = temp;
//Shift the characters to the right
for (int x = currentCount; x < chars.Count; x++)
{
Write(chars[x]);
}
GetConsole().X -= (chars.Count - currentCount) - 1;
currentCount++;
}
}
WriteLine();
char[] final = chars.ToArray();
return new string(final);
}
public static void ResetColor()
{
set_BackgroundColor(ConsoleColor.Black);
set_ForegroundColor(ConsoleColor.White);
}
public static void SetBufferSize(int width, int height)
{
WriteLine("Not implemented: SetBufferSize");
}
public static void SetCursorPosition(int left, int top)
{
set_CursorLeft(left);
set_CursorTop(top);
}
//public static void SetError(TextWriter newError) {
// WriteLine("Not implemented: SetError");
//}
//public static void SetIn(TextReader newIn) {
// WriteLine("Not implemented: SetIn");
//}
//public static void SetOut(TextWriter newOut) {
// WriteLine("Not implemented: SetOut");
//}
public static void SetWindowPosition(int left, int top)
{
WriteLine("Not implemented: SetWindowPosition");
}
public static void SetWindowSize(int width, int height)
{
WriteLine("Not implemented: SetWindowSize");
}
#region Write
public static void Write(bool aBool)
{
Write(aBool.ToString());
}
/*
* A .Net character can be effectevily more can one byte so calling the low level Console.Write() will be wrong as
* it accepts only bytes, we need to convert it using the specified OutputEncoding but to do this we have to convert
* it ToString first
*/
public static void Write(char aChar) => Write(aChar.ToString());
public static void Write(char[] aBuffer) => Write(aBuffer, 0, aBuffer.Length);
/* Decimal type is not working yet... */
//public static void Write(decimal aDecimal) => Write(aDecimal.ToString());
public static void Write(double aDouble) => Write(aDouble.ToString());
public static void Write(float aFloat) => Write(aFloat.ToString());
public static void Write(int aInt) => Write(aInt.ToString());
public static void Write(long aLong) => Write(aLong.ToString());
/* Correct behaviour printing null should not throw NRE or do nothing but should print an empty string */
public static void Write(object value) => Write((value ?? String.Empty));
public static void Write(string aText)
{
var xConsole = GetConsole();
if (xConsole == null)
{
// for now:
return;
}
byte[] aTextEncoded = ConsoleOutputEncoding.GetBytes(aText);
GetConsole().Write(aTextEncoded);
}
public static void Write(uint aInt) => Write(aInt.ToString());
public static void Write(ulong aLong) => Write(aLong.ToString());
public static void Write(string format, object arg0) => Write(String.Format(format, arg0));
public static void Write(string format, object arg0, object arg1) => Write(String.Format(format, arg0, arg1));
public static void Write(string format, object arg0, object arg1, object arg2) => Write(String.Format(format, arg0, arg1, arg2));
public static void Write(string format, object arg0, object arg1, object arg2, object arg3) => Write(String.Format(format, arg0, arg1, arg2, arg3));
public static void Write(string format, params object[] arg) => Write(String.Format(format, arg));
public static void Write(char[] aBuffer, int aIndex, int aCount)
{
if (aBuffer == null)
{
throw new ArgumentNullException("aBuffer");
}
if (aIndex < 0)
{
throw new ArgumentOutOfRangeException("aIndex");
}
if (aCount < 0)
{
throw new ArgumentOutOfRangeException("aCount");
}
if ((aBuffer.Length - aIndex) < aCount)
{
throw new ArgumentException();
}
for (int i = 0; i < aCount; i++)
{
Write(aBuffer[aIndex + i]);
}
}
//You'd expect this to be on System.Console wouldn't you? Well, it ain't so we just rely on Write(object value)
//public static void Write(byte aByte) {
// Write(aByte.ToString());
//}
#endregion
#region WriteLine
public static void WriteLine() => Write(Environment.NewLine);
public static void WriteLine(bool aBool) => WriteLine(aBool.ToString());
public static void WriteLine(char aChar) => WriteLine(aChar.ToString());
public static void WriteLine(char[] aBuffer) => WriteLine(new String(aBuffer));
/* Decimal type is not working yet... */
//public static void WriteLine(decimal aDecimal) => WriteLine(aDecimal.ToString());
public static void WriteLine(double aDouble) => WriteLine(aDouble.ToString());
public static void WriteLine(float aFloat) => WriteLine(aFloat.ToString());
public static void WriteLine(int aInt) => WriteLine(aInt.ToString());
public static void WriteLine(long aLong) => WriteLine(aLong.ToString());
/* Correct behaviour printing null should not throw NRE or do nothing but should print an empty line */
public static void WriteLine(object value) => Write((value ?? String.Empty) + Environment.NewLine);
public static void WriteLine(string aText) => Write(aText + Environment.NewLine);
public static void WriteLine(uint aInt) => WriteLine(aInt.ToString());
public static void WriteLine(ulong aLong) => WriteLine(aLong.ToString());
public static void WriteLine(string format, object arg0) => WriteLine(String.Format(format, arg0));
public static void WriteLine(string format, object arg0, object arg1) => WriteLine(String.Format(format, arg0, arg1));
public static void WriteLine(string format, object arg0, object arg1, object arg2) => WriteLine(String.Format(format, arg0, arg1, arg2));
public static void WriteLine(string format, object arg0, object arg1, object arg2, object arg3) => WriteLine(String.Format(format, arg0, arg1, arg2, arg3));
public static void WriteLine(string format, params object[] arg) => WriteLine(String.Format(format, arg));
public static void WriteLine(char[] aBuffer, int aIndex, int aCount)
{
Write(aBuffer, aIndex, aCount);
WriteLine();
}
#endregion
}
}
| |
//
// 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.IO;
using System.Runtime.InteropServices;
using SR = System.Reflection;
using SquabPie.Mono.Collections.Generic;
namespace SquabPie.Mono.Cecil.Cil {
[StructLayout (LayoutKind.Sequential)]
public struct ImageDebugDirectory {
public int Characteristics;
public int TimeDateStamp;
public short MajorVersion;
public short MinorVersion;
public int Type;
public int SizeOfData;
public int AddressOfRawData;
public int PointerToRawData;
}
public sealed class Scope : IVariableDefinitionProvider {
Instruction start;
Instruction end;
Collection<Scope> scopes;
Collection<VariableDefinition> variables;
public Instruction Start {
get { return start; }
set { start = value; }
}
public Instruction End {
get { return end; }
set { end = value; }
}
public bool HasScopes {
get { return !scopes.IsNullOrEmpty (); }
}
public Collection<Scope> Scopes {
get {
if (scopes == null)
scopes = new Collection<Scope> ();
return scopes;
}
}
public bool HasVariables {
get { return !variables.IsNullOrEmpty (); }
}
public Collection<VariableDefinition> Variables {
get {
if (variables == null)
variables = new Collection<VariableDefinition> ();
return variables;
}
}
}
public struct InstructionSymbol {
public readonly int Offset;
public readonly SequencePoint SequencePoint;
public InstructionSymbol (int offset, SequencePoint sequencePoint)
{
this.Offset = offset;
this.SequencePoint = sequencePoint;
}
}
public sealed class MethodSymbols {
internal int code_size;
internal string method_name;
internal MetadataToken method_token;
internal MetadataToken local_var_token;
internal Collection<VariableDefinition> variables;
internal Collection<InstructionSymbol> instructions;
public bool HasVariables {
get { return !variables.IsNullOrEmpty (); }
}
public Collection<VariableDefinition> Variables {
get {
if (variables == null)
variables = new Collection<VariableDefinition> ();
return variables;
}
}
public Collection<InstructionSymbol> Instructions {
get {
if (instructions == null)
instructions = new Collection<InstructionSymbol> ();
return instructions;
}
}
public int CodeSize {
get { return code_size; }
}
public string MethodName {
get { return method_name; }
}
public MetadataToken MethodToken {
get { return method_token; }
}
public MetadataToken LocalVarToken {
get { return local_var_token; }
}
internal MethodSymbols (string methodName)
{
this.method_name = methodName;
}
public MethodSymbols (MetadataToken methodToken)
{
this.method_token = methodToken;
}
}
public delegate Instruction InstructionMapper (int offset);
public interface ISymbolReader : IDisposable {
bool ProcessDebugHeader (ImageDebugDirectory directory, byte [] header);
void Read (MethodBody body, InstructionMapper mapper);
void Read (MethodSymbols symbols);
}
public interface ISymbolReaderProvider {
ISymbolReader GetSymbolReader (ModuleDefinition module, string fileName);
ISymbolReader GetSymbolReader (ModuleDefinition module, Stream symbolStream);
}
#if !PCL
static class SymbolProvider {
static readonly string symbol_kind = Type.GetType ("Mono.Runtime") != null ? "Mdb" : "Pdb";
static SR.AssemblyName GetPlatformSymbolAssemblyName ()
{
var cecil_name = typeof (SymbolProvider).Assembly.GetName ();
var name = new SR.AssemblyName {
Name = "SquabPie.Mono.Cecil." + symbol_kind,
Version = cecil_name.Version,
};
name.SetPublicKeyToken (cecil_name.GetPublicKeyToken ());
return name;
}
static Type GetPlatformType (string fullname)
{
var type = Type.GetType (fullname);
if (type != null)
return type;
var assembly_name = GetPlatformSymbolAssemblyName ();
type = Type.GetType (fullname + ", " + assembly_name.FullName);
if (type != null)
return type;
try {
var assembly = SR.Assembly.Load (assembly_name);
if (assembly != null)
return assembly.GetType (fullname);
} catch (FileNotFoundException) {
} catch (FileLoadException) {
}
return null;
}
static ISymbolReaderProvider reader_provider;
public static ISymbolReaderProvider GetPlatformReaderProvider ()
{
if (reader_provider != null)
return reader_provider;
var type = GetPlatformType (GetProviderTypeName ("ReaderProvider"));
if (type == null)
return null;
return reader_provider = (ISymbolReaderProvider) Activator.CreateInstance (type);
}
static string GetProviderTypeName (string name)
{
return "SquabPie.Mono.Cecil." + symbol_kind + "." + symbol_kind + name;
}
#if !READ_ONLY
static ISymbolWriterProvider writer_provider;
public static ISymbolWriterProvider GetPlatformWriterProvider ()
{
if (writer_provider != null)
return writer_provider;
var type = GetPlatformType (GetProviderTypeName ("WriterProvider"));
if (type == null)
return null;
return writer_provider = (ISymbolWriterProvider) Activator.CreateInstance (type);
}
#endif
}
#endif
#if !READ_ONLY
public interface ISymbolWriter : IDisposable {
bool GetDebugHeader (out ImageDebugDirectory directory, out byte [] header);
void Write (MethodBody body);
void Write (MethodSymbols symbols);
}
public interface ISymbolWriterProvider {
ISymbolWriter GetSymbolWriter (ModuleDefinition module, string fileName);
ISymbolWriter GetSymbolWriter (ModuleDefinition module, Stream symbolStream);
}
#endif
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Channels
{
using System;
using System.Globalization;
using System.Text;
using System.Threading;
using System.Runtime.InteropServices;
using System.Security;
using System.Runtime.Serialization;
using System.ServiceModel.Diagnostics;
using Microsoft.Win32.SafeHandles;
abstract class NativeMsmqMessage : IDisposable
{
UnsafeNativeMethods.MQPROPVARIANT[] variants;
UnsafeNativeMethods.MQMSGPROPS nativeProperties;
int[] ids;
GCHandle nativePropertiesHandle;
GCHandle variantsHandle;
GCHandle idsHandle;
MsmqProperty[] properties;
bool disposed;
object[] buffersForAsync;
protected NativeMsmqMessage(int propertyCount)
{
this.properties = new MsmqProperty[propertyCount];
this.nativeProperties = new UnsafeNativeMethods.MQMSGPROPS();
this.ids = new int[propertyCount];
this.variants = new UnsafeNativeMethods.MQPROPVARIANT[propertyCount];
this.nativePropertiesHandle = GCHandle.Alloc(null, GCHandleType.Pinned);
this.idsHandle = GCHandle.Alloc(null, GCHandleType.Pinned);
this.variantsHandle = GCHandle.Alloc(null, GCHandleType.Pinned);
}
~NativeMsmqMessage()
{
Dispose(false);
}
public virtual void GrowBuffers()
{
}
public object[] GetBuffersForAsync()
{
if (null == this.buffersForAsync)
{
int propertyBuffersToPin = 0;
for (int i = 0; i < this.nativeProperties.count; ++i)
{
if (this.properties[i].MaintainsBuffer)
++propertyBuffersToPin;
}
this.buffersForAsync = new object[propertyBuffersToPin + 3];
}
int bufferCount = 0;
for (int i = 0; i < this.nativeProperties.count; ++i)
{
if (this.properties[i].MaintainsBuffer)
{
this.buffersForAsync[bufferCount++] = this.properties[i].MaintainedBuffer;
}
}
this.buffersForAsync[bufferCount++] = this.ids;
this.buffersForAsync[bufferCount++] = this.variants;
this.buffersForAsync[bufferCount] = this.nativeProperties;
return this.buffersForAsync;
}
public IntPtr Pin()
{
for (int i = 0; i < this.nativeProperties.count; i++)
properties[i].Pin();
this.idsHandle.Target = this.ids;
this.variantsHandle.Target = this.variants;
this.nativeProperties.status = IntPtr.Zero;
this.nativeProperties.variants = this.variantsHandle.AddrOfPinnedObject();
this.nativeProperties.ids = this.idsHandle.AddrOfPinnedObject();
this.nativePropertiesHandle.Target = this.nativeProperties;
return nativePropertiesHandle.AddrOfPinnedObject();
}
public void Unpin()
{
this.nativePropertiesHandle.Target = null;
this.idsHandle.Target = null;
this.variantsHandle.Target = null;
for (int i = 0; i < this.nativeProperties.count; i++)
properties[i].Unpin();
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
void Dispose(bool disposing)
{
if (!this.disposed && disposing)
{
for (int i = 0; i < this.nativeProperties.count; i++)
{
this.properties[i].Dispose();
}
this.disposed = true;
}
if (this.nativePropertiesHandle.IsAllocated)
this.nativePropertiesHandle.Free();
if (this.idsHandle.IsAllocated)
this.idsHandle.Free();
if (this.variantsHandle.IsAllocated)
this.variantsHandle.Free();
}
public abstract class MsmqProperty : IDisposable
{
UnsafeNativeMethods.MQPROPVARIANT[] variants;
int index;
protected MsmqProperty(NativeMsmqMessage message, int id, ushort vt)
{
this.variants = message.variants;
this.index = message.nativeProperties.count++;
message.variants[this.index].vt = vt;
message.ids[this.index] = id;
message.properties[this.index] = this;
}
protected int Index
{
get { return this.index; }
}
public virtual bool MaintainsBuffer
{
get { return false; }
}
public virtual object MaintainedBuffer
{
get { return null; }
}
public virtual void Pin()
{
}
public virtual void Unpin()
{
}
public virtual void Dispose()
{
}
protected UnsafeNativeMethods.MQPROPVARIANT[] Variants
{
get { return this.variants; }
}
}
public class ByteProperty : MsmqProperty
{
public ByteProperty(NativeMsmqMessage message, int id)
: base(message, id, UnsafeNativeMethods.VT_UI1)
{
}
public ByteProperty(NativeMsmqMessage message, int id, byte value)
: this(message, id)
{
this.Value = value;
}
public byte Value
{
get
{
return this.Variants[this.Index].byteValue;
}
set
{
this.Variants[this.Index].byteValue = value;
}
}
}
public class ShortProperty : MsmqProperty
{
public ShortProperty(NativeMsmqMessage message, int id)
: base(message, id, UnsafeNativeMethods.VT_UI2)
{
}
public ShortProperty(NativeMsmqMessage message, int id, short value)
: this(message, id)
{
this.Value = value;
}
public short Value
{
get
{
return this.Variants[this.Index].shortValue;
}
set
{
this.Variants[this.Index].shortValue = value;
}
}
}
public class BooleanProperty : MsmqProperty
{
public BooleanProperty(NativeMsmqMessage message, int id)
: base(message, id, UnsafeNativeMethods.VT_BOOL)
{
}
public BooleanProperty(NativeMsmqMessage message, int id, bool value)
: this(message, id)
{
this.Value = value;
}
public bool Value
{
get
{
return this.Variants[this.Index].shortValue != 0;
}
set
{
this.Variants[this.Index].shortValue = value ? (short)-1 : (short)0;
}
}
}
public class IntProperty : MsmqProperty
{
public IntProperty(NativeMsmqMessage message, int id)
: base(message, id, UnsafeNativeMethods.VT_UI4)
{
}
public IntProperty(NativeMsmqMessage message, int id, int value)
: this(message, id)
{
this.Value = value;
}
public int Value
{
get
{
return this.Variants[this.Index].intValue;
}
set
{
this.Variants[this.Index].intValue = value;
}
}
}
public class LongProperty : MsmqProperty
{
public LongProperty(NativeMsmqMessage message, int id)
: base(message, id, UnsafeNativeMethods.VT_UI8)
{
}
public LongProperty(NativeMsmqMessage message, int id, long value)
: this(message, id)
{
this.Value = value;
}
public long Value
{
get
{
return this.Variants[this.Index].longValue;
}
set
{
this.Variants[this.Index].longValue = value;
}
}
}
public class BufferProperty : MsmqProperty
{
byte[] buffer;
GCHandle bufferHandle;
public BufferProperty(NativeMsmqMessage message, int id)
: base(message, id, UnsafeNativeMethods.VT_UI1 | UnsafeNativeMethods.VT_VECTOR)
{
bufferHandle = GCHandle.Alloc(null, GCHandleType.Pinned);
}
public BufferProperty(NativeMsmqMessage message, int id, byte[] buffer)
: this(message, id, buffer.Length)
{
System.Buffer.BlockCopy(buffer, 0, this.Buffer, 0, buffer.Length);
}
public BufferProperty(NativeMsmqMessage message, int id, int length)
: this(message, id)
{
SetBufferReference(DiagnosticUtility.Utility.AllocateByteArray(length));
}
~BufferProperty()
{
Dispose(false);
}
public override void Dispose()
{
base.Dispose();
this.Dispose(true);
GC.SuppressFinalize(this);
}
void Dispose(bool disposing)
{
if (bufferHandle.IsAllocated)
bufferHandle.Free();
}
public void SetBufferReference(byte[] buffer)
{
SetBufferReference(buffer, buffer.Length);
}
public void SetBufferReference(byte[] buffer, int length)
{
this.buffer = buffer;
this.BufferLength = length;
}
public override bool MaintainsBuffer
{
get { return true; }
}
public override object MaintainedBuffer
{
get { return this.buffer; }
}
public override void Pin()
{
bufferHandle.Target = buffer;
this.Variants[this.Index].byteArrayValue.intPtr = bufferHandle.AddrOfPinnedObject();
}
public override void Unpin()
{
this.Variants[this.Index].byteArrayValue.intPtr = IntPtr.Zero;
bufferHandle.Target = null;
}
public byte[] GetBufferCopy(int length)
{
byte[] buffer = DiagnosticUtility.Utility.AllocateByteArray(length);
System.Buffer.BlockCopy(this.buffer, 0, buffer, 0, length);
return buffer;
}
public void EnsureBufferLength(int length)
{
if (this.buffer.Length < length)
{
SetBufferReference(DiagnosticUtility.Utility.AllocateByteArray(length));
}
}
public int BufferLength
{
get
{
return this.Variants[this.Index].byteArrayValue.size;
}
set
{
if (value > this.buffer.Length)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value"));
this.Variants[this.Index].byteArrayValue.size = value;
}
}
public byte[] Buffer
{
get
{
return this.buffer;
}
}
}
public class StringProperty : MsmqProperty
{
char[] buffer;
GCHandle bufferHandle;
internal StringProperty(NativeMsmqMessage message, int id, string value)
: this(message, id, value.Length + 1)
{
CopyValueToBuffer(value);
}
internal StringProperty(NativeMsmqMessage message, int id, int length)
: base(message, id, UnsafeNativeMethods.VT_LPWSTR)
{
this.buffer = DiagnosticUtility.Utility.AllocateCharArray(length);
this.bufferHandle = GCHandle.Alloc(null, GCHandleType.Pinned);
}
~StringProperty()
{
Dispose(false);
}
public override bool MaintainsBuffer
{
get { return true; }
}
public override object MaintainedBuffer
{
get { return this.buffer; }
}
public override void Pin()
{
this.bufferHandle.Target = buffer;
this.Variants[this.Index].intPtr = bufferHandle.AddrOfPinnedObject();
}
public override void Unpin()
{
this.Variants[this.Index].intPtr = IntPtr.Zero;
this.bufferHandle.Target = null;
}
public override void Dispose()
{
base.Dispose();
Dispose(true);
GC.SuppressFinalize(this);
}
void Dispose(bool disposing)
{
if (bufferHandle.IsAllocated)
bufferHandle.Free();
}
public void EnsureValueLength(int length)
{
if (length > this.buffer.Length)
{
this.buffer = DiagnosticUtility.Utility.AllocateCharArray(length);
}
}
public void SetValue(string value)
{
if (null == value)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value");
EnsureValueLength(value.Length + 1);
CopyValueToBuffer(value);
}
void CopyValueToBuffer(string value)
{
value.CopyTo(0, this.buffer, 0, value.Length);
this.buffer[value.Length] = '\0';
}
public string GetValue(int length)
{
if (length == 0)
{
return null;
}
else
{
return new string(this.buffer, 0, length - 1);
}
}
}
}
static class MsmqMessageId
{
const int guidSize = 16;
public static string ToString(byte[] messageId)
{
StringBuilder result = new StringBuilder();
byte[] guid = new byte[guidSize];
Array.Copy(messageId, guid, guidSize);
int id = BitConverter.ToInt32(messageId, guidSize);
result.Append((new Guid(guid)).ToString());
result.Append("\\");
result.Append(id);
return result.ToString();
}
public static byte[] FromString(string messageId)
{
string[] pieces = messageId.Split(new char[] { '\\' });
if (pieces.Length != 2)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.MsmqInvalidMessageId, messageId), "messageId"));
Guid guid;
if (!DiagnosticUtility.Utility.TryCreateGuid(pieces[0], out guid))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.MsmqInvalidMessageId, messageId), "messageId"));
}
int integerId;
try
{
integerId = Convert.ToInt32(pieces[1], CultureInfo.InvariantCulture);
}
catch (FormatException)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.MsmqInvalidMessageId, messageId), "messageId"));
}
byte[] bytes = new byte[UnsafeNativeMethods.PROPID_M_MSGID_SIZE];
Array.Copy(guid.ToByteArray(), bytes, guidSize);
Array.Copy(BitConverter.GetBytes(integerId), 0, bytes, guidSize, 4);
return bytes;
}
}
class MsmqEmptyMessage : NativeMsmqMessage
{
public MsmqEmptyMessage()
: base(0)
{ }
}
static class MsmqDuration
{
public static int FromTimeSpan(TimeSpan timeSpan)
{
long totalSeconds = (long)timeSpan.TotalSeconds;
if (totalSeconds > int.MaxValue)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
SR.GetString(SR.MsmqTimeSpanTooLarge)));
return (int)totalSeconds;
}
public static TimeSpan ToTimeSpan(int seconds)
{
return TimeSpan.FromSeconds(seconds);
}
}
static class MsmqDateTime
{
public static DateTime ToDateTime(int seconds)
{
return new DateTime(1970, 1, 1).AddSeconds(seconds);
}
}
}
| |
#region License
/*
* All content copyright Terracotta, Inc., unless otherwise indicated. 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.
*
*/
#endregion
using System;
namespace Quartz.Impl.Triggers
{
/// <summary>
/// A concrete <see cref="ITrigger" /> that is used to fire a <see cref="IJobDetail" />
/// at a given moment in time, and optionally repeated at a specified interval.
/// </summary>
/// <seealso cref="ITrigger" />
/// <seealso cref="ICronTrigger" />
/// <author>James House</author>
/// <author>Contributions by Lieven Govaerts of Ebitec Nv, Belgium.</author>
/// <author>Marko Lahma (.NET)</author>
[Serializable]
public class SimpleTriggerImpl : AbstractTrigger, ISimpleTrigger
{
/// <summary>
/// Used to indicate the 'repeat count' of the trigger is indefinite. Or in
/// other words, the trigger should repeat continually until the trigger's
/// ending timestamp.
/// </summary>
public const int RepeatIndefinitely = -1;
private const int YearToGiveupSchedulingAt = 2299;
private DateTimeOffset? nextFireTimeUtc;
private DateTimeOffset? previousFireTimeUtc;
private int repeatCount;
private TimeSpan repeatInterval = TimeSpan.Zero;
private int timesTriggered;
private bool complete = false;
/// <summary>
/// Create a <see cref="SimpleTriggerImpl" /> with no settings.
/// </summary>
public SimpleTriggerImpl()
{
}
/// <summary>
/// Create a <see cref="SimpleTriggerImpl" /> that will occur immediately, and
/// not repeat.
/// </summary>
public SimpleTriggerImpl(string name) : this(name, null)
{
}
/// <summary>
/// Create a <see cref="SimpleTriggerImpl" /> that will occur immediately, and
/// not repeat.
/// </summary>
public SimpleTriggerImpl(string name, string group)
: this(name, group, SystemTime.UtcNow(), null, 0, TimeSpan.Zero)
{
}
/// <summary>
/// Create a <see cref="SimpleTriggerImpl" /> that will occur immediately, and
/// repeat at the the given interval the given number of times.
/// </summary>
public SimpleTriggerImpl(string name, int repeatCount, TimeSpan repeatInterval)
: this(name, null, repeatCount, repeatInterval)
{
}
/// <summary>
/// Create a <see cref="SimpleTriggerImpl" /> that will occur immediately, and
/// repeat at the the given interval the given number of times.
/// </summary>
public SimpleTriggerImpl(string name, string group, int repeatCount, TimeSpan repeatInterval)
: this(name, group, SystemTime.UtcNow(), null, repeatCount, repeatInterval)
{
}
/// <summary>
/// Create a <see cref="SimpleTriggerImpl" /> that will occur at the given time,
/// and not repeat.
/// </summary>
public SimpleTriggerImpl(string name, DateTimeOffset startTimeUtc)
: this(name, null, startTimeUtc)
{
}
/// <summary>
/// Create a <see cref="SimpleTriggerImpl" /> that will occur at the given time,
/// and not repeat.
/// </summary>
public SimpleTriggerImpl(string name, string group, DateTimeOffset startTimeUtc)
: this(name, group, startTimeUtc, null, 0, TimeSpan.Zero)
{
}
/// <summary>
/// Create a <see cref="SimpleTriggerImpl" /> that will occur at the given time,
/// and repeat at the the given interval the given number of times, or until
/// the given end time.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="startTimeUtc">A UTC <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" /> to fire.</param>
/// <param name="endTimeUtc">A UTC <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" />
/// to quit repeat firing.</param>
/// <param name="repeatCount">The number of times for the <see cref="ITrigger" /> to repeat
/// firing, use <see cref="RepeatIndefinitely "/> for unlimited times.</param>
/// <param name="repeatInterval">The time span to pause between the repeat firing.</param>
public SimpleTriggerImpl(string name, DateTimeOffset startTimeUtc,
DateTimeOffset? endTimeUtc, int repeatCount, TimeSpan repeatInterval)
: this(name, null, startTimeUtc, endTimeUtc, repeatCount, repeatInterval)
{
}
/// <summary>
/// Create a <see cref="SimpleTriggerImpl" /> that will occur at the given time,
/// and repeat at the the given interval the given number of times, or until
/// the given end time.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="group">The group.</param>
/// <param name="startTimeUtc">A UTC <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" /> to fire.</param>
/// <param name="endTimeUtc">A UTC <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" />
/// to quit repeat firing.</param>
/// <param name="repeatCount">The number of times for the <see cref="ITrigger" /> to repeat
/// firing, use <see cref="RepeatIndefinitely "/> for unlimited times.</param>
/// <param name="repeatInterval">The time span to pause between the repeat firing.</param>
public SimpleTriggerImpl(string name, string group, DateTimeOffset startTimeUtc,
DateTimeOffset? endTimeUtc, int repeatCount, TimeSpan repeatInterval)
: base(name, group)
{
StartTimeUtc = startTimeUtc;
EndTimeUtc = endTimeUtc;
RepeatCount = repeatCount;
RepeatInterval = repeatInterval;
}
/// <summary>
/// Create a <see cref="SimpleTriggerImpl" /> that will occur at the given time,
/// fire the identified <see cref="IJob" /> and repeat at the the given
/// interval the given number of times, or until the given end time.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="group">The group.</param>
/// <param name="jobName">Name of the job.</param>
/// <param name="jobGroup">The job group.</param>
/// <param name="startTimeUtc">A <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" />
/// to fire.</param>
/// <param name="endTimeUtc">A <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" />
/// to quit repeat firing.</param>
/// <param name="repeatCount">The number of times for the <see cref="ITrigger" /> to repeat
/// firing, use RepeatIndefinitely for unlimited times.</param>
/// <param name="repeatInterval">The time span to pause between the repeat firing.</param>
public SimpleTriggerImpl(string name, string group, string jobName, string jobGroup, DateTimeOffset startTimeUtc,
DateTimeOffset? endTimeUtc,
int repeatCount, TimeSpan repeatInterval)
: base(name, group, jobName, jobGroup)
{
StartTimeUtc = startTimeUtc;
EndTimeUtc = endTimeUtc;
RepeatCount = repeatCount;
RepeatInterval = repeatInterval;
}
/// <summary>
/// Get or set thhe number of times the <see cref="SimpleTriggerImpl" /> should
/// repeat, after which it will be automatically deleted.
/// </summary>
/// <seealso cref="RepeatIndefinitely" />
public int RepeatCount
{
get { return repeatCount; }
set
{
if (value < 0 && value != RepeatIndefinitely)
{
throw new ArgumentException("Repeat count must be >= 0, use the constant RepeatIndefinitely for infinite.");
}
repeatCount = value;
}
}
/// <summary>
/// Get or set the the time interval at which the <see cref="ISimpleTrigger" /> should repeat.
/// </summary>
public TimeSpan RepeatInterval
{
get { return repeatInterval; }
set
{
if (value < TimeSpan.Zero)
{
throw new ArgumentException("Repeat interval must be >= 0");
}
repeatInterval = value;
}
}
/// <summary>
/// Get or set the number of times the <see cref="ISimpleTrigger" /> has already
/// fired.
/// </summary>
public virtual int TimesTriggered
{
get { return timesTriggered; }
set { timesTriggered = value; }
}
public TriggerBuilder GetTriggerBuilder()
{
return GetTriggerBuilder<ISimpleTrigger>();
}
public override IScheduleBuilder GetScheduleBuilder()
{
SimpleScheduleBuilder sb = SimpleScheduleBuilder.Create()
.WithInterval(RepeatInterval)
.WithRepeatCount(RepeatCount);
switch (MisfireInstruction)
{
case Quartz.MisfireInstruction.SimpleTrigger.FireNow: sb.WithMisfireHandlingInstructionFireNow();
break;
case Quartz.MisfireInstruction.SimpleTrigger.RescheduleNextWithExistingCount: sb.WithMisfireHandlingInstructionNextWithExistingCount();
break;
case Quartz.MisfireInstruction.SimpleTrigger.RescheduleNextWithRemainingCount : sb.WithMisfireHandlingInstructionNextWithRemainingCount();
break;
case Quartz.MisfireInstruction.SimpleTrigger.RescheduleNowWithExistingRepeatCount : sb.WithMisfireHandlingInstructionNowWithExistingCount();
break;
case Quartz.MisfireInstruction.SimpleTrigger.RescheduleNowWithRemainingRepeatCount: sb.WithMisfireHandlingInstructionNowWithRemainingCount();
break;
}
return sb;
}
/// <summary>
/// Returns the final UTC time at which the <see cref="ISimpleTrigger" /> will
/// fire, if repeatCount is RepeatIndefinitely, null will be returned.
/// <para>
/// Note that the return time may be in the past.
/// </para>
/// </summary>
public override DateTimeOffset? FinalFireTimeUtc
{
get
{
if (repeatCount == 0)
{
return StartTimeUtc;
}
if (repeatCount == RepeatIndefinitely && !EndTimeUtc.HasValue)
{
return null;
}
if (repeatCount == RepeatIndefinitely && !EndTimeUtc.HasValue)
{
return null;
}
else if (repeatCount == RepeatIndefinitely)
{
return GetFireTimeBefore(EndTimeUtc);
}
DateTimeOffset lastTrigger = StartTimeUtc.AddMilliseconds(repeatCount * repeatInterval.TotalMilliseconds);
if (!EndTimeUtc.HasValue || lastTrigger < EndTimeUtc.Value)
{
return lastTrigger;
}
else
{
return GetFireTimeBefore(EndTimeUtc);
}
}
}
/// <summary>
/// Tells whether this Trigger instance can handle events
/// in millisecond precision.
/// </summary>
/// <value></value>
public override bool HasMillisecondPrecision
{
get { return true; }
}
/// <summary>
/// Validates the misfire instruction.
/// </summary>
/// <param name="misfireInstruction">The misfire instruction.</param>
/// <returns></returns>
protected override bool ValidateMisfireInstruction(int misfireInstruction)
{
if (misfireInstruction < Quartz.MisfireInstruction.IgnoreMisfirePolicy)
{
return false;
}
if (misfireInstruction > Quartz.MisfireInstruction.SimpleTrigger.RescheduleNextWithExistingCount)
{
return false;
}
return true;
}
/// <summary>
/// Updates the <see cref="ISimpleTrigger" />'s state based on the
/// MisfireInstruction value that was selected when the <see cref="ISimpleTrigger" />
/// was created.
/// </summary>
/// <remarks>
/// If MisfireSmartPolicyEnabled is set to true,
/// then the following scheme will be used: <br />
/// <ul>
/// <li>If the Repeat Count is 0, then the instruction will
/// be interpreted as <see cref="MisfireInstruction.SimpleTrigger.FireNow" />.</li>
/// <li>If the Repeat Count is <see cref="RepeatIndefinitely" />, then
/// the instruction will be interpreted as <see cref="MisfireInstruction.SimpleTrigger.RescheduleNowWithRemainingRepeatCount" />.
/// <b>WARNING:</b> using MisfirePolicy.SimpleTrigger.RescheduleNowWithRemainingRepeatCount
/// with a trigger that has a non-null end-time may cause the trigger to
/// never fire again if the end-time arrived during the misfire time span.
/// </li>
/// <li>If the Repeat Count is > 0, then the instruction
/// will be interpreted as <see cref="MisfireInstruction.SimpleTrigger.RescheduleNowWithExistingRepeatCount" />.
/// </li>
/// </ul>
/// </remarks>
public override void UpdateAfterMisfire(ICalendar cal)
{
int instr = MisfireInstruction;
if (instr == Quartz.MisfireInstruction.SmartPolicy)
{
if (RepeatCount == 0)
{
instr = Quartz.MisfireInstruction.SimpleTrigger.FireNow;
}
else if (RepeatCount == RepeatIndefinitely)
{
instr = Quartz.MisfireInstruction.SimpleTrigger.RescheduleNextWithRemainingCount;
}
else
{
instr = Quartz.MisfireInstruction.SimpleTrigger.RescheduleNowWithExistingRepeatCount;
}
}
else if (instr == Quartz.MisfireInstruction.SimpleTrigger.FireNow && RepeatCount != 0)
{
instr = Quartz.MisfireInstruction.SimpleTrigger.RescheduleNowWithRemainingRepeatCount;
}
if (instr == Quartz.MisfireInstruction.SimpleTrigger.FireNow)
{
nextFireTimeUtc = SystemTime.UtcNow();
}
else if (instr == Quartz.MisfireInstruction.SimpleTrigger.RescheduleNextWithExistingCount)
{
DateTimeOffset? newFireTime = GetFireTimeAfter(SystemTime.UtcNow());
while (newFireTime.HasValue && cal != null && !cal.IsTimeIncluded(newFireTime.Value))
{
newFireTime = GetFireTimeAfter(newFireTime);
if (!newFireTime.HasValue)
{
break;
}
//avoid infinite loop
if (newFireTime.Value.Year > YearToGiveupSchedulingAt)
{
newFireTime = null;
}
}
nextFireTimeUtc = newFireTime;
}
else if (instr == Quartz.MisfireInstruction.SimpleTrigger.RescheduleNextWithRemainingCount)
{
DateTimeOffset? newFireTime = GetFireTimeAfter(SystemTime.UtcNow());
while (newFireTime.HasValue && cal != null && !cal.IsTimeIncluded(newFireTime.Value))
{
newFireTime = GetFireTimeAfter(newFireTime);
if (!newFireTime.HasValue)
{
break;
}
//avoid infinite loop
if (newFireTime.Value.Year > YearToGiveupSchedulingAt)
{
newFireTime = null;
}
}
if (newFireTime.HasValue)
{
int timesMissed = ComputeNumTimesFiredBetween(nextFireTimeUtc, newFireTime);
TimesTriggered = TimesTriggered + timesMissed;
}
nextFireTimeUtc = newFireTime;
}
else if (instr == Quartz.MisfireInstruction.SimpleTrigger.RescheduleNowWithExistingRepeatCount)
{
DateTimeOffset newFireTime = SystemTime.UtcNow();
if (repeatCount != 0 && repeatCount != RepeatIndefinitely)
{
RepeatCount = RepeatCount - TimesTriggered;
TimesTriggered = 0;
}
if (EndTimeUtc.HasValue && EndTimeUtc.Value < newFireTime)
{
nextFireTimeUtc = null; // We are past the end time
}
else
{
StartTimeUtc = newFireTime;
nextFireTimeUtc = newFireTime;
}
}
else if (instr == Quartz.MisfireInstruction.SimpleTrigger.RescheduleNowWithRemainingRepeatCount)
{
DateTimeOffset newFireTime = SystemTime.UtcNow();
int timesMissed = ComputeNumTimesFiredBetween(nextFireTimeUtc, newFireTime);
if (repeatCount != 0 && repeatCount != RepeatIndefinitely)
{
int remainingCount = RepeatCount - (TimesTriggered + timesMissed);
if (remainingCount <= 0)
{
remainingCount = 0;
}
RepeatCount = remainingCount;
TimesTriggered = 0;
}
if (EndTimeUtc.HasValue && EndTimeUtc.Value < newFireTime)
{
nextFireTimeUtc = null; // We are past the end time
}
else
{
StartTimeUtc = newFireTime;
nextFireTimeUtc = newFireTime;
}
}
}
/// <summary>
/// Called when the <see cref="IScheduler" /> has decided to 'fire'
/// the trigger (Execute the associated <see cref="IJob" />), in order to
/// give the <see cref="ITrigger" /> a chance to update itself for its next
/// triggering (if any).
/// </summary>
/// <seealso cref="JobExecutionException" />
public override void Triggered(ICalendar cal)
{
timesTriggered++;
previousFireTimeUtc = nextFireTimeUtc;
nextFireTimeUtc = GetFireTimeAfter(nextFireTimeUtc);
while (nextFireTimeUtc.HasValue && cal != null && !cal.IsTimeIncluded(nextFireTimeUtc.Value))
{
nextFireTimeUtc = GetFireTimeAfter(nextFireTimeUtc);
if (!nextFireTimeUtc.HasValue)
{
break;
}
//avoid infinite loop
if (nextFireTimeUtc.Value.Year > YearToGiveupSchedulingAt)
{
nextFireTimeUtc = null;
}
}
}
/// <summary>
/// Updates the instance with new calendar.
/// </summary>
/// <param name="calendar">The calendar.</param>
/// <param name="misfireThreshold">The misfire threshold.</param>
public override void UpdateWithNewCalendar(ICalendar calendar, TimeSpan misfireThreshold)
{
nextFireTimeUtc = GetFireTimeAfter(previousFireTimeUtc);
if (nextFireTimeUtc == null || calendar == null)
{
return;
}
DateTimeOffset now = SystemTime.UtcNow();
while (nextFireTimeUtc.HasValue && !calendar.IsTimeIncluded(nextFireTimeUtc.Value))
{
nextFireTimeUtc = GetFireTimeAfter(nextFireTimeUtc);
if (!nextFireTimeUtc.HasValue)
{
break;
}
//avoid infinite loop
if (nextFireTimeUtc.Value.Year > YearToGiveupSchedulingAt)
{
nextFireTimeUtc = null;
}
if (nextFireTimeUtc != null && nextFireTimeUtc.Value < now)
{
TimeSpan diff = now - nextFireTimeUtc.Value;
if (diff >= misfireThreshold)
{
nextFireTimeUtc = GetFireTimeAfter(nextFireTimeUtc);
}
}
}
}
/// <summary>
/// Called by the scheduler at the time a <see cref="ITrigger" /> is first
/// added to the scheduler, in order to have the <see cref="ITrigger" />
/// compute its first fire time, based on any associated calendar.
/// <para>
/// After this method has been called, <see cref="GetNextFireTimeUtc" />
/// should return a valid answer.
/// </para>
/// </summary>
/// <returns>
/// The first time at which the <see cref="ITrigger" /> will be fired
/// by the scheduler, which is also the same value <see cref="GetNextFireTimeUtc" />
/// will return (until after the first firing of the <see cref="ITrigger" />).
/// </returns>
public override DateTimeOffset? ComputeFirstFireTimeUtc(ICalendar cal)
{
nextFireTimeUtc = StartTimeUtc;
while (cal != null && !cal.IsTimeIncluded(nextFireTimeUtc.Value))
{
nextFireTimeUtc = GetFireTimeAfter(nextFireTimeUtc);
if (!nextFireTimeUtc.HasValue)
{
break;
}
//avoid infinite loop
if (nextFireTimeUtc.Value.Year > YearToGiveupSchedulingAt)
{
return null;
}
}
return nextFireTimeUtc;
}
/// <summary>
/// Returns the next time at which the <see cref="ISimpleTrigger" /> will
/// fire. If the trigger will not fire again, <see langword="null" /> will be
/// returned. The value returned is not guaranteed to be valid until after
/// the <see cref="ITrigger" /> has been added to the scheduler.
/// </summary>
public override DateTimeOffset? GetNextFireTimeUtc()
{
return nextFireTimeUtc;
}
public override void SetNextFireTimeUtc(DateTimeOffset? nextFireTime)
{
nextFireTimeUtc = nextFireTime;
}
public override void SetPreviousFireTimeUtc(DateTimeOffset? previousFireTime)
{
previousFireTimeUtc = previousFireTime;
}
/// <summary>
/// Returns the previous time at which the <see cref="ISimpleTrigger" /> fired.
/// If the trigger has not yet fired, <see langword="null" /> will be
/// returned.
/// </summary>
public override DateTimeOffset? GetPreviousFireTimeUtc()
{
return previousFireTimeUtc;
}
/// <summary>
/// Returns the next UTC time at which the <see cref="ISimpleTrigger" /> will
/// fire, after the given UTC time. If the trigger will not fire after the given
/// time, <see langword="null" /> will be returned.
/// </summary>
public override DateTimeOffset? GetFireTimeAfter(DateTimeOffset? afterTimeUtc)
{
if (complete)
{
return null;
}
if ((timesTriggered > repeatCount) && (repeatCount != RepeatIndefinitely))
{
return null;
}
if (!afterTimeUtc.HasValue)
{
afterTimeUtc = SystemTime.UtcNow();
}
if (repeatCount == 0 && afterTimeUtc.Value.CompareTo(StartTimeUtc) >= 0)
{
return null;
}
DateTimeOffset startMillis = StartTimeUtc;
DateTimeOffset afterMillis = afterTimeUtc.Value;
DateTimeOffset endMillis = !EndTimeUtc.HasValue ? DateTimeOffset.MaxValue : EndTimeUtc.Value;
if (endMillis <= afterMillis)
{
return null;
}
if (afterMillis < startMillis)
{
return startMillis;
}
long numberOfTimesExecuted = (long) (((long) (afterMillis - startMillis).TotalMilliseconds / repeatInterval.TotalMilliseconds) + 1);
if ((numberOfTimesExecuted > repeatCount) &&
(repeatCount != RepeatIndefinitely))
{
return null;
}
DateTimeOffset time = startMillis.AddMilliseconds(numberOfTimesExecuted * repeatInterval.TotalMilliseconds);
if (endMillis <= time)
{
return null;
}
return time;
}
/// <summary>
/// Returns the last UTC time at which the <see cref="ISimpleTrigger" /> will
/// fire, before the given time. If the trigger will not fire before the
/// given time, <see langword="null" /> will be returned.
/// </summary>
public virtual DateTimeOffset? GetFireTimeBefore(DateTimeOffset? endUtc)
{
if (endUtc.Value < StartTimeUtc)
{
return null;
}
int numFires = ComputeNumTimesFiredBetween(StartTimeUtc, endUtc);
return StartTimeUtc.AddMilliseconds(numFires*repeatInterval.TotalMilliseconds);
}
/// <summary>
/// Computes the number of times fired between the two UTC date times.
/// </summary>
/// <param name="startTimeUtc">The UTC start date and time.</param>
/// <param name="endTimeUtc">The UTC end date and time.</param>
/// <returns></returns>
public virtual int ComputeNumTimesFiredBetween(DateTimeOffset? startTimeUtc, DateTimeOffset? endTimeUtc)
{
long time = (long) (endTimeUtc.Value - startTimeUtc.Value).TotalMilliseconds;
return (int) (time/repeatInterval.TotalMilliseconds);
}
/// <summary>
/// Determines whether or not the <see cref="ISimpleTrigger" /> will occur
/// again.
/// </summary>
public override bool GetMayFireAgain()
{
return GetNextFireTimeUtc().HasValue;
}
/// <summary>
/// Validates whether the properties of the <see cref="IJobDetail" /> are
/// valid for submission into a <see cref="IScheduler" />.
/// </summary>
public override void Validate()
{
base.Validate();
if (repeatCount != 0 && repeatInterval.TotalMilliseconds < 1)
{
throw new SchedulerException("Repeat Interval cannot be zero.");
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.